首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我似乎弄不明白为什么我不能转换为int类型

我似乎弄不明白为什么我不能转换为int类型
EN

Stack Overflow用户
提问于 2019-05-15 20:38:30
回答 2查看 75关注 0票数 1

我试图将一个字符串转换为int类型,但由于某种原因,它似乎确实想要工作。我非常有兴趣了解在我对所写代码的理解上有什么脱节之处。谢谢!

代码语言:javascript
复制
def fourdigitnum(num):
    string = str(num)
    while (len(string) < 4):
        string = "0" + string
    return string
def ascend_desend(string,order):
    if(order == "ascend"):
        string = sorted(string,reverse = True)
    elif(order == "descend"):
        string = sorted(string,reverse = False)
    return string
def list_to_num(lst):
    string = ""
    for ele  in lst:
        string = string + ele
    return int(string)

def KaprekarsConstant(num): 
    num = int(num)
    count = 0
    while num != 6174:
        num = fourdigitnum(num)
        #ascend and descend are lists
        ascend = ascend_desend(num,"ascend")
        descend = ascend_desend(num,"descend")
        #they must be turned into nums
        ascend = list_to_num(ascend)
        descend = list_to_num(descend)
        num = descend - ascend
        count += 1

    return count

print KaprekarsConstant(raw_input())  

错误:

代码语言:javascript
复制
Traceback (most recent call last):
  File "/tmp/576159006/main.py", line 41, in <module>
    print KaprekarsConstant(2111)
  File "/tmp/576159006/main.py", line 33, in KaprekarsConstant
    ascend = list_to_num(ascend)
  File "/tmp/576159006/main.py", line 16, in list_to_num
    return int(string)
ValueError: invalid literal for int() with base 10: '999-'
EN

回答 2

Stack Overflow用户

发布于 2019-05-15 20:47:39

在您的代码中,num = descend - ascend行的计算返回负(-)值,因为生成的ascend值大于descend。您可以获取绝对值并从此处继续,请参见以下几行:

代码语言:javascript
复制
num = descend - ascend
num = abs(num)
count += 1
票数 0
EN

Stack Overflow用户

发布于 2019-05-15 21:12:52

您需要检查第15行的计算。

似乎在你的代码中,在这一行计算的'string‘的值是'999-’,它不能被转换成整数类型,因为它有一个'-‘。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56149553

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档