请问一下,这个可以怎么实现呀?

Write a program that creates a closure function such that it returns a geometric sequence (等比数列), , with 5 items, where  is the common ratio defined by the outer function named input_ratio(r), and  is a scale factor used by the inner function named scale_factor(a). The following shows an execution of the program.

 

 

 
gs3=input_ratio(3)
print(gs3(4))
#output
(4, 12, 36, 108, 324) 

两个函数名input_ratio和scale_factor不时很贴切。不过下面代码应该已经可以了。

def geometric_sequence(ratio, factor):
    count = 5
    def input_ratio(r):
    
        def scale_factor(a):
            s = [a]
            i = 1
            n = a
            while i < count:
                n = n * r
                s.append(n)
                i = i + 1

            return tuple(s)
            
        return scale_factor(factor)
  
    return input_ratio(ratio)
    
print(geometric_sequence(3, 4))

输出:

(4, 12, 36, 108, 324)

 

附注:求赞助积分和C币。加入CSDN将近20年了。最近几年忙小孩没登录。刚才搜索到一本电子书想下载,需要20积分/C币。赞助多少都可以。多谢。