In trying to use list comprehension more often I tried to code golf an assignment. So this works:
if fraction[0] % i == 0 and fraction[1] % i == 0:
fraction = [fraction[x]/i for x in range(2)]
But this doesn't work:
fraction = [fraction[x]/i for x in range(2) if fraction[0] % i == 0 and fraction[1] % i == 0]
It gives a list index out of range
error
Fraction is a two item list and the if statement has a specific indices which should never be out of range... thoughts?
The issue is that in the second case, fraction
always gets overridden.
So for example, if fraction = [2, 4]
and i = 3
, your list comprehension will result in fraction == []
, while the loop will just do nothing.
UPDATE
Here's the code I tested with:
def a(fraction, i):
if fraction[0] % i == 0 and fraction[1] % i == 0:
fraction = [fraction[x] // i for x in range(2)]
return fraction
def b(fraction, i):
fraction = [fraction[x] // i for x in range(2) if fraction[0] % i == 0 and fraction[1] % i == 0]
return fraction
print(a([2, 4], 3)) # Output: [2, 4]
print(b([2, 4], 3)) # Ouptut: []
GOLF UPDATE
I think if you can reverse the order you're testing values in, your list comprehension can work. Eg:
f = next([n//i for n in f] for i in range(max(f),0,-1) if all(n%i==0 for n in f))
Test:
for fraction in ('2/4', '1/5', '4/2', '1/9'):
f = [int(x) for x in fraction.split('/')]
f = next([n//i for n in f] for i in range(max(f),0,-1) if all(n%i==0 for n in f))
print('/'.join(map(str,f)))
# Output:
# 1/2
# 1/5
# 2/1
# 1/9
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.