4

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'
timgeb
  • 76,762
  • 20
  • 123
  • 145
Peter Nydahl
  • 119
  • 1
  • 9

4 Answers4

5

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)
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • It worked! Thanks! My first post and I got an answer in less then one minute! Excelent site and thanks again! Cheers from Sweden :) – Peter Nydahl Feb 14 '16 at 12:40
  • 1
    @PeterNydahl you got an answer fast because you included what you want to do and what you have tried in your question. Next time also include the full error message and you'll be good. – timgeb Feb 14 '16 at 12:41
3

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

Community
  • 1
  • 1
danidee
  • 9,298
  • 2
  • 35
  • 55
2

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()

0

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
Subham
  • 397
  • 1
  • 6
  • 14