Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to sort a number in two ways and then subtract the numbers

I'm new to programming and have a Python-question!
What I want to do is:

  1. Let the user type in a number (for ex 4512)

  2. Sort this number, starting with the biggest digit (5421)

  3. Sort the same number but starting with the smallest digit (1245)

  4. Subtract the two numbers (5421-1245)

  5. Print out the result

Here is what I have tried:

print("type in a number")
number = (input())

start_small = "".join(sorted(number))

start_big = "".join(sorted(number, reverse=True))

subtraction = ((start_big)-(start_small))
print(subtraction)

I'm getting the error

TypeError: unsupported operand type(s) for -: 'str' and 'str'
like image 722
Peter Nydahl Avatar asked Dec 24 '22 09:12

Peter Nydahl


1 Answers

You forgot to convert the numbers to integers before doing arithmetic with them. Change the line where you do the subtraction to

subtraction = int(start_big) - int(start_small)
like image 101
timgeb Avatar answered Feb 16 '23 00:02

timgeb