简体   繁体   English

Ruby 的 to_s(2) 如何翻译成 python?

[英]How does Ruby's to_s(2) translate into python?

So I've been trying to rewrite a Ruby snippet of code into Python, and I haven't been able to make it work.所以我一直在尝试将一段 Ruby 代码改写成 Python,但我一直无法让它工作。 I reread everything to make sure I did it right, but it still doesn't work.我重新阅读了所有内容以确保我做对了,但它仍然不起作用。 I guess the problem lies in this "translation":我想问题在于这个“翻译”:

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

This is my translated python version:这是我翻译的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

I believe I didn't quite understand Ruby's concepts of to_s(2) and/or .drop(1) .我相信我不太了解 Ruby 的to_s(2)和/或.drop(1) 概念 Could someone tell me what is the best way of translating this Ruby code into Python?有人能告诉我这个 Ruby 代码翻译成 Python 的最佳方法是什么吗?

EDIT So, I'll elaborate just as @Michael Butscher suggested:编辑因此,我将按照@Michael Butscher 的建议进行详细说明:

I have this Ruby code, which I tried to translate into this Python code.我有这个Ruby 代码,我试图将其翻译成这个Python 代码。 And while the output should be虽然输出应该是

044aeaf55040fa16de37303d13ca1dde85f4ca9baa36e2963a27a1c0c1165fe2b11511a626b232de4ed05b204bd9eccaf1b79f5752e14dd1e847aa2f4db6a5

it throws an error.它抛出一个错误。 Why?为什么?

The problem is not in the function you have shown, but in your inverse function.问题不在于您显示的函数,而在于您的inverse函数。 / between integers in Ruby translates as // in Python 3: /在 Ruby 中的整数之间转换为//在 Python 3 中:

Ruby:红宝石:

3 / 2
# => 1
3.0 / 2
# => 1.5

Python 3:蟒蛇3:

3 / 2
# => 1.5
3 // 2
# => 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM