如何重复n次功能

编程入门 行业动态 更新时间:2024-10-25 05:11:23
本文介绍了如何重复n次功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在python中编写一个函数,例如:

I'm trying to write a function in python that is like:

def repeated(f, n): ...

其中f是一个带有一个参数的函数,而n是一个正整数.

where f is a function that takes one argument and n is a positive integer.

例如,如果我将正方形定义为:

For example if I defined square as:

def square(x): return x * x

我打电话

repeated(square, 2)(3)

这将平方3、2倍.

推荐答案

应该这样做:

def repeated(f, n): def rfun(p): return reduce(lambda x, _: f(x), xrange(n), p) return rfun def square(x): print "square(%d)" % x return x * x print repeated(square, 5)(3)

输出:

square(3) square(9) square(81) square(6561) square(43046721) 1853020188851841

或lambda少?

def repeated(f, n): def rfun(p): acc = p for _ in xrange(n): acc = f(acc) return acc return rfun

更多推荐

如何重复n次功能

本文发布于:2023-11-30 20:20:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651363.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!