Write a function link_to_list that takes in a linked list and returns the sequence as a Python list. You may assume that the input list is shallow; none of the elements is another linked list.
deflink_to_list(link):"""Takes a linked list and returns a Python list with the same elements.>>> link = Link(1, Link(2, Link(3, Link(4))))>>> link_to_list(link) [1, 2, 3, 4]>>> link_to_list(Link.empty) [] """"*** YOUR CODE HERE ***"
Q2: Solution
deflink_to_list(link):"""Takes a linked list and returns a Python list with the same elements.>>> link = Link(1, Link(2, Link(3, Link(4))))>>> link_to_list(link) [1, 2, 3, 4]>>> link_to_list(Link.empty) [] """"*** YOUR CODE HERE ***"if link is Link.empty:return []else:return [link.first] +link_to_list(link.rest)
Q3: Store Digits
Write a function store_digits that takes in an integer n and returns a linked list where each element of the list is a digit of n.
defstore_digits(n):"""Stores the digits of a positive number n in a linked list.>>> s = store_digits(1)>>> s Link(1)>>> store_digits(2345) Link(2, Link(3, Link(4, Link(5))))>>> store_digits(876) Link(8, Link(7, Link(6))) """"*** YOUR CODE HERE ***"
Q3: Solution
defstore_digits(n):"""Stores the digits of a positive number n in a linked list.>>> s = store_digits(1)>>> s Link(1)>>> store_digits(2345) Link(2, Link(3, Link(4, Link(5))))>>> store_digits(876) Link(8, Link(7, Link(6))) """"*** YOUR CODE HERE ***"if n <10:returnLink(n)else: first_digit =int(str(n)[0]) digit_cut =int(str(n)[1:])returnLink(first_digit, store_digits(digit_cut))
Q4: Cumulative Sum
Write a function cumulative_sum that mutates the Tree t so that each node's label becomes the sum of all labels in the subtree rooted at the node
defcumulative_sum(t):"""Mutates t so that each node's label becomes the sum of all labels in the corresponding subtree rooted at t.>>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)])>>> cumulative_sum(t)>>> t Tree(16, [Tree(8, [Tree(5)]), Tree(7)]) """"*** YOUR CODE HERE ***"
Q5: Solution
defsum_tree(t):if t.is_leaf():return t.labelelse:for b in t.branches: t.label +=sum_tree(b)return t.labeldefcumulative_sum(t):"""Mutates t so that each node's label becomes the sum of all labels in the corresponding subtree rooted at t.>>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)])>>> cumulative_sum(t)>>> t Tree(16, [Tree(8, [Tree(5)]), Tree(7)]) """"*** YOUR CODE HERE ***"for branch in t.branches: t.label +=sum_tree(branch)