0

i have a python code which should read in 2 integers from standard input till user presses Ctrl+D (i.e EOF) and do some processing .I tried the following code : n,k=map(int,[a for a in sys.stdin.read().split()]) Here , when i enter two integers the programme accepts it and when i press Ctrl+D it shows the correct output , like: 6 3 but when i put in 2 pairs in intergers like: 6 3 12 2 and then press Ctrl+D then instead of the desired result i get error that: [i]ValueError: Too many values to upack[/i] So how do i correct the code for it to work properly? I intend to have the shortest possible code for that Thanks.

2 Answers 2

4
>>> x=map(int,[a for a in sys.stdin.read().split()])
2 3 4 5
>>> x
[2, 3, 4, 5]

and work against the list; this so you will accept a variable number of ints if required to do so

Sign up to request clarification or add additional context in comments.

2 Comments

Why are you combining map with a pointless list comprehension? Use one or the other: map(int, sys.stdin.read().split()) or [int(a) for a in sys.stdin.read().split()]
i'm not; i used with fidelity whatever code was initially submitted and pointed out where the error was; the fact that there's a pointless list comprehension can be discussed after the initial problem is eliminated, you did it alright, cheers
3

The problem is not in how you read from stdin. Entering 6 3 essentially makes your code equivalent to

n, k = [6, 3]

which will work fine. Entering 6 3 12 2 though will result in

n, k = [6, 3, 12, 2]

which does not work, since you try to unpack a sequence of four values to only two targets. If you want to ignore everything beyond the first two numbers, try

n, k = [int(a) for a in sys.stdin.read().split()][:2]

If you want to iterate through the numbers read from stdin in pairs, you can use

numbers = (int(a) for a in sys.stdin.read().split())
for n, k in zip(numbers, numbers):
    # whatever

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.