【发布时间】:2020-03-28 13:07:40
【问题描述】:
我需要了解以下代码的复杂性。我熟悉所有 Big O() 表示法的概念,也阅读了很多博客,但我不知道如何应用于大型程序。 以下是从 100 到 999 的最大回文数的代码:
def isPaindrome(number):
stringNum = str(number)
firstDigit_index,lastDigit_index=0,len(stringNum)-1
isPalindrome = False
while(lastDigit_index > 0 and firstDigit_index < lastDigit_index):
#print(stringNum[f],"==",stringNum[l],"......")
if(stringNum[firstDigit_index]==stringNum[lastDigit_index]):
isPalindrome = True
else:
isPalindrome = False
break
firstDigit_index = firstDigit_index + 1
lastDigit_index = lastDigit_index - 1
if(isPalindrome):
return number
else:
return 0
max = 0
startRange = 100
endRange = 999
for i in range(endRange*endRange,startRange*startRange,-1):
factors = []
result = isPaindrome(i)
if(result!=0):
for i in range(startRange,endRange+1):
if(result%i==0):
factors.append(i)
if(len(factors)>1):
sumFactor = factors[(len(factors))-1] + factors[(len(factors))-2]
mul = factors[(len(factors))-1] * factors[(len(factors))-2]
if(sumFactor>max and mul==result):
max = sumFactor
print("Largest Palindrome made from product of two 3 digit numbers(",factors[(len(factors))-1],",",factors[(len(factors))-2] ,") is", result,".")
如果有人能让我逐步了解如何计算,我将不胜感激。
【问题讨论】:
-
Emm.. 你的代码不应该工作?您没有更改 isPalindrome 函数中的索引
-
您是否正在尝试解决 Project Euler 问题 4? projecteuler.net/problem=4
-
是的,它确实有效。现在来看看函数。 @GarethMa。
-
还是O(n),复杂度和我分析的差不多
标签: python time-complexity complexity-theory