+ 3
How to simplify this code?
In the range 1-100, print f for multiples of 3, print e FOR MULTIPLES OF 5. THE CODE I WROTE IS TOO LONG, PLEASE HELP SIMPLIFY IT. THANKS. https://code.sololearn.com/c7eQdD28JWW1/?ref=app
11 odpowiedzi
+ 6
Jessica,
the code you presented here looks really good, no compelling reason to compress or optimize it. It has a good readability, and is easy to maintain.
This task looks like a homework or something like this. So if you expect some help from us, please present us first your try for an "optimized" version here. Thanks!
+ 2
It is too long?
You can cut this lines according to your question
if i%3==0 and i%5==0:
print ("f","e")
+ 2
It should be like this
for i in range (1,101):
if i%3==0 and i%5==0:
print (i)
else:
continue
+ 2
You can or Syntax in python
+ 1
sometimes saying that your code is too long is because you see it so, I do this to get rid of thoughts like that:
for i in range (1,101):
if i%15==0: print('f e')
elif i%3==0: print('f')
elif i%5==0: print('e')
else: print(i)
Just organize it the way you like it. I have done some improvements for you.
+ 1
print(*list('f,e' if i%3==0 and i%5==0 else 'f' if i%3==0 else 'e' if i%5==0 else i for i in range(1,101)))
or with commas
print(",".join(list('f e' if i%3==0 and i%5==0 else 'f' if i%3==0 else 'e' if i%5==0 else str(i) for i in range(1,101))))
0
i mean if i is a multiple of 3, it prints f. if i is a multiple of 5, it prints e. for example : 1,2,f,4,e,f,7,8,f,....
And for the common factor of 3and5, it prints f and e. Just want to make it using one condition only. Now it is 3 conditions.
0
can it be simplified by just one pair of if,else condition?
0
Here is a simplified version
For i in range( 1, 100)
#this won't include 100
if i%3 == 0 and i%5 == 0: print('fe)
elif i%3 == 0: print('f')
elif i%5 == 0: print('e')
0
#I have simplified this code
print(*[(('f' if i%3==0 else i and 'e' if i%5==0 else i) if i%15 else 'fe') for i in range(1,101)],sep='\n')
- 1
Hello Jessica , you code is well written and easy to understand.
Here is code using only one if else.
li=[-1,'f','e','fe']
for i in range (1,101):
if i%3 == 0 or i%5 ==0:
print (li[(i%3==0)*1+(i%5==0)*2])
else :
print (i)