## Problem 3: 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`. ```python def store_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 ***" ``` ##
时间: 2023-12-25 17:06:15 浏览: 103
Here's one way to implement the `store_digits` function in Python:
```python
class Link:
empty = ()
def __init__(self, first, rest=empty):
self.first = first
self.rest = rest
def __repr__(self):
if self.rest is not Link.empty:
rest_str = ', ' + repr(self.rest)
else:
rest_str = ''
return 'Link(' + str(self.first) + rest_str + ')'
def store_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)))
"""
if n < 10:
return Link(n)
else:
all_but_last, last = n // 10, n % 10
return Link(last, store_digits(all_but_last))
```
The `store_digits` function recursively constructs a linked list by repeatedly taking the last digit of the input number `n` and attaching it to the front of the linked list. The base case occurs when `n` is less than 10, in which case we simply return a single-element linked list containing `n`.
Note that we use the `//` operator to perform integer division and obtain the quotient `all_but_last`, which is the input number with its last digit removed. We then use the `%` operator to obtain the remainder `last`, which is the last digit of the input number. Finally, we recursively call `store_digits` on `all_but_last` and attach the resulting linked list to the front of the linked list containing `last`.
阅读全文