OOP
Q1: Vending Machine
In this question you'll create a vending machine that only outputs a single product and provides change when needed.
Create a class called
VendingMachine
that represents a vending machine for some product. AVendingMachine
object returns strings describing its interactions. Remember to match exactly the strings in the doctests -- including punctuation and spacing!Fill in the
VendingMachine
class, adding attributes and methods as appropriate, such that its behavior matches the following doctests:
According to the wiki, a vending machine is an automated machine that provides items to consumers after cash, or other forms of payment are inserted into the machine or otherwise made
這里說的 vending machine 其實也就是常見的自動售貨機, 我們要為其寫一個類實現應該有的功能. 這里的要求更為簡單, 因為我們要實現的自動售貨機只有一樣東西可以賣, 而且每次只會買一件. 注意下面要實現函數的邏輯即可:
restock
, 補充商品, 這個比較簡單add_funds
- 商品有庫存的時候才會記住你付了多少錢
- 商品沒有庫存的時候直接退款給你
vend
- 商品有庫存的時候
- 你支付的錢💰如果足夠就可以買
- 💰 不夠的話會告訴你還差多少錢
- 不要忘記購買成功后庫存要 - 1
- 商品沒有庫存
- 提示要補充貨物
- 商品有庫存的時候
class VendingMachine:
"""A vending machine that vends some product for some price.
"""
def __init__(self, product, price):
self.product = product
self.price = price
self.balance = 0
self.stocks = 0
def restock(self, num):
"""Restock num items to our vending machine"""
self.stocks += num
return f"Current {self.product} stock: {self.stocks}"
def add_funds(self, fund):
"""Add funds to balance, return funds if no stocks"""
if self.stocks != 0:
self.balance += fund
return f"Current balance: ${self.balance}"
else:
return f"Nothing left to vend. Please restock. Here is your ${fund}."
def vend(self):
"""Vend a product"""
if self.stocks == 0:
return 'Nothing left to vend. Please restock.'
else:
if self.balance < self.price:
return f"You must add ${self.price - self.balance} more funds."
else:
change = self.balance - self.price
self.balance = 0
self.stocks -= 1
if change == 0:
return f"Here is your {self.product}."
else:
return f"Here is your {self.product} and ${change} change."
Q2: Mint
A mint is a place where coins are made. In this question, you'll implement a
Mint
class that can output aCoin
with the correct year and worth.
- Each
Mint
instance has ayear
stamp. Theupdate
method sets theyear
stamp to thepresent_year
class attribute of theMint
class.- The
create
method takes a subclass ofCoin
and returns an instance of that class stamped with themint
's year (which may be different fromMint.present_year
if it has not been updated.)- A
Coin
'sworth
method returns thecents
value of the coin plus one extra cent for each year of age beyond 50. A coin's age can be determined by subtracting the coin's year from thepresent_year
class attribute of theMint
class.
這一題要我們實現鑄幣廠的類, 可以制造出年份和面值都正確的硬幣.
class Mint:
"""A mint creates coins by stamping on years.
"""
present_year = 2021
def __init__(self):
self.update()
def create(self, kind):
return kind(self.year)
def update(self):
self.year = Mint.present_year
class Coin:
def __init__(self, year):
self.year = year
def worth(self):
age = Mint.present_year - self.year
if age > 50:
return self.cents + (age - 50)
else:
return self.cents
Linked Lists
Q3: Store Digits
Write a function
store_digits
that takes in an integern
and returns a linked list where each element of the list is a digit ofn
.Important: Do not use any string manipulation functions like
str
andreversed
簡單來說, 就是要把整數 n
的每一位存儲到鏈表里面. 這個用迭代的方法做就很簡單, 我們可以每次 %10
來獲得最后一位, 采用鏈表的頭插法來構建鏈表, 頭插法就是每次我們都新建結點插入到鏈表的開頭. 這里用了哨兵結點.
def store_digits(n):
"""Stores the digits of a positive number n in a linked list.
"""
sentinel = Link(0)
while n > 0:
all_but_last, last = n // 10, n % 10
# every time we insert node in the front of the linklist
new_node = Link(n % 10, sentinel.rest)
sentinel.rest = new_node
n = all_but_last
return sentinel.rest
Q4: Mutable Mapping
Implement
deep_map_mut(fn, link)
, which applies a functionfn
onto all elements in the given linked listlink
. If an element is itself a linked list, applyfn
to each of its elements, and so on.Your implementation should mutate the original linked list. Do not create any new linked lists.
Hint: The built-in
isinstance
function may be useful.>>> s = Link(1, Link(2, Link(3, Link(4)))) >>> isinstance(s, Link) True >>> isinstance(s, int) False
對嵌套鏈表的每個元素應用 fn
函數, 顯然這個要用遞歸方法來解決. 具體解題思路可以看下面的代碼
def deep_map_mut(fn, link):
"""Mutates a deep link by replacing each item found with the
result of calling fn on the item. Does NOT create new Links (so
no use of Link's constructor)
"""
# base case 1. do thing if it is empty
if link is Link.empty:
return
# base case 2. if it is an integer
if isinstance(link, int):
link = fn(link)
if isinstance(link.first, int):
link.first = fn(link.first)
else:
deep_map_mut(fn, link.first)
deep_map_mut(fn, link.rest)
Q5: Two List
Implement a function
two_list
that takes in two lists and returns a linked list. The first list contains the values that we want to put in the linked list, and the second list contains the number of each corresponding value. Assume both lists are the same size and have a length of 1 or greater. Assume all elements in the second list are greater than 0.
有兩個列表: 一個表示值, 一個表示這個值應該重復插入幾次. 用這種方式構建一個鏈表, 用鏈表的尾插法即可(每次把新的節點插入到鏈表末尾). 這里同樣用了哨兵結點
def two_list(vals, amounts):
"""
Returns a linked list according to the two lists that were passed in. Assume
vals and amounts are the same size. Elements in vals represent the value, and the
corresponding element in amounts represents the number of this value desired in the
final linked list. Assume all elements in amounts are greater than 0. Assume both
lists have at least one element.
"""
idx = 0
sentinel = Link(0)
pos = sentinel
while idx < len(vals):
val, amount = vals[idx], amounts[idx]
for _ in range(amount):
new_node = Link(val)
pos.rest = new_node
pos = pos.rest
idx += 1
return sentinel.rest
Extra Questions
Q6: Next Virahanka Fibonacci Object
Implement the
next
method of theVirFib
class. For this class, thevalue
attribute is a Fibonacci number. Thenext
method returns aVirFib
instance whosevalue
is the next Fibonacci number. Thenext
method should take only constant time.Note that in the doctests, nothing is being printed out. Rather, each call to
.next()
returns aVirFib
instance. The way eachVirFib
instance is displayed is determined by the return value of its__repr__
method.Hint: Keep track of the previous number by setting a new instance attribute inside
next
. You can create new instance attributes for objects at any point, even outside the__init__
method.
這題要求我們寫一個類, 每次調用它的方法就可以算出下一個斐波那契數
Q7: Is BST
Write a function
is_bst
, which takes a Treet
and returnsTrue
if, and only if,t
is a valid binary search tree, which means that:
- Each node has at most two children (a leaf is automatically a valid binary search tree)
- The children are valid binary search trees
- For every node, the entries in that node's left child are less than or equal to the label of the node
- For every node, the entries in that node's right child are greater than the label of the node
An example of a BST is:
Note that, if a node has only one child, that child could be considered either the left or right child. You should take this into consideration.
Hint: It may be helpful to write helper functions
bst_min
andbst_max
that return the minimum and maximum, respectively, of a Tree if it is a valid binary search tree.
寫一個函數判斷輸入是否為二叉搜索樹, 根據提示我們需要先實現兩個輔助函數: bst_min
和 bst_max
, 返回輸入的樹的最小和最大值
寫代碼要注意下面幾點:
- 左子樹最小值 <= 當前節點. 而不是 <
- 當前節點如果只有一個子樹, 那么在那邊都可以, 這里要做兩種情況的判定
def is_bst(t):
"""Returns True if the Tree t has the structure of a valid BST.
"""
def bst_min(t):
"""Return the min value of the tree t"""
if t.is_leaf():
return t.label
sub_branch_min = min([bst_min(b) for b in t.branches])
return min(t.label, sub_branch_min)
def bst_max(t):
"""Return the max value of the tree t"""
if t.is_leaf():
return t.label
sub_branch_max = max([bst_max(b) for b in t.branches])
return max(t.label, sub_branch_max)
# base case 1. a leaf node is a BST
if t.is_leaf():
return True
# base case 2. each node has at most 2 children
if len(t.branches) > 2:
return False
# base case 3. a node with a single child
# it can be considered either the left or the right
if len(t.branches) == 1:
return (bst_max(t.branches[0]) < t.label or bst_min(t.branches[0]) > t.label) \
and is_bst(t.branches[0])
left_max = bst_max(t.branches[0])
right_min = bst_min(t.branches[1])
return left_max <= t.label < right_min and is_bst(t.branches[0]) and is_bst(t.branches[1])