-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecursiveFunctions
108 lines (91 loc) · 2.2 KB
/
RecursiveFunctions
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
101
102
103
104
105
106
107
108
def recurPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
# Your code here
if exp == 0:
return 1
elif exp == 1:
return base
return (base*recurPower(base, exp-1))
def recurPowerNew(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float; base^exp
'''
# Your code here
if exp == 0:
return 1
elif (exp %2 == 1):
return base * recurPowerNew(base, exp-1)
return recurPowerNew(base * base, exp / 2)
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
for i in range(min(a,b)+1, 1, -1):
if (a%i == 0 and b%i == 0):
return i
return 1
def gcdRecur(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
Utiliza el algoritmo de Euclides
'''
# Your code here
if b == 0:
return a
return gcdRecur(b, a%b)
def lenIter(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
# Your code here
count = 0
for ch in aStr:
count += 1
return count
def lenRecur(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
# Your code here
if aStr == '':
return 0
return 1 + lenRecur(aStr[1:])
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Your code here
if aStr=='':
return False
elif char == aStr[len(aStr)/2]:
return True
elif char < aStr[len(aStr)/2]:
return isIn(char, aStr[:len(aStr)/2])
else:
return isIn(char, aStr[len(aStr)/2+1:])
def semordnilap(str1, str2):
'''
str1: a string
str2: a string
returns: True if str1 and str2 are semordnilap;
False otherwise.
'''
# Your code here
if str1=='' or str2=='':
if str1 != str2:
return False
return True
return str1[0]==str2[-1] and semordnilap(str1[1:],str2[:-1])