[英]How does Ruby's to_s(2) translate into python?
所以我一直在嘗試將一段 Ruby 代碼改寫成 Python,但我一直無法讓它工作。 我重新閱讀了所有內容以確保我做對了,但它仍然不起作用。 我想問題在於這個“翻譯”:
def multiply(k, point = $G)
current = point
binary = k.to_s(2)
binary.split("").drop(1).each do |char|
current = double(current)
current = add(current, point) if char == "1"
end
current
end
這是我翻譯的python版本:
def multiply(k, point = G):
current = point
binary = bin(k)
for i in binary[3:]:
current = double(current)
if i == "1":
current = add(current, point)
return current
我相信我不太了解 Ruby 的to_s(2)和/或.drop(1) 概念。 有人能告訴我將這個 Ruby 代碼翻譯成 Python 的最佳方法是什么嗎?
編輯因此,我將按照@Michael Butscher 的建議進行詳細說明:
我有這個Ruby 代碼,我試圖將其翻譯成這個Python 代碼。 雖然輸出應該是
044aeaf55040fa16de37303d13ca1dde85f4ca9baa36e2963a27a1c0c1165fe2b11511a626b232de4ed05b204bd9eccaf1b79f5752e14dd1e847aa2f4db6a5
它拋出一個錯誤。 為什么?
問題不在於您顯示的函數,而在於您的inverse
函數。 /
在 Ruby 中的整數之間轉換為//
在 Python 3 中:
紅寶石:
3 / 2
# => 1
3.0 / 2
# => 1.5
蟒蛇3:
3 / 2
# => 1.5
3 // 2
# => 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.