我似乎无法弄清楚为什么我不能转换为整数

时间:2019-05-15 12:38:30

标签: python python-2.7

我正在尝试将字符串转换为int,但由于某种原因,它似乎确实想工作。我对学习我对所编写代码的理解存在断层的地方非常感兴趣。谢谢!

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())  

错误:

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-'

2 个答案:

答案 0 :(得分:0)

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

num = descend - ascend
num = abs(num)
count += 1

答案 1 :(得分:0)

您需要在第15行检查计算结果。

好像在您的代码中一样,在此行计算的“字符串”的值获得的值为“ 999-”,该值不能转换为整数类型,因为其中包含“-”。