How to ask for an input and bubble sort that input?

Question:

It’s my first time in coding in Python, I have created a code that bubbles sort a given list. This is my code:

def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp

alist = ["hi",50,93,"/",77,31," ",55,20]
bubbleSort(alist)
print(alist)

I am trying to ask the user for the list instead of storing the list in the code, but I have no idea of how to do that in Python. Would someone help me out with it.

Asked By: user3467152

||

Answers:

One possible way is to read the arguments as commandline arguments. Some kind like this:

import sys

def main():
    # Some Code
    for arg in sys.argv[1:]:
         print(arg)

if __name__ == '__main__':
    main()

Another way is to read the input at runtime with “raw_input ()”:

s = raw_input()
numbers = map(int, s.split())
Answered By: user3305988

Take a look at Python’s built-in methods and functions: raw_input and split.

def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp

alist = raw_input('Enter the list to sort (seperated by spaces): ').rstrip()
alist = alist.split(' ')

bubbleSort(alist)
print(alist)
Answered By: GoofyBall
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.