简体   繁体   English

在没有内置排序的情况下从给定列表中排序数字列表,如果第一个数字大于第二个数字则复制它们交换它们

[英]Order a list of numbers from given list without built-in sort, copy if first number is greater than second number swap them

I am tring to implement a function 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.我试图实现一个 function 的方式,它与sorted(lst)基本相同,而不使用sorted(lst)var = lst.copy()但我只是不知道如何工作方式并完全遵循伪代码中编写的方式。

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. Go 通过列表到最后。
  4. If there have been any mix-ups at step 2,go to step 1如果在第 2 步有任何混淆,go 到第 1 步

my code right now:我现在的代码:

def my_sort(lst):
    lst_sorted = []
    lst2 = lst.copy()
    compare = True
    while compare:
        compare = False
        num = lst2[0]
        if num not in lst_sorted:
            try:
                for x in lst2:
                    if x < num:
                        x, num = num, x
                        lst_sorted.append(num)
                    elif num < x:
                        compare = True
        else:
            compare = True
    return lst_sorted

the test code that my professor gave me:我的教授给我的测试代码:

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!")

Straightforward solution简单的解决方案

Following your intention of using a flag compare and the exact assesment rules, here is a step by step explanation:根据您使用标志compare的意图和确切的评估规则,这里是一步一步的解释:

def my_sort(lst):
    # We copy the list so that the changes are not made in the original variable.
    # We will modify lst2 from now.
    lst2 = lst.copy()
    compare = True
    while compare is True:
        # compare will remain False as long as there is no swapping
        compare=False
        # We walk the list index by index, excepted the last one
        # so we don't get an index error from the last "index+1"
        for i in range(len(lst2)-1):
            # If the first is greater than the second...
            if lst2[i]>lst2[i+1]:
                # We swap
                bump = lst2[i]
                lst2[i]=lst2[i+1]
                lst2[i+1]= bump
                # and set compare to True to ask for another iteration of the while loop
                compare=True
    return lst2

Another way of swapping in Python Python 中的另一种交换方式

You can swap in one line:您可以换成一行:

for i in range(len(lst2)-1):
    if lst2[i]>lst2[i+1]:
       lst2[i], lst2[i+1] = lst2[i+1], lst2[i]
       compare=True

Optimizing Bubble sort优化冒泡排序

This sorting algorithm is called Bubble Sort .这种排序算法称为Bubble Sort

There is an optimization based on the observation that the largest value is always carried to the end slot in a single iteration.有一个优化是基于观察到的,最大值总是在一次迭代中被带到最后的槽。 Therefore, in the worst case scenario, you can avoid (n-1)**2 indexings by stopping one index earlier at each iteration.因此,在最坏的情况下,您可以通过在每次迭代中提前停止一个索引来避免(n-1)**2索引。

Here is an adapted implementation:这是一个改编的实现:

def optimized_sort(lst):
    lst2 = lst.copy()
    compare = True
    #Creating a variable to store the iteration count
    n = 0
    while compare is True :
        compare=False
        # This time, we walk from index 0 to the last index minus the iteration count
        for i in range(len(lst2) - 1 - n):
            if lst2[i]>lst2[i+1]:
                lst2[i],lst2[i+1] = lst2[i+1], lst2[i]
                compare=True
        # We increment the iteration count
        n += 1
    return lst2

As you can see, the optimized one is indeed a bit more performing.如您所见,优化后的性能确实更高。 排序比较

Of course, this algorithm remains a poorly performing one and mainly used for educational purpose.当然,这种算法仍然表现不佳,主要用于教育目的。

I'm just learning python, but this works for me:我只是在学习 python,但这对我有用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在没有内置排序的情况下从给定列表中订购数字列表,复制 - order a list of numbers from given list without built-in sort, copy 从排序列表中获取大于给定数字的第一个元素 - Get first element greater than a given number from a sorted list 订购没有内置排序的数字列表,最小值,最大值 function - Order a list of numbers without built-in sort, min, max function 在排序列表中查找大于给定数字的最小数字 - Find the smallest number that is greater than a given number in a sorted list 在列表中找到连续数字大于“ n”的最后一个数字 - find the last number in list with consecutive number of numbers greater than “n” 在不使用内置 function 的情况下查找列表中的最小正数 - Find smallest positive number in a list without using a built-in function 如何打印大于 python 列表中特定数字的 3 个数字? - how to print 3 numbers greater than a specific number of a list in python? 如何找到列表的顺序,使其元素大于第二个列表中的相应元素。 我必须最大化这样的数字 - How to find an order of list such that its elements are greater than the corresponding elements in second list. I have to maximize such number 列表中大于某个数字的值的数量 - number of values in a list greater than a certain number 一个数字的倍数并且大于列表中的“一个数字” - multiples of a number and greater than “a number” in list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM