-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstarter.py
executable file
·85 lines (65 loc) · 1.32 KB
/
starter.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
#!/bin/pypy
"""
STARTER CODE FOR CREATIVE CODING 6
"""
def head(xs):
return xs[0]
def tail(xs):
return xs[1::1]
def flatten(xs):
newList = []
for x in xs:
if isinstance(x, list):
for y in x:
newList.append(y)
else:
newList.append(x)
return newList
def cons(a, b):
return flatten([a,b])
#----------------------------------------------------
#YOUR CODE HERE
#Question 1
def fact(x):
if x <= 1:
return 1
return x * fact(x - 1)
#Question 2
def count(xs):
if tail(xs) == []:
return 1
return 1 + count(tail(xs))
#Question 3
def sumList(xs):
if tail(xs) == []:
return head(xs)
return head(xs) + sumList(tail(xs))
#Question 4
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
#Question 5
def take(xs, n):
if tail(xs) == [] or n == 1:
return head(xs)
return cons(head(xs), take(tail(xs), n - 1))
#Question 6
def drop(xs, n):
if tail(xs) == [] or n == 1:
return xs
return drop(tail(xs), n - 1)
#----------------------------------------------------
"""
EXAMPLES
"""
def printNums(x):
print(x)
if x <= 1:
return
printNums(x - 1)
def printList(xs):
print(head(xs))
if len(xs) == 1:
return
printList(tail(xs))