我找不到一个简单的过滤器,用于我的pyth三元组过滤器

时间:2015-08-16 18:28:11

标签: python

我想把它过滤到原始三元组([3,4,5],[7,24,25]等)没有非原始像[6,8,10]我不能似乎想通了,所以在我的代码中我只是尝试了这个过滤器,它显示了原始和非原始的三元组。

import Tkinter
import sys
from fractions import gcd


def func(event):
    x = int(e1.get())  # get max number
    result = []
    for a in range(1, x):  # loops to get each value in range of x
        for b in range(a, x):
            for c in range(b, x):
                if a**2 + b**2 == c**2 and gcd(a, b) == 1:  # if it is a primitive pyth triple, append result
                    result += ['[',a,',',b,',',c,']']  # add group of triples to list
    l = Tkinter.Message(root, text=result).grid(ipadx=5, ipady=5, sticky='W''E')  # display each group of triples to root
    l0 = Tkinter.Label(root, text="Non-primitive and primitive triples").grid(ipadx=5, ipady=5, sticky='W''E')
    root.bind('<Return>', close)  # Hit enter to exit, only temp for debugging, will reassign to button later


def close(event):  # close program, define parameter event to allow for binding
    Tkinter.sys.exit(0)
    sys.exit(0)


root = Tkinter.Tk()  # establish main gui
root.title('Generator')
e1 = Tkinter.Entry(root)
assert isinstance(e1, object)  # only method I've found to allow for Entry().grid()
e1.grid(ipadx=5, ipady=5, sticky='W''E')
root.bind('<Return>', func)  # bind to Enter, cleaner and quicker than a button
root.mainloop()

2 个答案:

答案 0 :(得分:1)

您可以使用fractions.gcd()来确定给定三元组是否具有任何公约数。

答案 1 :(得分:1)

导入gcd(from fractions import gcd)并添加另一个测试到你检查三元组是否是毕达哥拉斯的行:

if a**2 + b**2 == c**2 and gcd(a, b) == 1:

这应该只产生原始的三元组。