首页 > 解决方案 > 如何让我的 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)

我尽我所能对代码进行了注释,以便您更容易理解。

标签: python-3.x

解决方案


推荐阅读