'I need to optimize a program that goes through numbers [closed]
My goal is to create a program that takes numbers from 1 to 100, if a number can be divided by 3, it gives Jack, if divided by 5 Pot, and if a number can be divided by both 3 and 5 it gives JackPot The below code works, but I was told it can be optimized but I do not see how
a = 0
while a < 100:
list = []
a = a + 1
if a % 3 == 0:
list.append("Jack")
if a % 5 == 0:
list.append("Pot")
elif a % 3 and a % 5 == 0:
print("JackPot")
if list != []:
print(*list)
else:
print(a)
Solution 1:[1]
Your big error is thinking that the elif is meaningful. Note that a % 3 and a % 5 == 0 means (a % 3 != 0) and (a % 5 == 0) which is probably not what you want. In any case you cannot reach here unless (a % 5 == 0) is false so the elif branch will never be taken. (You also print "Jack Pot" instead of "JackPot").
I can see a couple of minor tweaks, that may make the code marginally faster. As this run time of this code is heavily dominated by the i/o this does not matter.
Remember the rule of code optimisation: Don't do it. There is also a rule for experts: Don't do it yet.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | William |
