我創建了一個腳本,該腳本應該通過重新排列數字來執行簡單的數學雜耍。請在此計算中解析python「magic」
它應該做的:
x = 777.0
y = 5
calc = x/y # 155.4
... 僞代碼:
Rearrange numbers (last digit + first) = 555.
Difference from 777 and 555 = 222
Add 222 to 555 = 777
基本上它應該重建原始的變量沒有做真正的計算,但實際上只是重新排列的數字和補充。
由於腳本的設計,我預計它只能使用像333.3這樣的4位數字。事實證明,它似乎也適用於像2543.6452這樣的數字,至少從我的(非學術)角度來看似乎是不可能的。 有人可以告訴我這裏發生了什麼?代碼是否正常工作或者我創建了一些我根本不明白的東西?這對我來說看起來像是幻覺。 :D
x = 5.0
y = 7345.3297
z= y/x
print "Initial Value = " + str(y)
print "Calculate:"
print str(y) + "/" + str(x)
print z # 177.6
print
a = int(str(z)[0])
print "First Number = " + str(a)
print
b = int(str(z)[1])
c = int(str(z)[2])
print "In between = " + str(b) + str(c)
d = int(str(z)[-1]) # treat z as string, take first string after . from z and format it back to int
print "Last Number = " + str(d)
print
print "Rearrange Numbers"
res = str(a+d) +str(b) +str(c)
to_int = int(res)
dif = y - to_int
add = to_int + dif
print "number = " + str(add)
所以代碼正在做你想做的事..... .....你想知道怎麼做它在做什麼? – DavidG
不是。它做得太多太好。 :D 例如,如果我把數字23135.34674和執行計算它應該有一個非常不同的結果比23135.34674。 該代碼旨在(至少我預料到)只能與「對稱」值(如666.666或888.8)一起工作:對我來說,它看起來像我的代碼只接受變量y並將其打印爲結果。 :D 「in_between」的值僅考慮第二位和第三位數字。用更大的數字看起來不可能得到正確的結果。 – Horst23