Peter Nydahl
Peter Nydahl

Reputation: 119

How to use calculated results in a repetitive algorithm

This is what I want to accomplish:

  1. let the user type in a number with four digits
  2. if this number is not equal to 6174 (Kaprekar’s constant) then sort the numbers in two ways: a. from the biggest to the smallest number b. from the smallest to the biggest
  3. Subtract the bigger number with the smaller
  4. If the result is not equal to 6174, then do the calculation again and write the result for each and every calculation
  5. When the result is equal to 6174, write a message to show that the calculation is done

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

Answers (4)

Santos
Santos

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

poke
poke

Reputation: 387617

You have multiple issues with your solution:

  1. 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.

  2. 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

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

bmbigbang
bmbigbang

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

Related Questions