【问题标题】:How to sort numbers in Python without using built-in methods如何在不使用内置方法的情况下在 Python 中对数字进行排序
【发布时间】:2016-11-15 19:23:49
【问题描述】:

我正在尝试在 python 中对 3 个数字进行排序,而不使用内置的排序方法,例如 'sorted' 或 .sort。

假设我有数字...

2、500、25、15、12

我想输出为 2, 12, 15, 25, 500

我想模仿python内置的排序函数如何工作,但找不到它的源代码。

我做了 3 个数字:

msg = "Give me a number: "
pfix = " is the greatest"


a = int(input(msg))
b = int(input(msg))
c = int(input(msg))
nums = []

if a>b and a>c:
    nums.append(a)
elif b>a and b>c:
    nums.append(b)
else:
    nums.append(c)


if a>b and b>c:
    nums.append(b)
elif a>b and b>c:
    nums.append(b)
elif a>c and c>b:
    nums.append(c)
elif b>a and a>c:
    nums.append(a)
elif b>c and c>a:
    nums.append(c)
elif c>a and a>b:
    nums.append(a)
elif c>b and b>a:
    nums.append(b)

if a<b and a<c:
    nums.append(a)
elif b<a and b<c:
    nums.append(b)
elif c<b and c<a:
    nums.append(c)

print(nums)

我知道这是一个不好的方法,因为它只适用于 3 个数字。我需要一些可以使用 for 循环处理不定数字列表的东西

喜欢...

def num_sort(_list):
    for i in range(0, len(_list)):
    ...

并像这样使用

print(num_sort([2, 500, 25, 15, 12]))

我将如何获得特定的排序? 例如升序或降序...

我知道这就像重新发明轮子,但有人告诉我我需要自己创造方法。

你会怎么做?

提前致谢。

【问题讨论】:

  • 阅读排序方法:冒泡、插入、合并、快速
  • 不要粗鲁,但是,如果您被要求制作自己的方法,您为什么要问我们?你知道排序算法吗?
  • 我提交了上面的代码,他们选择接受,因为无论多么糟糕,它都会按照他们的要求进行。 3个数字。我想知道应该怎么做。

标签: sorting numbers


【解决方案1】:

快速排序算法 - http://www.algolist.net/Algorithms/Sorting/Quicksort

def sort(array):
    less = []
    equal = []
    greater = []

    if len(array) > 1:
        pivot = array[0]
        for x in array:
            if x < pivot:
                less.append(x)
            if x == pivot:
                equal.append(x)
            if x > pivot:
                greater.append(x)
        return sort(less)+equal+sort(greater)  
    else: 
        return array
print(sort([12,4,5,6,7,3,1,15]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 2011-07-19
    • 2021-12-12
    • 1970-01-01
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多