Peter Nydahl
Peter Nydahl

Reputation: 119

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'

Upvotes: 4

Views: 1102

Answers (4)

Subham
Subham

Reputation: 411

We can use abs if we are not sure about which one is large value

num = ''.join(sorted(input()))

res = abs(int(num) - int(num[::-1]))

print(res)

gives

32
9

Upvotes: 0

danidee
danidee

Reputation: 9624

Try this

number = input('Please enter a number')

number = sorted(number, reverse=True)

number = ''.join(number)

print(int(number) - int(number[::-1]))

number[::-1] reverses the string, it's a feature of python called slicing, generally the syntax of a slice is [start:stop:step] so leaving the first two arguments empty and filling -1 as the last, tells us to step through the list by negative 1, which starts from the last element, to the second to the last element whose index is -2 till it gets to the end of the string

iterables can also be sliced so this technique will work on tuples and lists

There are several answers on this question that explain more about slicing Explain Python's slice notation

Upvotes: 3

Try:

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

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

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

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

Using python 2.7. You have to use str() and int()

Upvotes: 2

timgeb
timgeb

Reputation: 78690

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)

Upvotes: 5

Related Questions