我一直在学习函数式编程,想到将数学运算符组合起来。顺理成章地,我写出了最简单和最朴素的代码表达式,并且它工作得非常好!问题是我真的不知道为什么它能如此有效地处理如此庞大的输出。
问题是:这个函数的复杂度是多少?
代码是用Python编写的:
def operator(d):
if d<=1:
return lambda x,y:x+y
else:
return lambda x,y:reduce(operator(d-1),(x for i in xrange(y)))
#test
f1 = operator(1) #f1 is adition
print("f1",f1(50,52)) #50+52
f2 = operator(2) #f2 is multiplication
print("f2",f2(2,20)) #2*20
f3 = operator(3) #f3 is power, just look how long output can be
print("f3",f3(4,100)) #4**100
f4 = operator(4) #f4 is superpower, this one does not work that well
print("f4",f4(2,6)) #((((2**2)**2)**2)**2)**2
f5 = operator(5) #f5 do not ask about this one,
print("f5",f5(2,4)) #
输出(即时):
('f1', 102)
('f2', 40)
('f3', 1606938044258990275541962092341162602522202993782792835301376L)
('f4', 4294967296L)
('f5', 32317006071311007300714876688669951960444102669715484032130345427524655138867890893197201411522913463688717960921898019494119559150490921095088152386448283120630877367300996091750197750389652106796057638384067568276792218642619756161838094338476170470581645852036305042887575891541065808607552399123930385521914333389668342420684974786564569494856176035326322058077805659331026192708460314150258592864177116725943603718461857357598351152301645904403697613233287231227125684710820209725157101726931323469678542580656697935045997268352998638215525166389437335543602135433229604645318478604952148193555853611059596230656L)
operator(1)
,使其每次被调用时增加一个变量。顺便提一句,我感觉你可能会对Ackerman函数感兴趣 :)。 - hugomg