Python:尝试将字符串转换为int,将以10为底的int()的错误转换为int无效文字 [英] Python: Trying to convert string to int, get error to int invalid literal for int() with base 10: ''

查看:240
本文介绍了Python:尝试将字符串转换为int,将以10为底的int()的错误转换为int无效文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,如果这是一个简单的修复,我深表歉意。我已经在一个Codeval问题(快乐数字)上停留了很长时间,而且我不确定是怎么回事。

I am new to Python, so I apologize if this is a simple fix. I have been stuck on a Codeval problem (Happy Numbers) for quite some time and I am not sure what is going wrong.

问题描述:

从任何正整数开始,用数字的平方和代替数字,然后重复此过程,直到数字等于1,否则它会无限循环一个不包含1的循环。那些以1结尾的数字表示满意,而没有以1结尾的数字表示不开心。

Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1, or it loops endlessly in a cycle which does not include 1.Those numbers for which this process ends in 1 are happy, while those that do not end in 1 are unhappy.

例如:

7是一个快乐数字(7-> 49-> 97-> 130-> 10-> 1)

7 is a happy number (7->49->97->130->10->1)

22不是一个快乐的数字(22-> 8-> 64-> 52-> 29-> 85-> 89-> 145-> 42-> 20-> 4-> 16 -> 37-> 58-> 89 ...)

22 is not a happy number (22->8->64->52->29->85->89->145->42->20->4->16->37->58->89 ...)

我的测试输入和预期结果:

1-> 1

7-> 1

22- > 0

如果该数字是一个快乐数字,则打印出1。否则,打印出0。

If the number is a happy number, print out 1. If not, print out 0.

这是完整的追溯:

Traceback (most recent call last):
  File "/happy_number.py", line 58, in <module>
    happy_number_check("happy_numbers.txt")
  File "/happy_number.py", line 55, in happy_number_check
    happy_or_not(line)
  File "/happy_number.py", line 33, in happy_or_not
    i = int(i)
ValueError: invalid literal for int() with base 10: ''

这是我的代码:

# test = 7


def happy_or_not(number):
    number = str(number)
    if number == 1:
        print 1
    else:
        new_num = 0
        for i in number:
            i = int(i)
            if i == " ":
                continue
            else:
                new_num += i**2
        if new_num == 10 or new_num == 10:
            print 1
        else:
            try:
                happy_or_not(new_num)
            except RuntimeError:
                print 0

# happy_or_not(test)


def happy_number_check(file):
    f = open(file, 'r+')
    for line in f:
        if line == "":
            continue
        else:
            happy_or_not(line)


happy_number_check("happy_numbers.txt")

我已经尝试过的方法:

基于我从其他类似问题中收集到的信息,问题可能是我我在行 i = int时无法将 str 转换为 int (i)。据我了解,在对它进行任何数学运算之前,我必须将 str 类型转换为 int 类型,但是

Based on what I gathered from other similar questions, the issue may be that I am not able to convert a str into an int when I hit the line i = int(i). It is my understanding that I have to convert the str type into an int type before doing any math on it, yet it looks like that is where it is failing.

我自己测试了 happy_or_not 函数,它确实可以打印超出我期望的价值。在我看来,当我尝试在 happy_number_check 函数中调用 happy_or_not 函数时,问题就来了正在读取我的txt文件(包含要测试的数字列表)。我在这里不能掌握一个更大的原则,因此任何解释都将有所帮助。

I tested the happy_or_not function by itself, and it does print out the value that I expect it to. It seems like to me that the issue comes when I try and call that happy_or_not function inside of the happy_number_check function, which is reading my txt file (containing a list of numbers to test). I must not be grasping a larger principle here, so any explanations would be helpful.

这也是我对递归函数的第一次真正尝试,可能有更好的方法来构造它,因此,任何有关如何使事情更有效的建议

This is also my first real attempt at a recursive function and there probably is a better way to structure this, so any suggestions on how to change things up to be more effective is most welcome.

谢谢!

推荐答案

尝试像这样更改 happy_number_check (验证每行都是整数):

Try changing happy_number_check like this (validate each line is an integer):

def happy_number_check(file):
    with open(file, 'r+') as f:   # Safer way to open a file. Will automatically close for you even if something goes wrong
        for line in f:
            if line.strip().isdigit():
                happy_or_not(line.strip())

strip()也可以使它可以删除此代码:

The strip() will also make it so that you can remove this code:

if i == " ":
    continue
else:

顺便说一句,您的逻辑中也有一个错误。您依赖于RuntimeError-足够有趣的堆栈溢出:-)-终止测试。您应该真正跟踪尝试过的数字,如果再次尝试使用相同的数字,请返回0。

By the way, you also have a bug in your logic. You are relying on a RuntimeError - a Stack Overflow interestingly enough :-) - to terminate a test. You should really keep track of what numbers have been tried, and if you try the same number again, return 0.

如果您没有输入此数字,请不要单击此链接。想要直接解决该问题,但如果您这样做,可以使用以下迭代解决方案: http:// rosettacode .org / wiki / Happy_numbers#Python

Don't click this link if you don't want a straight up solution to the problem, but if you do, here is an iterative solution: http://rosettacode.org/wiki/Happy_numbers#Python

这篇关于Python:尝试将字符串转换为int,将以10为底的int()的错误转换为int无效文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆