-
Notifications
You must be signed in to change notification settings - Fork 0
/
exam_prep02.py
88 lines (71 loc) · 1.49 KB
/
exam_prep02.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
def kbonacci(n, k):
""" Return element N of a K-bonacci sequence
>>> kbonacci(3, 4)
1
>>> kbonacci(9,4)
29
>>> kbonacci(4,2)
3
>>> kbonacci(8,2)
21
"""
if n < k-1:
return 0
elif n==k-1:
return 1
else:
total = 0
i = n - k
while i<n:
total = total + kbonacci(i, k)
i += 1
return total
### Question 2
def combine(left, right):
factor = 1
while factor <= right:
factor = factor * 10
return left * factor + right
def reverse(n):
"""Return the digits of N in reverse
>>> reverse(122543)
345221
"""
if n<10:
return n
else:
return combine(n%10, reverse(n//10))
def remove(n, digit):
"""Return all digits of N that are not DIGIT,
for DIGIT less than 10.
>>> remove(243132,3)
2412
>>> remove(remove(2243132, 1), 2)
433
"""
removed = 0
while n != 0:
n, last = n//10, n%10
if last != digit:
removed = removed*10 + last
return reverse(removed)
### Question 3
square = lambda x: x*x
double = lambda x: 2*x
def memory(x, f):
"""Return a higher-order function that prints its memories.
>>> f = memory(3, lambda x: x)
>>> f = f(square)
3
>>> f = f(double)
9
>>> f = f(print)
6
>>> f = f(square)
3
None
"""
def g(h):
print(f(x))
return memory(x, h)
return g