留学生作业之7进制与序列产生

留学生作业之7进制与序列产生

作业如下所示:

1. (25 Points) Fill in the definition of the recursive function base7digits(?) below that prints out the base 7
digits of the positive integer ?. All output will be on a single line with no spaces between the digits. Your
function need not print anything when ? ≤ 0. (Hint: this was discussed as an exercise in lecture on 4-1-
21, and in the examples on the class webpage.) 主要意思是把n转换成7进制数.

def base7digits(n):
# begin solution

2. (25 Points) Fill in the definition of the Python function sequence_gen(?, ?) below that returns a generator
object which produces the (infinite) sequence of positive multiples of ? that have remainder 1 when divided
by ?. Thus sequence_gen(3, 5) would produce the sequence: 6, 21, 36, 51, 66, 81,… . You may assume
that ? and ? are positive integers. 主要意思是定义一个生成器,产生6,21,36,51,66……,81这个序列.
def sequence_gen(a, b):

# begin solution

以下是7进制的参考答案:

def base7digits(n):
  
    n,r = divmod(n,7)
    if n !=0:
        return base7digits(n) + str(r)
    else:
        return str(r) 

print(base7digits(19)) 

以下是产生序列的参考答案:

def sequence_gen(a, b):

    n=6
    while True:
        yield n
        n = n + a*b

x = sequence_gen(3,5)
for _ in range(10):
    print(next(x),end=',')

晚是10:41了,还没洗脸和脚和刷牙,但要睡觉了!

李兴球

李兴球的博客是Python创意编程原创博客