-
Notifications
You must be signed in to change notification settings - Fork 0
/
recursion.py
100 lines (98 loc) · 2.59 KB
/
recursion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
POWER SOLUTION
def power(base, exponent):
if exponent == 0:
return 1
return base * power(base, exponent-1)
FACTORIAL SOLUTION
def factorial(num):
if num <= 1:
return 1
return num * factorial(num-1)
PRODUCT OF ARRAY SOLUTION
def productOfArray(arr):
if len(arr) == 0:
return 1
return arr[0] * productOfArray(arr[1:])
RECURSIVE RANGE SOLUTION
def recursiveRange(num):
if num <= 0:
return 0
return num + recursiveRange(num - 1)
FIBONACCI SOLUTION
def fib(num):
if (num < 2):
return num
return fib(num - 1) + fib(num - 2)
REVERSE SOLUTION
def reverse(strng):
if len(strng) <= 1:
return strng
return strng[len(strng)-1] + reverse(strng[0:len(strng)-1])
IS PALINDROME SOLUTION
def isPalindrome(strng):
if len(strng) == 0:
return True
if strng[0] != strng[len(strng)-1]:
return False
return isPalindrome(strng[1:-1])
SOME RECURSIVE SOLUTION
def someRecursive(arr, cb):
if len(arr) == 0:
return False
if not(cb(arr[0])):
return someRecursive(arr[1:], cb)
return True
def isOdd(num):
if num%2==0:
return False
else:
return True
FLATTEN SOLUTION
def flatten(arr):
resultArr = []
for custItem in arr:
if type(custItem) is list:
resultArr.extend(flatten(custItem))
else:
resultArr.append(custItem)
return resultArr
CAPITALIZE FIRST SOLUTION
def capitalizeFirst(arr):
result = []
if len(arr) == 0:
return result
result.append(arr[0][0].upper() + arr[0][1:])
return result + capitalizeFirst(arr[1:])
NESTED EVEN SUM SOLUTION
def nestedEvenSum(obj, sum=0):
for key in obj:
if type(obj[key]) is dict:
sum += nestedEvenSum(obj[key])
elif type(obj[key]) is int and obj[key]%2==0:
sum+=obj[key]
return sum
CAPITALIZE WORDS SOLUTION
def capitalizeWords(arr):
result = []
if len(arr) == 0:
return result
result.append(arr[0].upper())
return result + capitalizeWords(arr[1:])
STRINGIFY NUMBERS SOLUTION
def stringifyNumbers(obj):
newObj = obj
for key in newObj:
if type(newObj[key]) is int:
newObj[key] = str(newObj[key])
if type(newObj[key]) is dict:
newObj[key] = stringifyNumbers(newObj[key])
return newObj
COLLECT STRINGS SOLUTION
def collectStrings(obj):
resultArr = []
for key in obj:
if type(obj[key]) is str:
resultArr.append(obj[key])
if type(obj[key]) is dict:
resultArr = resultArr + collectStrings(obj[key])
return resultArr