Skip to content Skip to sidebar Skip to footer

How To Manually Sort A List Of Numbers In Python?

Specs: Ubuntu 13.04, Python 3.3.1 Background: total beginner to Python, came across this 'manual sorting' problem. What I was asked to do: 'Have the user enter 3 numeric values

Solution 1:

For three items, you could use max and min to sort them:

a, b,c=3,1,8

x =min(a, b,c)# Smallest of the three
z =max(a, b,c)# Largest of the three
y =(a + b +c)-(x + z)# Since you have two of the three, you can solve for# the third

print(a, b,c)
print(x, y, z)

If you don't want to use a sorting algorithm but can use lists, you could just pop out the smallest item each time and store it in a new list:

numbers = [1, 8, 9, 6, 2, 3, 1, 4, 5]
output = []

while numbers:
    smallest = min(numbers)
    index = numbers.index(smallest)
    output.append(numbers.pop(index))

print(output)

It's pretty inefficient, but it works.

Solution 2:

Using the Bubble Sort Algorithm:

num1=input("Enter a number: ")
num2=input("Enter another number: ")
num3=input("One more! ")
if num1<num2:temp=0temp=num1num1=num2num2=tempifnum1<num3:temp=0temp=num1num1=num3num3=tempifnum2<num3:temp=0temp=num2num2=num3num3=tempprintnum3, num2, num1

Solution 3:

For Sorting a list manually, you can implement any kind of sorting algorithm like bubble sort, selection sort, insertion sort etc. so you can try the following code of bubble sort

#Bubble sort in pythondefbubbleSort(numbers):
  for i inrange(len(numbers)):
    for j inrange(len(numbers)-i-1):
      if(numbers[j]>numbers[j+1]):
        temp=numbers[j]
        numbers[j]=numbers[j+1]
        numbers[j+1]=temp
        
#taking space seperated numbers as input in list
numbers=list(map(int, input().split(' ')));
bubbleSort(numbers)
print(numbers)

Post a Comment for "How To Manually Sort A List Of Numbers In Python?"