[Tutor] I'm having a small problem with my code

Cameron Simpson cs at cskk.id.au
Thu May 23 19:34:33 EDT 2019


On 23May2019 15:16, David Lifschitz <davidthebiglipperlifschitz at gmail.com> wrote:
>I am currently working on a project for myself.
>The code posted here is supposed to ask the user for an amount of numbers,
>what those numbers are, and places those numbers in a list.
>The next job of the code is to sort the list of numbers that were inputted
>in an ascending fashion.
>There is no error from the code,

Regardless, it clearly isn't doing what you want. In this situation it 
is helpful (to us, and therefore to you later) to post the output from a 
run and an example of the output you wanted, and and description of what 
is deficient in the programme output. You've got the last 2 of these 3.

>however, when I run the code the first
>inputted number stays in its place and doesn't get sorted with the rest of
>the numbers.

Comments below the code.

>emptyList = []
>nOFN = int(input("how many numbers do you want to sort: "))
>
>for x in range(nOFN):
>    number1 = int(input("input number: "))
>    emptyList.append(number1)
>firstElement = emptyList[0]
>n = len(emptyList)
>for j in range(1, n):
>    if emptyList[j-1] > emptyList[j]:
>        (emptyList[j-1], emptyList[j]) = (emptyList[j], emptyList[j-1])
>print(emptyList)

Well, you only make one pass over the list. So if emptyList[0] <= 
emptyList[1] _on the first (and only) pass_, it will not move.

Try comparing:

  2 5 3

and:

  3 2 5

and see if the behaviour differs.

BTW, what you['re implementing looks like a bubble sort to me (look it 
up). But a since pass over the list isn't enough to sort the whole 
thing.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list