python-3.x - 如何让我的 python 程序更快
问题描述
我有一个项目,我需要找到数字(E,F,G)的最佳三元组,使得 E 和 F 彼此非常接近(差异最小)并且 G 大于 E 和 F。我必须做出n 个这样的三元组。
我坚持的方法是对给定的数字列表进行排序,然后搜索最小的差异,然后这两个将是我的 E 和 F 在完成所有 n 对之后我将搜索每一对 E 和 F a G 这样G 比 E 和 F 大。我知道这是贪婪的方式,但我的代码很慢,当列表像 300k 数字时需要 1 分钟,而我必须做 2k 三元组。关于如何改进代码的任何想法?
客人是n(三胞胎的数量)
棒是所有数字的列表
# We sort the list using the inbuilt function sticks.sort()
save = guests # Begining to search for the best pairs of E and F
efficiency = 0 while save != 0:
difference = 1000000 # We asign a big value to difference each time
# Searching for the smallest difference between two elements
for i in range(0, length - 1):
if sticks[i+1] - sticks[i] < difference:
temp_E = i
temp_F = i + 1
difference = sticks[i+1] - sticks[i]
# Saving the two elements in list stick_E and stick_F
stick_E.append(sticks[temp_E])
stick_F.append(sticks[temp_F])
# Calculating the efficiency
efficiency += ((sticks[temp_F] - sticks[temp_E]) * (sticks[temp_F] - sticks[temp_E]))
# Deleting the two elements from the main list
sticks.pop(temp_E)
sticks.pop(temp_E)
length -= 2
save -= 1
# Searching for stick_G for every pair made for i in range(0, len(stick_F)):
for j in range(0, length):
if stick_F[i] < sticks[j]:
stick_G.append(sticks[j]) # Saves the element found
sticks.pop(j) # Deletes the element from the main list
length -= 1
break
> # Output the result to a local file print_to_file(stick_E, stick_F, stick_G, efficiency, output_file)
我尽我所能对代码进行了注释,以便您更容易理解。
解决方案
推荐阅读
- sockets - 处理来自 Socket 的异构信息
- c# - SignalR 客户端未收到服务器消息
- docker - 如何更改 Zabbix 代理以监控 tls 安全的 Docker 守护进程套接字
- json - Ionic3 - 使用 Sqlite 同步大 JSON 文件数据的最快方法
- javascript - 如何在 ExpressJS 中添加内容安全策略以从 CDN 加载外部 JS 文件?
- python - ValueError:无法挤压暗淡 [1],预期尺寸为 1,输入形状为 '{{node ctc/Squeeze}} 得到 3:[?,3]
- javascript - 如何读取txt文件并将其保存在html中javascript中的数组中
- javascript - 如何在地图中获取 X 项?
- c++ - 错误 LNK2001:Visual Studio 2019 中未解析的外部符号 CWbemProviderGlue::FrameworkLogoffDLL(wchar_t const *)"
- google-sheets - 在谷歌表格中,有没有办法将两个不同表格中的列组合成饼图?