user13798483
user13798483

Reputation:

order a list of numbers from given list without built-in sort, copy

in python i try to implement my code in a way that it does basically the same thing as sorted(lst) without using sorted(lst) or var = lst.copy() but i just can't figure it out how to work it that way and following exactly the way as it is written in the pseudo code.

can someone please help me ?

my assesment is:

Below is the pseudocode of a sorting algorithm:

  1. Starting from the beginning of a list, compare each element with its next neighbor.
  2. If the element is larger than its next neighbour, change them places.
  3. Go through the list to the end.
  4. If there have been any mix-ups at step 2,go to step 1

my code right now :


    lst_sorted = lst.copy()
    has_swapped = True
    while has_swapped:
        has_swapped = False
        for i in range(len(lst_sorted) - 1):
            a = lst_sorted[i]
            b = lst_sorted[i + 1]
            if b < a:
                lst_sorted[i] = b
                lst_sorted[i + 1] = a
                has_swapped = True
    return lst_sorted

the test code:

    def test_my_sort():
        lst_test = random.choices(range(-99, 100), k=6)
        lst_copy = lst_test.copy()
        lst_output = my_sort(lst_test)

        assert lst_copy == lst_test, "Error: my_sort (lst) changes the contents of list lst"
        assert lst_output == sorted(lst_test), \
            f "Error: my_sort ({lst_test}) returns {lst_output} instead of {sorted (lst_test)}"

    if __name__ == '__main__':
        try:
            test_my_sort()
            print("Your my_sort () function works fine!")

Upvotes: 0

Views: 74

Answers (2)

LaBeaux
LaBeaux

Reputation: 90

When submitting questions it is helpful to identify what in particular you have a question about instead of a vague request. Whether that's an error code you are getting or a particular unexpected response.

Before even looking at your sort function There are a couple things in your pasted code that need to be fixed prior to it running correctly. You have a try statement without a corresponding except in your main. Also, I am assuming you have

import random

somewhere above your code but didn't paste it?

The sort function you have created both looks and runs correctly for me. I would recommend fixing the areas I've mentioned above if needed, and modifying your question with what particularly you are stuck on.

Upvotes: 1

user14695487
user14695487

Reputation:

I'm just learning python, so this is probably not the best way, but it seems to work:

def my_sort(lst):
    randHolder = []
    for ele in range(len(lst)):
        mini = min(lst)
        giveIndex = lst.index(mini)
        popped = lst.pop(giveIndex)
        randHolder.append(popped)
    lst = randHolder
    return lst

Upvotes: 0

Related Questions