-1

Hello I am having trouble inputting two numbers from stdin using the following code as I am not quite yet familiar with this feature, when I input numbers manually the code seems to work properly but I can't get sys.stdin.readline to properly work.

import sys

def k(upto):
    def collatz(n):
        if n < upto and lst[n] > 0:
            return lst[n]
        if n % 2 == 0:
            val = collatz(n/2) + 1
        else:
            val = collatz((3*n + 1)/2) + 2
        if n < upto:
            lst[n] = val
        return val

    lst = [0]*upto
    lst[1] = 1
    lst[0] = 1
    for i in range(mini,upto):
        collatz(i)
    return max(lst)

line=int(sys.stdin.readline())
maxi = max(line)
mini = min(line)
print k(maxi)

The code produces the following error: TypeError: 'int' object is not iterable. Any assistance would be appreciated.

EDIT ::: Should have mentioned only two numbers will be input, one per line.

Roberto
  • 1
  • 1
  • 3

2 Answers2

0

The "one per line" is an important information :)

If you're reading one per line you're code is quite close - except you're reading only one line: your variable line is only one number - hence min and max can't work.

You could do something like

i1 = int(raw_input("Enter first number: "))
i2 = int(raw_input("Enter second number: "))
maxi = max(i1, i2)
mini = min(i1, i2)
...

note: If you switch to Python 3 (recommended) it's input() instead of raw_input()


old version:

What is the input? A list of integers, e.g. 2 3 5? This will be interpreted as a string "2 3 5". To convert this into integers you to have to do something like

line = [int(i) for i in sys.stdin.readline().split()]

This - will split() the input into an array of strings ["2", "3", "5"] and then - apply the int() conversion to each element of the array.

daten-kieker
  • 105
  • 7
  • Seems to be in the right direction, there will only be two numbers being input one per line. Will this make a difference? – Roberto Feb 01 '19 at 20:41
  • no, that's fine. With the other code you have this will work. It should actually work for more numbers, too. (On the other hand, for real-world code you would have to check that there are only two entries and both are convertable to int). If you trust your users to enter exactly two numeric values, the `mini, maxi = sorted(...)` trick from @wim is cool. – daten-kieker Feb 02 '19 at 21:18
0

After reading your comment, it looks like you want something like this

line = list()
for x in range(2):
    line.append(int(sys.stdin.readline()))

That will read 2 lines from STDIN, convert each line to an int, and append each value to line.

  • Doing that only gives me the first number as it appears the second number doesnt exist, should have been clearer the two numbers are being input in seperate lines like this. 1 5 – Roberto Feb 01 '19 at 21:44