日拱一卒，伯克利教你学Python，CS61A作业6、7合集

·  阅读 837

Github

Next Fibonacci Object

`Fib`类中实现`next`函数，`value`属性是斐波那契数列的值。

`next`方法返回一个`Fib`的实例，这个实例中的值是斐波那契数列下一个值。`next`函数的复杂度必须是常数。

``````    >>> start = Fib()
>>> start
0
>>> start.next()
1
>>> start.next().next()
1
>>> start.next().next().next()
2
>>> start.next().next().next().next()
3
>>> start.next().next().next().next().next()
5
>>> start.next().next().next().next().next().next()
8
>>> start.next().next().next().next().next().next() # Ensure start isn't changed
8

``````class Fib():
"""A Fibonacci number.
"""

def __init__(self, value=0):
self.value = value

def next(self):

def __repr__(self):
return str(self.value)

``````def next(self):
ret = Fib(self.value + self.previous)
self.previous = self.value
return ret

``````class Fib():
"""A Fibonacci number.
"""

def __init__(self, value=0):
self.value = value

def next(self):
if self.value == 0:
ret = Fib(1)
else:
ret = Fib(self.previous + self.value)
self.previous = self.value
return ret

def __repr__(self):
return str(self.value)

Vending Machine

``````>>> v = VendingMachine('candy', 10)
>>> v.vend()
'Machine is out of stock.'
>>> v.deposit(15)
'Machine is out of stock. Here is your \$15.'
>>> v.restock(2)
'Current candy stock: 2'
>>> v.vend()
'You must deposit \$10 more.'
>>> v.deposit(7)
'Current balance: \$7'
>>> v.vend()
'You must deposit \$3 more.'
>>> v.deposit(5)
'Current balance: \$12'
>>> v.vend()
'Here is your candy and \$2 change.'
>>> v.deposit(10)
'Current balance: \$10'
>>> v.vend()
>>> v.deposit(15)
'Machine is out of stock. Here is your \$15.'

>>> w = VendingMachine('soda', 2)
>>> w.restock(3)
'Current soda stock: 3'
>>> w.restock(3)
'Current soda stock: 6'
>>> w.deposit(2)
'Current balance: \$2'
>>> w.vend()

``````class VendingMachine:
"""A vending machine that vends some product for some price.
"""
def __init__(self, item, price):
self.item = item
self.price = price
self.stock = 0
self.balance = 0

def restock(self, amount):
self.stock += amount
return 'Current {} stock: {}'.format(self.item, self.stock)

def deposit(self, amount):
if self.stock == 0:
return 'Machine is out of stock. Here is your \${}.'.format(amount)
self.balance += amount
return 'Current balance: \${}'.format(self.balance)

def vend(self):
if self.stock == 0:
return 'Machine is out of stock.'
if self.balance < self.price:
return 'You must deposit \${} more.'.format(self.price - self.balance)
else:
ret = 'Here is your {}{}'.format(self.item, '.' if self.balance == self.price else ' and \${} change.'.format(self.balance - self.price))
self.balance = 0
self.stock -= 1
return ret

Digits

``````    >>> digits(0) is Link.empty
True
>>> digits(543)

``````class Link:

>>> s.first
1
True
>>> s.second
3
>>> s.first = 5
>>> s.second = 6
>>> s                                    # Displays the contents of repr(s)
>>> s
>>> print(s)                             # Prints str(s)
<5 7 <8 9>>
"""
empty = ()

def __init__(self, first, rest=empty):
self.first = first
self.rest = rest

@property
def second(self):
return self.rest.first

@second.setter
def second(self, value):
self.rest.first = value

def __repr__(self):
rest_repr = ', ' + repr(self.rest)
else:
rest_repr = ''
return 'Link(' + repr(self.first) + rest_repr + ')'

def __str__(self):
string = '<'
string += str(self.first) + ' '
self = self.rest
return string + str(self.first) + '>'

``````def digits(n):
"""Return the digits of n as a linked list.

True
>>> digits(543)
"""
while n > 0:
n, last = n // 10, n % 10
return s

Miss Manners

`MissManners`对象的构造函数接受另外一个对象`object`，它有一个函数，叫做`ask`。通过`ask`函数可以调用`object`中的方法，但前提是必须在调用之前用上`please`表示礼貌。

``````>>> v = VendingMachine('teaspoon', 10)
>>> v.restock(2)
'Current teaspoon stock: 2'

>>> m = MissManners(v)
'You must learn to say please first.'
'You must deposit \$10 more.'
'Current balance: \$20'
'You must learn to say please first.'
'Thanks for asking, but I know not how to hand over a teaspoon.'
'Here is your teaspoon and \$10 change.'

>>> double_fussy = MissManners(m) # Composed MissManners objects
'You must learn to say please first.'
'Thanks for asking, but I know not how to deposit.'
'Current balance: \$10'

`VendingMachine`类也在之前的作业当中出现过，如果不清楚原理，下面也给出了完整代码。

``````class VendingMachine:
"""A vending machine that vends some product for some price.
"""
def __init__(self, product, price):
self.product = product
self.price = price
self.stock = 0
self.balance = 0

def restock(self, n):
self.stock += n
return 'Current {0} stock: {1}'.format(self.product, self.stock)

def deposit(self, n):
if self.stock == 0:
return 'Machine is out of stock. Here is your \${0}.'.format(n)
self.balance += n
return 'Current balance: \${0}'.format(self.balance)

def vend(self):
if self.stock == 0:
return 'Machine is out of stock.'
difference = self.price - self.balance
if difference > 0:
return 'You must deposit \${0} more.'.format(difference)
message = 'Here is your {0}'.format(self.product)
if difference != 0:
message += ' and \${0} change'.format(-difference)
self.balance = 0
self.stock -= 1
return message + '.'

class MissManners:
"""A container class that only forwards messages that say please.
"""
def __init__(self, obj):
self.obj = obj

if not message.startswith(magic_word):
return 'You must learn to say please first.'
left_message = message[len(magic_word):]
if hasattr(self.obj, left_message):
return getattr(self.obj, left_message)(*args)
else:
return 'Thanks for asking, but I know not how to {}.'.format(left_message)