简体   繁体   中英

Can someone explain to me why python 3.4 is parsing a string to an int without me explicitly asking for it

I am so confused it's beyond belief, it's probably a noobie mistake, but I am thoroughly befuddled by this behavior. Here's the small algorithm (as I think it should be):

a, b, n = input().split()
x = 0

def prod(num):
    x=1
    for y in range(len(num)):
        if int(num[y])>0:
           x*=int(num[y])
    x+=int(num)
    return x

while x < int(n):
    a, b = b, prod(b)+prod(a)
    print(b, end=' ')
    x+=1

and here's how I apparently have to do it to make it work:

a, b, n = input().split()
x = 0

def prod(num):
    x=1
    for y in range(len(str(num))):
        if int(str(num)[y])>0:
           x*=int(str(num)[y])
    x+=int(num)
    return x

while x < int(n):
    a, b = b, prod(b)+prod(a)
    print(b, end=' ')
    x+=1

so if it isn't clear, my problem is in the prod function. it seems to convert the string to an int for no apparent reason.

the input I'm giving it is 1 100 3 and is supposed to be of that format.

Python is not implicitly turning your string into an integer, no. Instead, you are giving your function an integer.

You are returning an integer from prod() and in the next operation, you pass that integer to the prod() function.

The steps are:

  1. a, b, n = '1', '100', '3'
  2. call prod('100') + prod('1') , produces 101 + 2 is 3 , an integer.
  3. a, b = '100', 3 , so now b is an integer, go to the next iteration.
  4. call prod(3) + prod('100') ; you are passing in an integer to your function.

Perhaps you need to convert the sum to return a string from prod() instead? Change your return statement to:

return str(x)

or perhaps the sum of the prod() results should be a string:

a, b = b, str(prod(b) + prod(a))

You can simplify your function to just iterating over num directly, and use the fact that single characters have an order too:

def prod(num):
    x = 1
    for digit in num:
        if digit > '0':
           x *= int(digit)
    x += int(num)
    return x  # or `str(x) if a string is expected

Your while loop should just be a for loop with range() :

for iteration in range(int(n)):
    a, b = b, str(prod(b) + prod(a))
    print(b, end=' ')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM