I am beginner in Competitive programming and getting started. Familiar with C and C++, but Python is what I am learning.I am facing difficulty in input in Python Problem is like : For given number of test cases, for ech test case , you will be provided with a number N and another number K, in same line. After this line, there will be N integers in a single line. You just have to divide and sum up like given below (brackets are just to keep track)
1 #test cases
3 2 #N #K
4 5 7 #N integers
Answer would be sum : 7
that is 4/2 + 5/2 + 7/2 = 7 (int division)
I have written a simple Python 2.7 program to accept input and perform operation.
t = map(int,raw_input())
t = t[0]
while t>=0:
count=0
n,k = map(int,raw_input().split())
candies = map(int,raw_input().split())
for candy in candies:
count += candy/k
t -= 1
I am getting error :
vivek@Pavilion-dv6:~/Desktop$ python kids_love_candies.py <in.txt >out.txt
Traceback (most recent call last):
File "kids_love_candies.py", line 6, in <module>
n,k = map(int,raw_input().split())
EOFError: EOF when reading a line
Another link suggests to read input using sys.stdin.readline()
but I have no idea how to apply it to my problem.
Which one should I use and why?Which is the correct way to learn and use them?
You're trying to read one too many lines, your while condition should be > 0
. But this whole thing is more complicated than need be
t = int(raw_input()) # no need to map
for _ in range(t): # loop with range instead of manual counting
# loop body
When I want to loop over lines from stdin, I generally use sys.stdin
instead. In that case you could ignore the count
raw_input() # ignore the size
for line in sys.stdin:
n, k = (int(i) for i in line.split())
count = sum(int(c) for c in raw_input.split()) / k