MicroPython on Casio fx-CG50 returns "BuzzFizz" on FizzBuzz(15)

Question:

Using the fizzbuzz program below on Python 3.10 on Windows 10 (64-bit) gives the output

1
2   
Fizz
4   
Buzz
(...)
14
FizzBuzz

Whereas running it on MicroPython 1.9.4 on a Casio PRIZM fx-CG50 (a graphing calculator) gives the following output

1
2
Fizz
4
Buzz
(...)
14
BuzzFizz

The last line of the above output is highly unexpected based on my understanding of how my fizzbuzz program works and differs between Python on Windows and MicroPython on the calculator. Help diagnosing this irregularity and any advice on who to alert(if any) for a fix(if needed) would be greatly appreciated.

Perhaps the way I have written the program causes the execution order to be ambiguous, or there is some implementation detail I have overlooked.

The exact same program file was run on both systems.

No warnings or errors came up on both runs.

The fizzbuzz program:

def fizzbuzz(num: float, ruleset: dict) -> str:
    output = "" # Declare Output string
    
    rule_string = ruleset # Vanity variable for readability
    # Ruleset is dict in format {float:str, float:string, ...}
    # The floats are the divisors, the strings are the rulestrings
    
    # If divisor is factor of num append corresponding rule_string to output
    for divisor in ruleset:
        output += rule_string[divisor] if (num%divisor)==0 else ""
    
    # If no divisors are factors of num(output is empty string),
    #  append num to output
    output += str(num) if output == "" else ""

    return output

# The classic fizzbuzz ruleset
classic_fizzbuzz_ruleset = {
    3:"Fizz",
    5:"Buzz"
}

# Test for numbers 1 to 50 inclusive with classic_fizzbuzz_ruleset
for i in range(1, 16):
    print(fizzbuzz(i, classic_fizzbuzz_ruleset))
Asked By: AzureArmageddon

||

Answers:

Here your code is looping through the keys of a dictionary:

# If divisor is factor of num append corresponding rule_string to output
for divisor in ruleset:
    output += rule_string[divisor] if (num%divisor)==0 else ""

In Python 3.6 and later, the default dict implementation is an OrderedDict. (See Are dictionaries ordered in Python 3.6+?) That appears to not be the case in MicroPython 1.9.4 running on your calculator, so the keys aren’t guaranteed to be in the order you specified when you created the rules dictionary.

Try making the ruleset an OrderedDict to see if you get the expected behavior, or change it to a list of tuples.

Answered By: Bill the Lizard
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.