I'm new to Python, I'm trying to ask the user for a number of elements needed, then ask to input each element in a separate line, then bubbles sort that input.
import readline
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 = readlines('Enter the list to sort \n', 'r').rstrip()
alist = alist.split(',')
bubbleSort(alist)
print alist.readlines()
If I changed readlines
to raw_input
, the code is working, but the input goes in only one line. Can someone help me out of how to specify the elements' number and how to get each input in a new line?
Python 3:
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
return alist
def main():
lines = []
print("Enter names (hit enter twice to bubble-sort):")
while True:
line = input("%3i: " % (len(lines)+1))
if not line:
break
lines.append(line)
print("Sorted names:")
for i, name in enumerate(bubbleSort(lines), 1):
print("%3i. %s" % (i, name))
main()
Input and output:
Enter names (hit enter twice to bubble-sort):
1: Mark
2: Jim
3: Kayne
4: Foobar
5: Zulu
6: Anna
7: Yeti
8:
Sorted names:
1. Anna
2. Foobar
3. Jim
4. Kayne
5. Mark
6. Yeti
7. Zulu