2017-04-01 104 views
1

你好我是python的新手,并决定练习写一些算法。 我想解决的问题可以在这里找到,如果感兴趣>http://codeforces.com/problemset/problem/791/A为什么在尝试在while循环中覆盖变量时会出现内存错误? (Python)

这是我写的代码来解决这个问题。

a = input("Enter Limak's weight:") 
b = input("Enter Bob's Weight:") 
i = 0 

while (a < b): 
    a = (a * 3) 
    b = (b * 2) 
    i= (i + 1) 

print(i) 

当我尝试运行我收到以下错误 -

Enter Limak's weight:4 
Enter Bob's Weight:7 
Traceback (most recent call last): 
    File "s.py", line 6, in <module> 
    a = (a * 3) 
MemoryError 

任何想法的代码?

+4

Python 2或Python 3?这听起来像你在Python 3上,而你正在乘以字符串而不是整数或浮点数。 – user2357112

回答

1

我不能用python 2.7.12重现你的崩溃。 假设你正在使用python 3,我的猜测是你的变量a和b的类型是str而不是int。 从控制台中读取它们后,您需要将它们投射为int

尝试改变:

a = input("Enter Limak's weight:") 

有:

a = int(input("Enter Limak's weight:")) 

而且有一些小技巧,在Python可以编写表达式:

i = i * 1 

i += 1 

正如@Pfonks指出的,这个表示法适用于大多数运算符,如*, - 或/

+0

也可以a = a * 3替换为* = 3.我只是测试它。没有int()函数,我得到一个无限循环。它使用int()函数工作。 – Pfonks

+1

对不起,忘记提及我使用python3.4感谢您的答案:) –

+0

我使用python 3.5重现了无限循环;) – Pfonks

相关问题