## 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 09:06:15 浏览: 143
Here's one possible implementation of the `store_digits` function:
```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)))
"""
if n == 0:
return Link(0)
digits = []
while n > 0:
digits.append(n % 10)
n //= 10
digits.reverse()
return Link(*digits)
```
The function works by first checking if `n` is equal to 0, in which case it just returns a linked list with a single element 0. Otherwise, it initializes an empty list `digits` to store the digits of `n`. It then repeatedly divides `n` by 10, appending the remainder (i.e., the last digit) to `digits`. Once `n` becomes 0, the function reverses the order of the digits in `digits` (since the last digit added will be the first element of the linked list) and creates a new `Link` object with the unpacked digits using the `*` operator.
Note that this implementation assumes that `n` is a positive integer. If `n` can be negative, we would need to handle the sign separately and then take the absolute value of `n` before storing its digits.
阅读全文