Reputation: 119
This is what I want to accomplish:
This is what I’ve tried:
print("type in a number")
number = (input())
while number != 6174:
start_big = "".join(sorted(number, reverse=True))
start_small = "".join(sorted(number))
number = (int(start_big)-int(start_small))
print(number)
print("Calculation finnished!")
I’m getting the error:
start_big = "".join(sorted(number, reverse=True)) TypeError: 'int'
object is not iterable
Upvotes: 0
Views: 135
Reputation: 194
When you calculate this:
number = (int(start_big)-int(start_small))
The type of number
becomes int
, so in the next iteration the error occurs.
One solution would be
print("type in a number")
number = input()
while number != "6174":
start_big = "".join(sorted(number, reverse=True))
start_small = "".join(sorted(number))
number = str((int(start_big) - int(start_small)))
print(number)
print("Calculation finnished!")
Upvotes: 1
Reputation: 387617
You have multiple issues with your solution:
input()
always returns a string, so number
will never be an integer and as such it will never be equal to 6174
. So your loop will still run for an input of 6174
.
You need to convert the string into a number first, you can do that by simply calling int()
on the string. Note that this may fail, so you might want to ask the user for input until they enter a valid number.
Once number
is an integer, it is no longer an iterable, so you cannot call sorted()
on it. If you want to sort the digits, then you need to convert it into a string first: sorted(str(number))
.
Upvotes: 0
Reputation: 28987
You are almost there. You need to convert number
to an iterable. I suggest:
start_big = "".join(sorted(str(number), reverse=True))
start_small = "".join(sorted(str(number)number))
Upvotes: 0
Reputation: 1378
you have to convert the input number to an iterable, you can just do
number = iter(number)
also you need to change the while loop condition:
while int(number) != 6174:
for printing the number just do this:
number = str((int(start_big)-int(start_small)))
Upvotes: 0