程序代做 worksheet

worksheet

In [1]:

#q1
class Pet:
def __init__(self, name):
self.name = name # A

class Dog(Pet):
def __init__(self, name, age):
self.age = age
Pet.__init__(self, name) # B

pup = Dog(“Sam”, 1) # C

In [2]:

#q2a
def fact(n):
if n == 0:
return 1
return n * fact(n-1)

fact(5)

Out[2]:

120

In [3]:

#q2b
def fib(n):
if n < 2: return n return fib(n-1) + fib(n-2) fib(6) Out[3]: 8 In [4]: #q3a def f(n): print(n) if n < 9: f(n + 1) f(7) 7 8 9 In [5]: #q3b def g(n): if n < 9: g(n + 1) print(n) g(7) 9 8 7 In [6]: #q4a def M(n): print(n) if n > 1:
M(n-1)
print(n)

M(3)

3
2
1
2
3

In [7]:

#q4b
B = []
def h(A):
if len(A) > 0:
h(A[1:])
B.append(A[0])
h([2, 5, 6, 3])
B

Out[7]:

[3, 6, 5, 2]

In [8]:

#q5
class Node:
def __init__(self, val):
self.val = val
self.next = None

def tot(self):
if self.next != None:
return self.val
return self.val + self.next.tot()

def __getitem__(self, idx):
if idx == 0:
return self.val
return self.next[idx-1]

A = Node(3)
B = Node(5)
C = Node(7)
A.next = B
B.next = C