在任何给定的两个数字之间找到三角数

时间:2013-11-27 18:26:28

标签: python python-2.7

我的代码显示在下面

import math,sys

#create a list with numbers
def create_list():
    num_list=[]
    for num in range(int(input("insert start point: ")),int(input("Insert end point: "))):
        num_list.append(num)
    return num_list

#function to find triangular numbers
def get_triangles(numlist):
    triangles = []
    for i in numlist:
        if (check_triangle(i)):
            triangles.append(i)
    return triangles

#function to check number is triangular or not
def check_triangle(n):
    return math.sqrt((8*n)+1).is_integer()

#function main to run the process
def main():
    numlist = create_list()
    print(get_triangles(numlist))

即使看起来任务已经完成,但事实并非如此。我试用了0到100000000(1 * 10 ^ 8)的数字。它是否会导致我的笔记本电脑卡住任何可以完成此任务的方法?

2 个答案:

答案 0 :(得分:2)

请勿打印大型列表。而是将其写入文件,这样您可以在以后打开文件。该程序无法有效地将大量信息写入控制台。我发现在控制台上打印东西会使程序效率降低。

此外,我阅读了一些关于您的代码的评论,他们说它没有效率,我不得不同意。

这是我写的一段代码。这需要一些解释,但我很匆忙。如果您需要帮助,请回复。

def getTriangles(input1,input2): #input1 is the min value and input2 is the max value
    li = [] #the list where all of the numbers will go
    i = 0 #an integer that acts how much another layer of the triangle would have
    j = 0 #the most current number that it is on
    while True: #I whipped up this algorithm in a couple minutes, so there is probably a more efficient way than just looping through all of them, but it is faster than the current one being used
        i += 1 #i has to increment to act as the increase of a side
        if j > input2: #if the value that could be added is greater than the max number, than just end the function and return the list
            return li
        if j >= input1: #if the number qualifies the minimum number requirements, then the program will add it to the list, otherwise it will ignore it and continue on with the function
            li.append(j)
        j += i #this simulates adding in another layer of the triangle to the bottom

这是一种使用它的方法:     打印(getTriangles(1,45)) 我相信你可以查看如何将内容写入文件。

答案 1 :(得分:0)

您似乎只是想在一个范围内生成所有三角形数字。如果是这样,直接计算它们比通过平方根检查要快得多。

请注意,您只需添加连续数字即可生成三角形数字。

T_0 = 0
T_1 = T_0 + 1 = 1
T_2 = T_1 + 2 = 3
T_3 = T_2 + 3 = 6
...

如果你想保持简单,你可以创建一个函数来保持从n = 0生成这些数字,在它们进入所需范围时保留它们,并继续直到它超过上限。

def generate_triangular_numbers(a, b):
    """Generates the triangular numbers in [a, b] (inclusive)"""
    n, t = 0, 0
    triangles = []

    while t < a:
        n += 1
        t += n

    while t <= b:
        triangles.append(t)
        n += 1
        t += n

    return triangles