将一段代码从ruby转换成python

时间:2019-01-06 14:04:34

标签: python ruby

我有一段用Ruby编写的代码。我想将其转换为Python。

def decode(bitstring, search_space, bits_per_param)
  vector = []
  search_space.each_with_index do |bounds, i|
    off, sum = i*bits_per_param, 0.0
    param = bitstring[off...(off+bits_per_param)].reverse
    param.size.times do |j|
      sum += ((param[j].chr=='1') ? 1.0 : 0.0) * (2.0 ** j.to_f)
    end
    min, max = bounds
    vector << min + ((max-min)/((2.0**bits_per_param.to_f)-1.0)) * sum
  end
  return vector
end

我将其转换如下。我需要转换param的帮助。

def decode(bitstring, search_space, bits_per_param):
    vector = []
    for i, bounds in enumerate(search_space):
        sum = i * bits_per_param



    for j in xrange(0, len(param)):
        sum += iif(param[j] == '1', '0', '1') * (2 ** j), param[j]
    min, max = bounds
    vector = min + ((max - min) / ((2.0 ** bits_per_param) - 1.0)) * sum
    return vector

param未正确转换。

ps。这是 iif 函数的代码:

def iif(condition, true_part, false_part):
    return (condition and [true_part] or [false_part])[0]

1 个答案:

答案 0 :(得分:0)

我想我可以部分解决我的问题。 python中的代码如下所示。

def decode(bitstring, search_space, bits_per_param):
vector = []
for i, bounds in enumerate(search_space):
    off, sum = i * bits_per_param, 0.0
    param = (bitstring[off:(off+bits_per_param)])[::-1]
    for j in xrange(0, len(param)):
        if param[j].__str__() == '1':
            sum += 1.0 * (2**float(j))
        else:
            sum += 0.0 * (2**float(j))
    min, max = bounds
    vector.append(min + ((max - min) / ((2.0 ** bits_per_param) - 1.0)) * sum)
return vector