我在某处看到了这个问题。 有一个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