質問

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?

役に立ちましたか?

解決 3

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

他のヒント

try this:

bubbleSort([raw_input('Enter element') for _ in range(input('Enter the number of elements needed'))])

That one liner should do the trick

EXPLAIN:::

Essentially what we're doing here is three things once you undo the list comprehensions and the pythonic format.

#Asking for the number of elements needed and making a loop that will repeat that many times
for _ in range(input('Enter the number of elements needed')):

    #in each loop, retrieve an element from the user and put it into a list for later
    listvariable.append(raw_input('enter element'))

#Then at the end we're taking that list and putting it through the bubbleSort
bubbleSort(listvariable)

that code is simplified using list comprehension in the one line solution above.

I believe this is the basics of what you're looking for.

ntimes = raw_input("Enter the number of lines")

ntimes = int(ntimes)

alist = []

while (ntimes > 0):
    ntimes -= 1
    alist.append(raw_input('Enter the list to sort \n').split(','))

print alist
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top