0

I'm doing the problem described here:

I understand the code has this error in python 3:

File "main.py", line 3, in <module>
    Test.assert_equals(seven (1603), (7, 2))
  File "/home/codewarrior/solution.py", line 7, in seven
    newM = int(s[:(len(s)-1)]);
ValueError: invalid literal for int() with base 10: '-'

Where/Why is their a difference in evaluation?

def seven(m):
    count=0;
    while(m/100 != 0):
        s = str(m);
        lastdigit = int(s[len(s)-1]);
        if(len(s)>1):
            newM = int(s[:(len(s)-1)]);
        count+=1;
        m = newM - 2*lastdigit;

    return (m,count);
mindahl
  • 77
  • 7

2 Answers2

1

Because the while loop does not have the same stop condition. In Python2 m/100 returns the truncated result as an integer, while in Python3 it returns the exact result as a float

Louis Saglio
  • 1,120
  • 10
  • 20
1

this has different behaviour in python 2 or 3

while(m/100 != 0):

In python 2, if m < 100 the result is 0 and the loop stops.

In python 3, it doesn't.

Quickfix is to always use integer division

while m//100 != 0:  # or just: while m//100:

this will work the same (and properly as you expect) on any python version

At this point you could save a division and test absolute value of m instead of dividing and dropping the result:

while abs(m) >= 100:
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219