[英]Functional Programming Python: smallest number divisible by each of the numbers 1 to 20
I want to build a while loop in python using its functional programming capabilities, but until now I'm failing. 我想使用它的功能编程功能在python中建立一个while循环,但是直到现在我还是失败了。
What I have accomplished is this peace of code, which should calculate the smallest number divisible by each of the numbers 1 to 20. But it doens't seem it's using functional programming capabilities a lot. 我已经实现了这种代码和平的功能,它应该计算出最小的数字,该数字可以被数字1到20整除。但是似乎并没有大量使用函数式编程功能。 And also gives me the error as below:
而且还给我以下错误:
"RuntimeError: maximum recursion depth exceeded" at the line of the incrementation of "i";
“ RuntimeError:超过最大递归深度”在增量“ i”的行中;
even if this should be limited to 20. 即使应限制为20。
def byYmult(x, y): return x % y == 0
def first20div():
i=0
for y in range(1,20):
i += byYmult(x, y)
return i >= 20
def while_block():
global x
if first20div():
print(x)
return 1
else:
x += 1
return 0
x = 0
while_FP = lambda: ((not first20div()) and while_block() ) or while_FP()
while_FP()
This is non-functial for a lot of reasons: 这是非功能性的,原因有很多:
global x
, that you update; global x
; So there is a lot to work with. 因此,有很多工作要做。 Furthermore the algorithm you describe is not very optimal.
此外,您描述的算法不是很理想。 Instead of performing a brute force approach where we keep guessing the number until finally we got lucky, a better approach is to calculate the least common multiple (LCM) of the numbers 1..20.
与其执行不断猜测数字直到最终获得幸运的蛮力方法,一种更好的方法是计算数字1..20的最小公倍数(LCM) 。
We can first define - in a functional way - we can calculate the LCM by calculating the greatest common divider (GCD) first, and this can be done by the Euclidean Algorithm . 我们可以首先定义-以功能方式-首先可以通过计算最大公共除法器(GCD)来计算LCM,这可以通过欧几里得算法来完成。 Lucky for us, it is already in the
math
package: 对我们来说幸运的是,它已经在
math
包中:
from math import gcd
Now the LCM is: 现在,LCM为:
def lcm(a,b):
return (a*b)//gcd(a,b)
The LCM of three or more numbers can be calculated by calculating the LCM of the first two numbers and then pass it as first argument to the LCM with the third number, or more formally: 可以通过计算前两个数字的LCM,然后将其作为第一个参数传递给具有第三个数字的LCM或更正式地计算三个或更多数字的LCM:
lcm(x,y,z) == lcm(lcm(x,y),z)
and this can be done by using reduce
from functools
: 这可以通过使用来自
functools
reduce
来完成:
from functools import reduce
def lcm_multiple(xs):
return reduce(lcm, xs)
and now we can calculate the answer, by passing it a range(2,20)
object: 现在我们可以通过将
range(2,20)
对象传递给它来计算答案:
answer = lcm_multiple(range(2, 20))
Or in full: 或全部:
from math import gcd
from functools import reduce
def lcm(a,b):
return (a*b)//gcd(a,b)
def lcm_multiple(xs):
return reduce(lcm, xs)
answer = lcm_multiple(range(2, 20))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.