Home > Net >  I need to optimize a program that goes through numbers
I need to optimize a program that goes through numbers

Time:02-26

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)

CodePudding user response:

Try this:

        for a in range(1, 101):
            print(f"{'Jack' if not a % 3 else ''}{'Pot' if not a % 5 else ''}{a if a % 3 and a % 5 else ''}")        

It uses an f-string to print the Python expressions inside the curly brackets.

'Jack' if not a % 3 else '' prints Jack only if not a % 3, in other words if a % 3 is zero. Similarly for 'Pot' if not a % 5.

The third set of curly brackets prints a if a % 3 and a % 5 else '', in other words, prints a if neither a % 3 or a % 5 is zero.

Output is:

1
2
Jack
4
Pot
Jack
7
8
Jack
Pot
11
Jack
13
14
JackPot
16
17
Jack
19
Pot
Jack
22
23
Jack
Pot
26
Jack
28
29
JackPot
31
32
Jack
34
Pot
Jack
37
38
Jack
Pot
41
Jack
43
44
JackPot
46
47
Jack
49
Pot
Jack
52
53
Jack
Pot
56
Jack
58
59
JackPot
61
62
Jack
64
Pot
Jack
67
68
Jack
Pot
71
Jack
73
74
JackPot
76
77
Jack
79
Pot
Jack
82
83
Jack
Pot
86
Jack
88
89
JackPot
91
92
Jack
94
Pot
Jack
97
98
Jack
Pot

If you'd like something even shorter, here is a one-liner which does essentially the same thing but with the for-loop iteration inside a list comprehension:

        [print(f"{'Jack' if not a % 3 else ''}{'Pot' if not a % 5 else ''}{a if a % 3 and a % 5 else ''}") for a in range(1,101)]

CodePudding user response:

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.

CodePudding user response:

You can do it using for loop and range() like this:

list = []
for i in range(100):
    if i % 3 == 0:
        list.append("Jack")
    if i % 5 == 0:
        list.append("Pot")
    if i % 3 and a % 5 == 0:
        print("JackPot")

if list != []:
    print(*list)
else:
    print("Empty")
  • Related