首先,我想說我不是在找人來做“我的家庭作業” 我已經投入了一些時間思考和解決這個問題我錯過了非常大的數字(超過 10**256)。所以,我正在解決 Google Foobar Challenge #4,其中指出:
燃油噴射完美
指揮官 Lambda 請求您幫助改進 LAMBCHOP 世界末日裝置的自動量子反物質燃料噴射系統。這是一個很好的機會讓你近距離觀察 LAMBCHOP —— 并且可能在你在它的時候偷偷地進行一些破壞——所以你很高興地接受了這份作業。
量子反物質燃料以小顆粒形式出現,這很方便,因為 LAMBCHOP 的許多移動部件都需要一次提供一個燃料顆粒。然而,小兵將顆粒大??量傾倒到燃料入口中。您需要找出最有效的方法來一次將顆粒分類和轉移到單個顆粒。
燃料控制機制具有三個操作:
- 添加一個燃料芯塊
- 取出一顆燃料芯塊
- 將整組燃料芯塊除以 2(由于將量子反物質芯塊切成兩半時釋放的破壞性能量,安全控制僅允許在芯塊數量為偶數時發生這種情況)
撰寫一個名為 solution(n) 的函式,它接受一個正整數作為字串,并回傳將顆粒數量轉換為 1 所需的最小運算元。燃料攝入控制面板只能顯示一個最長為 309 位的數字,所以永遠不會有比你能用這么多數字表達的更多的顆粒。
例如:
解決方案(4)回傳 2:4 -> 2 -> 1
解決方案(15)回傳 5:15 -> 16 -> 8 -> 4 -> 2 -> 1
我的解決方案:
def solution(n):
n = int(n)
operations = 0
# Handling edge cases here:
# n(3)=2, n(2)=1 and n(1)=0
if (n >= 1) and (n <= 3):
return n - 1
while n > 1:
# Any even number will be divided by two
# until we get an odd number. Since we are
# guaranteed the number is divisible by
# two we use floor division to avoid stack
# overflow with strings of 309 digits.
if n % 2 == 0:
n = n // 2
# Any odd number has two even neighbors:
# a) One can be divided by two just ONCE, and
# b) The other can be divided by two MORE than once
# We will always take option b) for path optimization:
elif (n-1) % 4 == 0:
n -= 1
else:
n = 1
operations = 1
return operations
現在,我的代碼通過了 10 個案例中的 8 個。我檢查并重新檢查......并再次檢查代碼并且數學看起來很完美,在某些時候我決定做一些我一開始不想做的事情:谷歌其他答案以找出問題所在。所以我發現了這個:
cnt=0
def divide(x):
global cnt
while(x>1):
if (x & 1==0):
#Dividing even number by two by shifting binary digits one step to the right.
x=x>>1
else:
a=x 1
b=x-1
#counters ac & bc will be used to count trailing 0s
ac=bc=0
#count trailing 0's for x 1
while(a & 1==0):
a=a>>1
ac =1
#count trailing 0's for x-1
while(b & 1==0):
b=b>>1
bc =1
#go with x 1 if it has more trailing 0s in binary format. Exception is number
#3 as b10 can be divided in less steps than b100.
#edge case 3 identified by manually testing numbers 1-10.
if (ac>bc and x!=3):
x =1
else:
x-=1
cnt =1
def solution(n):
global cnt
n=int(n)
divide(n)
return cnt
資料來源:Google Foobar:如何查找邊緣案例和識別測驗案例。Python
現在,真正奇怪的事情來了,第二個代碼似乎使用了與我類似的方法(在二進制中查找最大數量的尾隨零與查找可以多次除以 2 的數字有點相同)僅一次),并且對于 1 到 10^256 之間的任何整數,兩個代碼都達到了完全相同的解決方案,現在在 10^256 和 10^257 之間的某個點發生了非常奇怪的事情:我的代碼給出了“n”操作的答案而另一種解決方案給出了“n-1”操作的輸出。現在我們知道 256 是數字計算機的一種“神奇”數字,互聯網本身 (IPv4) 就是建立在這個數字之上的。我是不是在這里弄壞了什么?
現在,誰能告訴我為什么我的腳本會得到不同的結果?我錯過了什么嗎?我在這里失去理智。
uj5u.com熱心網友回復:
您的代碼看起來會得到錯誤的結果 12.
12 -> 6 -> 3 -> 4 -> 2 -> 1
而不是
12 -> 6 -> 3 -> 2 -> 1.
您的特殊外殼 3 需要在回圈內,而不是在回圈外。
并回答你的另一個問題。256很特別。2^256 或 10^256 沒有什么特別之處。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/472655.html
