【问题标题】:How does Ruby's to_s(2) translate into python?Ruby 的 to_s(2) 是如何翻译成 python 的?
【发布时间】:2021-10-27 01:42:11
【问题描述】:

所以我一直在尝试将 Ruby sn-p 代码重写为 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 的建议进行详细说明:

我有this Ruby 代码,我试图将其转换为this Python 代码。而输出应该是

044aeaf55040fa16de37303d13ca1dde85f4ca9baa36e2963a27a1c0c1165fe2b11511a626b232de4ed05b204bd9eccaf1b79f5752e14dd1e847aa2f4db6a5

它会引发错误。为什么?

【问题讨论】:

  • 你有正确的等价物:Ruby 的 k.to_s(2) 等价于 Python 的 bin(k)[2:],binary.split("").drop(1).each 的语法等价于 for i in binary[1:](当你与 bin(k) 结合使用时,它变为 binary[3:] )。
  • 解释它是如何不起作用的。会发生什么,应该发生什么?
  • 以后请关注[help/how-to-ask]创建minimal reproducible example。确保问题是独立的,不是每个人都想关注外部链接。如果有错误,包括错误信息;如果代码没有错误,请说明您想要的结果与您得到的结果有何不同。
  • 抱歉,应该是How do I ask a good question? :)

标签: python ruby python-cryptography


【解决方案1】:

问题不在于您显示的功能,而在于您的inverse 功能。 Ruby 中整数之间的 / 在 Python 3 中转换为 //:

鲁比:

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

Python 3:

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

【讨论】:

  • 非常感谢,这太简单了,但我却无法发现。感谢您的时间和耐心。
  • 不用担心。找到这类事情的简单方法是在代码周围添加足够多的 puts 或 print 语句,看看哪里开始变得奇怪。
猜你喜欢
  • 1970-01-01
  • 2011-09-05
  • 2021-03-06
  • 1970-01-01
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多