Issue
I am new to python. I am learning list comprehension to shorten my code to minimum. But I am unable to incremnent inside a list comprehension. Like this code:
n = 0; c = 0
for i in range(input()):
m = map(int,raw_input().split())
[n+=1 if m[0] > m[1] else c+=1]
print ['N', 'C'][c > n]
My input:
3
3 4
2 4
2 5
The output should be:
N
Solution
You do not actually need to keep track of both n
and c
, since you can calculate one from the other and the total (your first input).
t = input()
n = 0
for i in range(t):
a, b = map(int, raw_input().split())
n += (a > b)
print 'N' if n >= t/2 else 'C'
If you really want to make this shorter (note: except for Code Golf, shorter does not always mean better) you could try something like this:
t = input()
n = sum(1 for i in range(t) for a, b in [map(int, raw_input().split())] if a > b)
print 'N' if n >= t/2 else 'C'
Or without t
, use cmp
(retired in Python 3) to count +1
for a > b
and -1
for a < b
, then compare to 0
. But this will handle the case a == b
differently, and the readability finally goes down the drain.
n = sum(cmp(*map(int, raw_input().split())) for _ in range(input()))
print 'N' if n >= 0 else 'C'
Answered By - tobias_k
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.