0

I'm new to python and trying to take some coding challenges to improve my skills. I've to take input in following ways:

 2
 3 1
 4 3

First, I get number of test cases.(2 here) Then based on that, I've to get given number of test cases that are each 2 integers. 1st is the range and second is the number to be searched in the range.

What's the correct, pythonic way of getting the input. I was thinking like this but it's obviously incorrect

num_testcases = int(raw_input())
for i in num_testcases:
    range_limit = int(raw_input())
    num_to_find = int(raw_input())
1
  • 1
    Downvote? Any reason? Like I said I'm beginner :/ Commented Aug 16, 2014 at 7:25

2 Answers 2

1

raw_input() is going to be read one line at a time from STDIN, so inside the loop you need to use str.split() to get the value of range_limit and num_to_find. Secondly you cannot iterate over an integer(num_testcases), so you need to use xrange()(Python 2) or range()(Python 3) there:

num_testcases = int(raw_input())
for i in xrange(num_testcases): #considering we are using Python 2
    range_limit, num_to_find = map(int, raw_input().split())
    #do something with the first input here 

Demo:

>>> line = '3 1'
>>> line.split()
['3', '1']
>>> map(int, line.split())
[3, 1]

Note that in Python 3 you'll have to use input() instead of raw_input() and range() instead of xrange(). range() will work in both Python 2 and 3, but it returns a list in Python 2, so it is recommended to use xrange().

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

Comments

1

Use for i in range(num_testcases): instead of for i in num_testcases. Have a look at range (or xrange in Python 2). range(a) produces an iterable from 0 to a - 1, so your code gets called the desired number of times.


Also, input and raw_input take input on encountering a newline, meaning that in range_limit = int(raw_input()), raw_input returns "3 1", which you can't just convert to int. Instead, you want to split the string using string.split and then convert the individual items:

num_testcases = int(raw_input())
for i in range(num_testcases):
    range_limit, num_to_find = [int(x) for x in raw_input().split()]

5 Comments

range produces actually a list in python 2. Use xrange here.
Very correct (I was not sure which version OP is on, because he tagged it both 2.7 and 3.x)
What about the inputs that I need? Based on num_testcases I need to dynamically num_testcases*2 inputs
@Maxsteel Added that now - @Daniel Just noticed raw_input instead of input (d'oh)
Now both the answers are almost same and both works. Wasn't sure which one to accept. +1 to you. Thanks a lot for help.

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.