Search code examples
pythonlistfizzbuzz

I need to optimize a program that goes through numbers


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

  • 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)]