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.

Was it helpful?

Solution 2

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)

OTHER TIPS

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())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top