我在某處看到了這個問題。 有一個8位數字。從左到右的第一個數字表示數字中有多少個零。第二位數字告訴你號碼中有多少個1,第三位數字告訴你號碼中有多少2,等等直到第8位數字告訴你號碼中有多少個7。找到號碼。 所以我在python中編寫了一段代碼來找出數字。除了上面提到的條件之外,我還有一些額外的檢查,比如'數字總和應該是8'以及'數字中不應該有8或9個'。我粘貼了下面的代碼。這只是蠻力,因爲我把每一個數字和檢查條件。我很好奇,想知道是否有解決問題的找到滿足特定條件的數字的優化方式
def returnStat(number, digit, count):
number = str(number)
digit = str(digit)
print "Analysing for ",digit," to see if it appears ",count, " times in ",number,"."
actCnt = number.count(digit)
count = str(count)
actCnt = str(actCnt)
if (actCnt == count):
return 1
else:
return 0
def validateNum(number):
numList = str(number)
if '8' in numList:
print "Skipping ",number, " since it has 8 in it"
return (-1)
elif '9' in numList:
print "Skipping ",number, " since it has 9 in it"
return (-1)
elif (sum(int(digit) for digit in numList) != 8):
print "Skipping ",number, " since its sum is not equal to 8"
return (-1)
index = 0
flag = 0
for num in numList:
if (returnStat(number,index,num)) :
index = index+1
continue
else:
flag = 1
break
if (flag == 1):
return (-1)
else:
return number
for num in range(0,80000000):
number = '{number:0{width}d}'.format(width=8,number=num)
desiredNum = "-1"
desiredNum = validateNum(number)
if (desiredNum == -1):
print number," does not satisfy all "
continue
else:
print "The number that satisfies all contition is ",number
break
完成,工作是你有意改善自己所屬的代碼審查代碼,而不是堆棧溢出。 – TigerhawkT3
我很樂意學習不同的解決方案。我不只是尋找解決方案來改進我的解決方案。 – Ani