簡體   English   中英

打印一個5位數的數字,這樣,如果我們將1放在開頭,則生成的6位數的數字比如果將1 @末尾的數字小3倍

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM