【问题标题】:for loop function to convert octal to decimal using string list of numbersfor循环函数使用数字字符串列表将八进制转换为十进制
【发布时间】:2022-11-25 05:30:05
【问题描述】:

我正在创建一个函数,在 for 循环中将八进制数从字符串列表转换为十进制数,每次测试使用不同的数字进行 9 次测试,但只有前 4 次测试有效并给出正确答案,而其他的则没有,我我不确定为什么,不起作用的数字是任何带有 2 位数字的数字,例如“10”,还有一些数字是一个序列,例如“34 56”。下面是我的代码

def decode(code):
    code = code.split(" ")  
    decimal = 0
    for i in range(len(code)):
        decimal += int(code[i]) * pow(8, len(code) - 1)
        return str(decimal)

我是 python 的新手,所以仍在学习和理解这一切!我使用 code.split(" ") 因为字符串列表中的一些数字之间有空格。

我试过几次重写代码并重新排列一些东西但无济于事,我知道 python 中有一个函数可以快速将八进制转换为十进制,但我没有尝试使用它。
我用于“代码”的字符串列表是数字“1、2、3、4、10、16、100、34 56、120 156 206”

【问题讨论】:

  • Code.split() 会将字符串拆分为字符串列表;更好地使用 code.replace(" ","");而且,8的次方是常数!它应该是 len(code) - i - 1。哦,最后一个(希望)错误:“return”语句应该是无意的

标签: python


【解决方案1】:

这是固定代码:

def decode(code):
    code = code.replace(" ","")  
    decimal = 0
    for i in range(len(code)):
        decimal += int(code[i]) * pow(8, len(code) - i - 1)
    return str(decimal)

和例子:

print([decode(x) for x in "1,2,3, 4, 10, 16, 100, 34 56, 120 156 206".split(',')])
# ['1', '2', '3', '4', '8', '14', '64', '1838', '21027974']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多