Cycling the digits of a 5 digit number in a function

Viewed 87

I'm trying to solve this problem but I'm just stuck at the very end.

I need to make a function that cycles the 5 digit number around. So for example, the input is 12345 and then it should be 51234, 45123 etc. Then when it cycles it out, until it's at the beginning again which is 12345, it should print out the biggest number of all of the cycled ones.

def number_cycle(number):
    if number >= 99999 or number < 9999:#this is for limiting the number to 5 digits
        print('Error,number isnt in 5 digit format')
    else:
        e = number%10 #5th digit
        d = int(((number-e)/10)%10)#4th digit
        c = int(((((number - e)/10)-d)/10)%10)#3rd digit
        b = int(((((((number - e)/10)-d)/10)-c)/10)%10)#2nd digit
        a = int(((((((((number - e)/10)-d)/10)-c)/10)-b)/10)%10)#1st digit
        print(e,a,b,c,d)
        print(d,e,a,b,c)
        print(c,d,e,a,b)
        print(b,c,d,e,a)
        print(a,b,c,d,e)
        
   number = eval(input('Input number:'))

I can't figure out how to get the biggest number out of all these.

Can you help?

1 Answers

You can try this solution:

def get_largest(number):
    num_str = str(number)
    num_len = len(num_str)

    if num_len != 5:
        print(f"Error: {number} is not a 5 digit number")
        return

    largest = 0
    for i in range(num_len):
        cycled_number = int(num_str[i:] + num_str[:i])
        print(cycled_number)

        if cycled_number > largest:
            largest = cycled_number

    print("Largest: ", largest)


number = int(input("Input number: "))
get_largest(number)

It will basically convert your 5 digit number to a string using a for loop, and then rotate the string, compare the rotated numbers and print the largest one.

Note:

In your original code snippet I'd suggest not to use the built-in eval method as it can be quite dangerous if you don't know what you are doing so avoid it as much as you can except you really have no other way to deal with a problem. More here:

Related