【问题标题】:What is the best algorithm to sort a number?对数字进行排序的最佳算法是什么?
【发布时间】:2021-05-30 11:11:00
【问题描述】:

所以我有一个名为 new.txt 的文档,其中包含许多 pi 数字(请参阅https://www.piday.org/million/),我想将数字拆分为由所有这些数字按顺序组成的列表。我的代码可以工作,但速度极慢,(我尝试过使用较少位数的 pi)。

def sort(stuff):
    for iter_num in range(len(stuff)-1,0,-1):
        for idx in range(iter_num):
            if stuff[idx]>stuff[idx+1]:
                temp = stuff[idx]
                stuff[idx] = stuff[idx+1]
                stuff[idx+1] = temp
    return stuff
                

a = []
with open("/Users/serax/desktop/new.txt", "r") as r:
    for line in r.readlines():
        for char in line:
            text = a.append(char)


print(sort(a))

【问题讨论】:

  • 不需要冒泡排序。只有 10 个项目 - 只需迭代文件一次并计算每个数字出现的次数,然后按顺序打印结果字典(首先是 1 或 9,取决于升序/降序)。这是桶排序的一种非常基本的形式。
  • 请注意,我认为您可以在此处使用带有key 参数的快速sorted 内置参数
  • @BenjaminGruenbaum 谢谢,现在这么快!
  • @JérômeRichard 谢谢,但使用内置函数并不好玩 :)

标签: python performance optimization


【解决方案1】:

感谢 cmets 我编辑了我的代码,结果如下。

thisdict = {
  ".": 0,
  "0": 0,
  "1": 0,
  "2": 0,
  "3": 0,
  "4": 0,
  "5": 0,
  "6": 0,
  "7": 0,
  "8": 0,
  "9": 0,
  }

with open("/Users/serax/documents/new.txt", "r") as r:
    for line in r.readlines():
        # print(sorted(line)) # built in function that can sort str/list/tuple (works)
        for char in line:
            for key in thisdict:
                if char == key:
                    thisdict[key] += 1

ordered = ""
for i in thisdict:
    ordered = ordered + i*thisdict[i]

print(ordered)

【讨论】:

  • 考虑使用计数器以获得更整洁的代码:)
猜你喜欢
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
  • 2013-07-07
相关资源
最近更新 更多