![](/img/trans.png)
[英]to write a program to find all the pair of 5digit number such that their sum is also a 5digit number
[英]print a 5digit number such that if we put 1 at the beginning, the resulting 6digit number is 3x smaller than if we put the 1 @ end of the number
到目前為止,這是我的代碼
x = 100000
while x < 100000:
y = x + 100000
z = (3*10000)-1/(10-3)
if y != z:
x += 1
else:
print(x)
打破
我知道答案應該是42857但給了我10000
由於x
初始化錯誤,因此循環永遠不會執行。 此外, z
是常數(不取決於x
)
在您的代碼中,由於斷行的縮進使else
語句與while
匹配,因此它可能打印100000
。 由於沒有break
發生,因此將打印x
的最后一個值。
最好做一個for
循環。 這樣可行:
for x in range (1,100000):
y = x + 100000
z = x*10 + 1
if y == z//3:
print(x)
break
else:
# for loop completed without break
print("not found")
或一行,使用next
和一生成器理解:
result = next(x for x in range (1,100000) if x + 100000 == (x*10 + 1)//3)
在這兩種情況下,結果的確是42857
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.