Question

Beginner at Python and trying to code this program:

a = 0
number = int(input("Choose a four digit number: "))

while number != 6174:                                    #Kaprekar's constant 
   sorted(number) 
   sorted(number, reverse=True)

   large = "".join(sorted(number, reverse=True))
   small = "".join(sorted(number))
   number = (int(large) - int(small))
   a += 1
print(a + "iterations.")

I get the following error:

sorted(number)     
TypeError: 'int' object is not iterable

So how can I sort the digits of number and get another number?

Était-ce utile?

La solution

First, putting sorted around an iterable doesn't change the iterable itself. You need to do something like a = sorted(a).

Now as for your example, you are trying to work with number as both an int and a str. You need to convert between str and int when necessary here:

a=0
number = input("Choose a four digit number: ")

while number != "6174":
    large = "".join(sorted(number, reverse=True))
    small = "".join(sorted(number))
    number = str(int(large) - int(small))
    a+=1
print(a, "iterations.")

Finally, a is an int, so you can't do int+str in the last print statement. Either put a comma like I have or do print(str(a)+" iterations").

Autres conseils

For that, you can simply do:

number = input("Choose a four digit number: ")

Now your sorted will work

Thanks to @SimonT for the suggestion.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top