Home > Net >  How does Ruby's to_s(2) translate into python?
How does Ruby's to_s(2) translate into python?

Time:10-27

So I've been trying to rewrite a Ruby snippet of code into Python, and I haven't been able to make it work. 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:

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). Could someone tell me what is the best way of translating this Ruby code into Python?

EDIT So, I'll elaborate just as @Michael Butscher suggested:

I have this Ruby code, which I tried to translate into this Python code. And while the output should be

044aeaf55040fa16de37303d13ca1dde85f4ca9baa36e2963a27a1c0c1165fe2b11511a626b232de4ed05b204bd9eccaf1b79f5752e14dd1e847aa2f4db6a5

it throws an error. Why?

CodePudding user response:

The problem is not in the function you have shown, but in your inverse function. / between integers in Ruby translates as // in Python 3:

Ruby:

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

Python 3:

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