Given an array, find out the product of its element using recursion.
def product(arr):
"""
calculates the product of all the numbers in array
"""
if len(arr) == 0:
return 1
else:
return len(arr) * product(arr[1:])
product([1, 2, 3, 4, 5])
120
Given a string, write a function reverse
which accepts a string and returns a new string in reverse.
def reverse(string):
"""
returns the reverse of a string
"""
if len(string) == 0:
return ""
return string[-1] + reverse(string[:-1])
reverse("Hello")
'olleH'
Given a string, write a function reverse
to check whether the string is palindrome.
Note: You must use recursion
for this problem.
def reverse(string):
"""
returns the reverse of a string
"""
if len(string) == 0:
return ""
return string[-1] + reverse(string[:-1])
string = "malayalam"
string == reverse(string)
True
Given a nested array, write a function flatten
to return a flatlist
def flatten(arr):
"""
returns the flattened array.
"""
result = []
for element in arr:
if type(element) is list:
result.extend(flatten(element))
else:
result.append(element)
return result
flatten([[2, 3, [4]]])
[2, 3, 4]
Given a word list, write a function capitalize_first
to capitalize the first letter of each string in the array. Note, you must use recursion for this problem.
def capitalize_first(arr):
"""
converts the first letter of all the elements into uppercase.
"""
result = []
if len(arr) == 0:
return result
result.append(arr[0][0].upper() + arr[0][1:])
return result + capitalize_first(arr[1:])
capitalize_first(["hello", "world"])
['Hello', 'World']
Given a .json
object, write a function string_convert
which takes an object and finds all the values which are numbers and converts them into a string.
"value" : 8,
"jam" : {
"english": 50
}
}
}"value" : "8",
"jam" : {
"english": "50"
}
}
}def string_convert(obj):
"""
converts all the integer values inside of an object into a string.
"""
for element in obj:
if type(obj[element]) is int:
obj[element] = str(obj[element])
elif type(obj[element]) is dict:
obj[element] = string_convert(obj[element])
return obj
string_convert({
"num" : 1,
"data": {
"value" : 8,
"jam" : {
"english": 50
}
}
})
{'num': '1', 'data': {'value': '8', 'jam': {'english': '50'}}}
Given a .json
object, write a function fetch_str
which takes the object and finds all the keys that have string values. Note, you must use recursion
for this problem.
"England": {
"London": "Heathrow",
"Oxford":100,
"Stanford": {
"France": "Paris",
"Germany": {
"Berlin": "TU Berlin",
"Frankfurt": 1000
}
}
},
"India": 1}
def fetch_str(obj):
"""
Returns keys with integer values.
"""
result = []
for element in obj:
if type(obj[element]) is str:
result.append(element)
if type(obj[element]) is dict:
result.extend(fetch_str(obj[element]))
return result
fetch_str({"Hello": "World",
"England": {
"London": "Heathrow",
"Oxford":100,
"Stanford": {
"France": "Paris",
"Germany": {
"Berlin": "TU Berlin",
"Frankfurt": 1000
}
}
},
"India": 1})
['Hello', 'London', 'France', 'Berlin']