【问题标题】:How to repeat a function multiple times in python [duplicate]如何在python中多次重复一个函数[重复]
【发布时间】:2020-05-08 19:01:25
【问题描述】:

我想多次重复一个函数,例如:

func(x) \  func(func(x))  \  func(func(func(x)))

我尝试了多种方法,例如:

for x in range(1,11):
  func*x(value)

还是不行,希望你能理解我的问题,如果我可以更具体的请回复。

【问题讨论】:

  • 你期待递归吗?

标签: python function repeat


【解决方案1】:
#loop:
def func(a):
    return a + 1

x = 0
for a in range(3):
    x = func(x)
print(x)


# alternatively, recursion:
def func(a, depth):
    if depth>0:
        return func(a+1, depth-1)
    return a

【讨论】:

    【解决方案2】:

    使用循环:

    def f(x):
        return x+2
    
    x = 1
    for _ in range(20):
        x = f(x)
        print(x)
    

    从函数返回值并使用新值调用函数。

    输出:

    3
    5
    7
    [...]
    39
    41
    

    如果您需要所有值,请使用列表:

    def f(x):
        return x+2
    
    x = [1]                  # initial value
    for _ in range(20):
        x.append(f(x[-1]))   # feed it the last value from the list and append result
    
    print(x)
    

    输出:

    [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      相关资源
      最近更新 更多