Maxsteel
Maxsteel

Reputation: 2040

Create variables dynamically inside 'for' loop

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())

Upvotes: 0

Views: 80

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

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().

Upvotes: 1

hlt
hlt

Reputation: 6317

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()]

Upvotes: 1

Related Questions