CS50P Introduction to Programming. Problem Set 4 Problem "Little Professor"

Question:

I am trying to get my program to pass the automated test "Little Professor generates 10 problems before exiting" but I keep gettin the error "Cause: timed out while waiting for program to exit". I have checked that the program handles edge cases, non-integer inputs, and it always exits after 10 problems. Am I missing something something obvious?

Here is my code:

import random
import sys

def main():
    op1_list = []
    op2_list = []
    score = 0
    level = get_level()

    for i in range(10):
        OP1 = generate_integer(level)
        OP2 = generate_integer(level)

        while OP1 in op1_list:
            OP1 = generate_integer(level)

        while OP2 in op2_list:
            OP2 = generate_integer(level)

        ans = OP1 + OP2
        op1_list.append(OP1)
        op2_list.append(OP2)
        print(OP1, "+", OP2, "= ",end="")

        for n in range(3):
            try:
                user_ans = int(input())
                if user_ans == ans:
                    score += 1
                    break
                else:
                    print("EEE")
                    print(OP1, "+", OP2, "= ",end="")
                    if n == 2:
                        print(OP1, "+", OP2, "=",ans)
                        break
            except ValueError:
                print("EEE")
                print(OP1, "+", OP2, "= ",end="")
                if n == 2:
                    print(ans)
                    break

    print(f"Score: {score}")
    sys.exit()

def get_level():
    while True:
        print("Level: ",end="")
        try:
            level = int(input())
            if (level > 3):
                raise ValueError
            elif (level < 1):
                raise ValueError
            else:
                return level
        except ValueError:
            pass

def generate_integer(level):
    match level:
        case 1:
            return random.randint(0,9)
        case 2:
            return random.randint(10,99)
        case 3:
            return random.randint(100,999)

if __name__ == "__main__":
    main()
Asked By: NullTerminator

||

Answers:

It fails because you filter out operands if they were already used.

Basically if you will remove the following section, the checks pass.

while OP1 in op1_list:
  OP1 = generate_integer(level)

while OP2 in op2_list:
  OP2 = generate_integer(level)

You should also remove all relevant code around the filtering, as it is not really necessary for the exercise.

Answered By: Igor Basko
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.