[Python] I am stuck with a python generator problem. Every time i run it, only one case always...

Discussão em 'Python' iniciado por Stack, Abril 15, 2025.

  1. Stack

    Stack Membro Participativo


    The Order of the Phoenix is a secret society founded by Albus Dumbledore to oppose Lord Voldemort and his Death Eaters. Now they need your help to enter their club. Help them to create a program that reverses the number entered by them. But it should consider only the even number in the digits. This will be the new password for their club.

    Get an integer number from the user and if the number is less than 2 digits or negative or should contain only 0's, then it should print "Invalid input".

    Use function and generator concept (yield the value instead of using 'return') for reversing and returning the reversed number from the function. The function name should be: reverse_number(number);
    ​

    Sample Input 1:

    Enter the number: 1234

    Sample Output 2:

    Your new password is: 42

    Sample Input 2:

    Enter the number: 0

    Sample Output 2:

    Invalid input

    Below is the boilerplate code given in editor:

    def reverse_number(no):
    #Fill your code here



    pass # remove this line once you completed the program


    number = int(input("Please enter the number: "))
    if number < 10:
    print("Invalid input")
    else:
    reverse=reverse_number(number)

    # Write the code for displaying the generator object values


    Here is my code that I am trying :

    # Collect even digits in reverse order
    def reverse_number(no):
    # Check if the input is valid
    if no < 10 or all(digit == '0' for digit in str(no)):
    yield "Invalid input"
    return

    # Collect even digits in reverse order
    for digit in reversed(str(no)):
    if int(digit) % 2 == 0:
    yield digit

    number = int(input("Please enter the number: "))

    if number < 10:
    print("Invalid input")
    else:
    reverse = reverse_number(number)

    # Write the code for displaying the generator object values
    result = ''.join(reverse)
    if result == "Invalid input": # Fixed syntax error here
    print(result)
    else:
    print(f"Your new password is: {result}")


    Here is the evaluation result:


    Fail 1 ::
    The values in the generator object returned by the 'reverse_number' method are not correct. Check the name and logic of the function
    ​

    Continue reading...

Compartilhe esta Página