CS61A_未解决
def close(n, smallest=10, d=10): """ A sequence is near increasing if each element but the last two is smaller than all elements following its subsequent element. That is, element i must be smaller than elements i + 2, i + 3, i + 4, etc. Implement close, which takes a non-negative integer n and returns the largest near increasing sequence of digits within n as an integer. The arguments smallest and d are part of the implementation; you must determine their purpose. The only values you may use are integers and booleans (True and False) (no lists, strings, etc.). Return the longest sequence of near-increasing digits in n. >>> close(123) 123 >>> close(153) 153 >>> close(1523) 153 >>> close(15123) 1123 >>> close(11111111) 11 >>> close(985357) 557 >>> close(14735476) 143576 >>> close(812348567) 1234567 """ if n == 0: return ______ no = close(n//10, smallest, d) if smallest > ______: yes = ______ return ______(yes, no) return ___
答案:
def close(n, smallest=10, d=10): """ A sequence is near increasing if each element but the last two is smaller than all elements following its subsequent element. That is, element i must be smaller than elements i + 2, i + 3, i + 4, etc. Implement close, which takes a non-negative integer n and returns the largest near increasing sequence of digits within n as an integer. The arguments smallest and d are part of the implementation; you must determine their purpose. The only values you may use are integers and booleans (True and False) (no lists, strings, etc.). Return the longest sequence of near-increasing digits in n. >>> close(123) 123 >>> close(153) 153 >>> close(1523) 153 >>> close(15123) 1123 >>> close(11111111) 11 >>> close(985357) 557 >>> close(14735476) 143576 >>> close(812348567) 1234567 """ if n == 0: return 0 no = close(n//10, smallest, d) if smallest > n % 10: yes = 10 * close(n//10, d, min(d, n%10)) + n%10 return max(yes, no) return no
2.
def sums(n, k): """ Implement sums, which takes two positive integers n and k. It returns a list of lists containing all the ways that a list of k positive integers can sum to n. Results can appear in any order. Return the ways in which K positive integers can sum to N. >>> sums(2, 2) [[1, 1]] >>> sums(2, 3) [] >>> sums(4, 2) [[3, 1], [2, 2], [1, 3]] >>> sums(5, 3) [[3, 1, 1], [2, 2, 1], [1, 3, 1], [2, 1, 2], [1, 2, 2], [1, 1, 3]] """ if ______: return ______ y = [] for x in ______: y.extend([______ for s in sums(______)]) return y
answer
def sums(n, k): """ Implement sums, which takes two positive integers n and k. It returns a list of lists containing all the ways that a list of k positive integers can sum to n. Results can appear in any order. Return the ways in which K positive integers can sum to N. >>> sums(2, 2) [[1, 1]] >>> sums(2, 3) [] >>> sums(4, 2) [[3, 1], [2, 2], [1, 3]] >>> sums(5, 3) [[3, 1, 1], [2, 2, 1], [1, 3, 1], [2, 1, 2], [1, 2, 2], [1, 1, 3]] """ if k==1: return [[n]] y = [] for x in range(1, n): y.extend([ s + [x] for s in sums(n - x, k - 1)]) return y
3.
1 def longest_seq( tr ): 2 """ Given a tree, t, find the length of the longest downward sequence of node 3 labels in the tree that are increasing consecutive integers. The length of the 4 longest downward sequence of nodes in T whose labels are consecutive integers. 5 >>> t = Tree (1 , [ Tree (2) , Tree (1 , [ Tree (2 , [ Tree (3 , [ Tree (0)])])])]) 6 >>> longest_seq( t) # 1 -> 2 -> 3 7 3 8 >>> t = Tree (1) 9 >>> longest_seq( t) 10 1 11 """ 12 max_len = 1 13 def longest( t ): 14 """ Returns longest downward sequence of nodes starting at T whose 15 labels are consecutive integers. Updates max_len to that length , 16 if greater. """ 17 ______ 18 n = 1 19 if ______: 20 for ______ in ______: 21 ______ 22 if ______: 23 n = ______ 24 max_len = ______ 25 return n 26 longest(tr) 27 return max_len 28 29 ### Tree Class definition ### 30 class Tree: 31 def __init__(self, label, branches=[]): 32 self.label = label 33 for branch in branches: 34 assert isinstance(branch, Tree) 35 self.branches = list(branches) 36 37 def is_leaf(self): 38 r
answer
1 def longest_seq( tr ): 2 """ Given a tree, t, find the length of the longest downward sequence of node 3 labels in the tree that are increasing consecutive integers. The length of the 4 longest downward sequence of nodes in T whose labels are consecutive integers. 5 >>> t = Tree (1 , [ Tree (2) , Tree (1 , [ Tree (2 , [ Tree (3 , [ Tree (0)])])])]) 6 >>> longest_seq( t) # 1 -> 2 -> 3 7 3 8 >>> t = Tree (1) 9 >>> longest_seq( t) 10 1 11 """ 12 max_len = 1 13 def longest( t ): 14 """ Returns longest downward sequence of nodes starting at T whose 15 labels are consecutive integers. Updates max_len to that length , 16 if greater. """ 17 nonlocal max_len 18 n = 1 19 if not Tree.is_leaf( t ): 20 for branch in t.branches: 21 L=longest( branch ) 22 if branch.label==t.label+1: 23 n = max(n,L+1) 24 max_len = max(n,max_len) 25 return n 26 longest(tr) 27 return max_len
4.
1 def schedule(galaxy, sum_to, max_digit): 2 """ 3 A 'galaxy' is a string which contains either digits or '?'s. 4 5 A 'completion' of a galaxy is a string that is the same as galaxy, except 6 with digits replacing each of the '?'s. 7 8 Your task in this question is to find all completions of the given `galaxy` 9 that use digits up to `max_digit`, and whose digits sum to `sum_to`. 10 11 Note 1: the function int can be used to convert a string to an integer and str 12 can be used to convert an integer to a string as such: 13 14 >>> int("5") 15 5 16 >>> str(5) 17 '5' 18 19 Note 2: Indexing and slicing can be used on strings as well as on lists. 20 21 >>> 'evocative'[3] 22 'c' 23 >>> 'evocative'[3:] 24 'cative' 25 >>> 'evocative'[:6] 26 'evocat' 27 >>> 'evocative'[3:6] 28 'cat' 29 30 31 >>> schedule('?????', 25, 5) 32 ['55555'] 33 >>> schedule('???', 5, 2) 34 ['122', '212', '221'] 35 >>> schedule('?2??11?', 5, 3) 36 ['0200111', '0201110', '0210110', '1200110'] 37 """ 38 def schedule_helper(galaxy, sum_sofar, index): 39 if ______ and ______: 40 return [galaxy] 41 elif ______: 42 return [] 43 elif ______: 44 return ______ 45 ans = [] 46 for x in ______: 47 modified_galaxy = ______ 48 ______ 49 return ans 50 51 r
answer:
1 def schedule(galaxy, sum_to, max_digit): 2 """ 3 A 'galaxy' is a string which contains either digits or '?'s. 4 5 A 'completion' of a galaxy is a string that is the same as galaxy, except 6 with digits replacing each of the '?'s. 7 8 Your task in this question is to find all completions of the given `galaxy` 9 that use digits up to `max_digit`, and whose digits sum to `sum_to`. 10 11 Note 1: the function int can be used to convert a string to an integer and str 12 can be used to convert an integer to a string as such: 13 14 >>> int("5") 15 5 16 >>> str(5) 17 '5' 18 19 Note 2: Indexing and slicing can be used on strings as well as on lists. 20 21 >>> 'evocative'[3] 22 'c' 23 >>> 'evocative'[3:] 24 'cative' 25 >>> 'evocative'[:6] 26 'evocat' 27 >>> 'evocative'[3:6] 28 'cat' 29 30 31 >>> schedule('?????', 25, 5) 32 ['55555'] 33 >>> schedule('???', 5, 2) 34 ['122', '212', '221'] 35 >>> schedule('?2??11?', 5, 3) 36 ['0200111', '0201110', '0210110', '1200110'] 37 """ 38 def schedule_helper(galaxy, sum_sofar, index): 39 if index>=len(galaxy) and sum_sofar==sum_to: 40 return [galaxy] 41 elif index>=len(galaxy) and sum_sofar>sum_to: 42 return [] 43 elif galaxy[index]!='?': 44 return schedule_helper(galaxy,sum_sofar+int(galaxy[index]),index+1) 45 ans = [] 46 for x in range(max_digit+1): 47 modified_galaxy = galaxy[:index]+str(x)+galaxy[index+1:] 48 ans+=schedule_helper(modified_galaxy,sum_sofar+x,index+1) 49 return ans 50 51 return schedule_helper(galaxy,0 , 0)
5.
1 def lemon(xv): 2 """ 3 A lemon-copy is a perfect replica of a nested list's box-and-pointer structure. 4 If an environment diagram were drawn out, the two should be entirely 5 separate but identical. 6 7 A `xv` is a list that only contains ints and other lists. 8 9 The function `lemon` generates a lemon-copy of the given list `xv`. 10 11 Note: The `isinstance` function takes in a value and a type and determines 12 whether the value is of the given type. So 13 14 >>> isinstance("abc", str) 15 True 16 >>> isinstance("abc", list) 17 False 18 19 Here's an example, where lemon_y = lemon(y) 20 21 22 +-----+-----+ +-----+-----+-----+ 23 | | | | | | | 24 | + | +-------------> | 200 | 300 | + | 25 y +----------------> | | | | | | | | | 26 +-----+-----+ +--> +-----+-----+-----+ 27 lemon_y +-+ | | ^ | 28 | +----------------+ | | 29 | +-----------+ 30 | 31 | +-----+-----+ +-----+-----+-----+ 32 | | | | | | | | 33 +-------> | + | +-------------> | 200 | 300 | + | 34 | | | | | | | | | 35 +-----+-----+ +--> +-----+-----+-----+ 36 | | ^ | 37 +----------------+ | | 38 +-----------+ 39 40 >>> x = [200, 300] 41 >>> x.append(x) 42 >>> y = [x, x] # this is the `y` from the doctests 43 >>> lemon_y = lemon(y) # this is the `lemon_y` from the doctests 44 >>> # check that lemon_y has the same structure as y 45 >>> len(lemon_y) 46 2 47 >>> lemon_y[0] is lemon_y[1] 48 True 49 >>> len(lemon_y[0]) 50 3 51 >>> lemon_y[0][0] 52 200 53 >>> lemon_y[0][1] 54 300 55 >>> lemon_y[0][2] is lemon_y[0] 56 True 57 >>> # check that lemon_y and y have no list objects in common 58 >>> lemon_y is y 59 False 60 >>> lemon_y[0] is y[0] 61 False 62 """ 63 lemon_lookup = [] 64 def helper(xv): 65 if ______: 66 return ______ 67 for old_new in ______: 68 if ______: 69 return old_new[1] 70 new_xv = [] 71 lemon_lookup.append((xv, new_xv)) 72 for element in ______: 73 ______ 74 return new_xv 75 return helper(xv)
answer
1 email = 'example_key' 2 3 def lemon(xv): 4 """ 5 A lemon-copy is a perfect replica of a nested list's box-and-pointer structure. 6 If an environment diagram were drawn out, the two should be entirely 7 separate but identical. 8 9 A `xv` is a list that only contains ints and other lists. 10 11 The function `lemon` generates a lemon-copy of the given list `xv`. 12 13 Note: The `isinstance` function takes in a value and a type and determines 14 whether the value is of the given type. So 15 16 >>> isinstance("abc", str) 17 True 18 >>> isinstance("abc", list) 19 False 20 21 Here's an example, where lemon_y = lemon(y) 22 23 24 +-----+-----+ +-----+-----+-----+ 25 | | | | | | | 26 | + | +-------------> | 200 | 300 | + | 27 y +----------------> | | | | | | | | | 28 +-----+-----+ +--> +-----+-----+-----+ 29 lemon_y +-+ | | ^ | 30 | +----------------+ | | 31 | +-----------+ 32 | 33 | +-----+-----+ +-----+-----+-----+ 34 | | | | | | | | 35 +-------> | + | +-------------> | 200 | 300 | + | 36 | | | | | | | | | 37 +-----+-----+ +--> +-----+-----+-----+ 38 | | ^ | 39 +----------------+ | | 40 +-----------+ 41 42 >>> x = [200, 300] 43 >>> x.append(x) 44 >>> y = [x, x] # this is the `y` from the doctests 45 >>> lemon_y = lemon(y) # this is the `lemon_y` from the doctests 46 >>> # check that lemon_y has the same structure as y 47 >>> len(lemon_y) 48 2 49 >>> lemon_y[0] is lemon_y[1] 50 True 51 >>> len(lemon_y[0]) 52 3 53 >>> lemon_y[0][0] 54 200 55 >>> lemon_y[0][1] 56 300 57 >>> lemon_y[0][2] is lemon_y[0] 58 True 59 >>> # check that lemon_y and y have no list objects in common 60 >>> lemon_y is y 61 False 62 >>> lemon_y[0] is y[0] 63 False 64 """ 65 lemon_lookup = [] 66 def helper(xv): 67 if isinstance(xv, int): 68 return xv 69 for old_new in lemon_lookup: 70 if old_new[0] is xv: 71 return old_new[1] 72 new_xv = [] 73 lemon_lookup.append((xv, new_xv)) 74 for element in xv: 75 new_xv.append(helper(element)) 76 return new_xv 77 return helper(xv)
6.
1 def copycat(lst1, lst2): 2 """ 3 Write a function `copycat` that takes in two lists. 4 `lst1` is a list of strings 5 `lst2` is a list of integers 6 7 It returns a new list where every element from `lst1` is copied the 8 number of times as the corresponding element in `lst2`. If the number 9 of times to be copied is negative (-k), then it removes the previous 10 k elements added. 11 12 Note 1: `lst1` and `lst2` do not have to be the same length, simply ignore 13 any extra elements in the longer list. 14 15 Note 2: you can assume that you will never be asked to delete more 16 elements than exist 17 18 19 >>> copycat(['a', 'b', 'c'], [1, 2, 3]) 20 ['a', 'b', 'b', 'c', 'c', 'c'] 21 >>> copycat(['a', 'b', 'c'], [3]) 22 ['a', 'a', 'a'] 23 >>> copycat(['a', 'b', 'c'], [0, 2, 0]) 24 ['b', 'b'] 25 >>> copycat([], [1,2,3]) 26 [] 27 >>> copycat(['a', 'b', 'c'], [1, -1, 3]) 28 ['c', 'c', 'c'] 29 """ 30 def copycat_helper(______, ______, ______): 31 if ______: 32 return ______ 33 if ______: 34 ______ = ______ 35 else: 36 ______ = ______[:______] 37 return ______ 38 r
answer
def copycat(lst1, lst2): """ Write a function `copycat` that takes in two lists. `lst1` is a list of strings `lst2` is a list of integers It returns a new list where every element from `lst1` is copied the number of times as the corresponding element in `lst2`. If the number of times to be copied is negative (-k), then it removes the previous k elements added. Note 1: `lst1` and `lst2` do not have to be the same length, simply ignore any extra elements in the longer list. Note 2: you can assume that you will never be asked to delete more elements than exist >>> copycat(['a', 'b', 'c'], [1, 2, 3]) ['a', 'b', 'b', 'c', 'c', 'c'] >>> copycat(['a', 'b', 'c'], [3]) ['a', 'a', 'a'] >>> copycat(['a', 'b', 'c'], [0, 2, 0]) ['b', 'b'] >>> copycat([], [1,2,3]) [] >>> copycat(['a', 'b', 'c'], [1, -1, 3]) ['c', 'c', 'c'] """ def copycat_helper(lst1, lst2, lst_so_far): if len(lst1) == 0 or len(lst2) == 0: return lst_so_far if lst2[0] >= 0: lst_so_far = lst_so_far + [lst1[0] for _ in range(lst2[0])] else: lst_so_far = lst_so_far[:lst2[0]]#去除lst[0]个元素 return copycat_helper(lst1[1:], lst2[1:], lst_so_far) return copycat_helper(lst1, lst2, [])
7
1 def village(apple, t): 2 """ 3 The `village` operation takes 4 a function `apple` that maps an integer to a tree where 5 every label is an integer. 6 a tree `t` whose labels are all integers 7 8 And applies `apple` to every label in `t`. 9 10 To recombine this tree of trees into a a single tree, 11 simply copy all its branches to each of the leaves 12 of the new tree. 13 14 For example, if we have 15 apple(x) = tree(x, [tree(x + 1), tree(x + 2)]) 16 and 17 t = 10 18 / \ 19 20 30 20 21 We should get the output 22 23 village(apple, t) 24 = 10 25 / \ 26 / \ 27 11 12 28 / \ / \ 29 20 30 20 30 30 / \ / \ / \ / \ 31 21 22 31 32 21 22 31 32 32 >>> t = tree(10, [tree(20), tree(30)]) 33 >>> apple = lambda x: tree(x, [tree(x + 1), tree(x + 2)]) 34 >>> print_tree(village(apple, t)) 35 10 36 11 37 20 38 21 39 22 40 30 41 31 42 32 43 12 44 20 45 21 46 22 47 30 48 31 49 32 50 """ 51 def graft(t, bs): 52 """ 53 Grafts the given branches `bs` onto each leaf 54 of the given tree `t`, returning a new tree. 55 """ 56 if ______: 57 return ______ 58 new_branches = ______ 59 return tree(______, ______) 60 base_t = ______ 61 bs = ______ 62 return graft(base_t, bs) 63 64 def tree(label, branches=[]): 65 """Construct a tree with the given label value and a list of branches.""" 66 for branch in branches: 67 assert is_tree(branch), 'branches must be trees' 68 return [label] + list(branches) 69 70 def label(tree): 71 """Return the label value of a tree.""" 72 return tree[0] 73 74 def branches(tree): 75 """Return the list of branches of the given tree.""" 76 return tree[1:] 77 78 def is_tree(tree): 79 """Returns True if the given tree is a tree, and False otherwise.""" 80 if type(tree) != list or len(tree) < 1: 81 return False 82 for branch in branches(tree): 83 if not is_tree(branch): 84 return False 85 return True 86 87 def is_leaf(tree): 88 """Returns True if the given tree's list of branches is empty, and False 89 otherwise. 90 """ 91 return not branches(tree) 92 93 def print_tree(t, indent=0): 94 """Print a representation of this tree in which each node is 95 indented by two spaces times its depth from the entry. 96 """ 97 print(' ' * indent + str(label(t))) 98 for b in branches(t): 99 p
answer:
1 def village(apple, t): 2 """ 3 The `village` operation takes 4 a function `apple` that maps an integer to a tree where 5 every label is an integer. 6 a tree `t` whose labels are all integers 7 8 And applies `apple` to every label in `t`. 9 10 To recombine this tree of trees into a a single tree, 11 simply copy all its branches to each of the leaves 12 of the new tree. 13 14 For example, if we have 15 apple(x) = tree(x, [tree(x + 1), tree(x + 2)]) 16 and 17 t = 10 18 / \ 19 20 30 20 21 We should get the output 22 23 village(apple, t) 24 = 10 25 / \ 26 / \ 27 11 12 28 / \ / \ 29 20 30 20 30 30 / \ / \ / \ / \ 31 21 22 31 32 21 22 31 32 32 >>> t = tree(10, [tree(20), tree(30)]) 33 >>> apple = lambda x: tree(x, [tree(x + 1), tree(x + 2)]) 34 >>> print_tree(village(apple, t)) 35 10 36 11 37 20 38 21 39 22 40 30 41 31 42 32 43 12 44 20 45 21 46 22 47 30 48 31 49 32 50 """ 51 def graft(t, bs): 52 """ 53 Grafts the given branches `bs` onto each leaf 54 of the given tree `t`, returning a new tree. 55 """ 56 if is_leaf(t): 57 return tree(label(t),bs) 58 new_branches = [graft(b,bs) for b in branches(t)] 59 return tree(label(t), new_branches) 60 base_t = apple(t) 61 bs = [village(apple,branch) for branch in branches(t)] 62 return graft(base_t, bs)

浙公网安备 33010602011771号