Generating unique, ordered Pythagorean triplets

前端 未结 19 1274
借酒劲吻你
借酒劲吻你 2020-11-29 16:57

This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can

19条回答
  •  情歌与酒
    2020-11-29 17:50

    A non-numpy version of the Hall/Roberts approach is

    def pythag3(limit=None, all=False):
        """generate Pythagorean triples which are primitive (default)
        or without restriction (when ``all`` is True). The elements
        returned in the tuples are sorted with the smallest first.
    
        Examples
        ========
    
        >>> list(pythag3(20))
        [(3, 4, 5), (8, 15, 17), (5, 12, 13)]
        >>> list(pythag3(20, True))
        [(3, 4, 5), (6, 8, 10), (9, 12, 15), (12, 16, 20), (8, 15, 17), (5, 12, 13)]
    
        """
        if limit and limit < 5:
            return
        m = [(3,4,5)]  # primitives stored here
        while m:
            x, y, z = m.pop()
            if x > y:
                x, y = y, x
            yield (x, y, z)
            if all:
                a, b, c = x, y, z
                while 1:
                    c += z
                    if c > limit:
                        break
                    a += x
                    b += y
                    yield a, b, c
            # new primitives
            a = x - 2*y + 2*z, 2*x - y + 2*z, 2*x - 2*y + 3*z
            b = x + 2*y + 2*z, 2*x + y + 2*z, 2*x + 2*y + 3*z
            c = -x + 2*y + 2*z, -2*x + y + 2*z, -2*x + 2*y + 3*z
            for d in (a, b, c):
                if d[2] <= limit:
                    m.append(d)
    

    It's slower than the numpy-coded version but the primitives with largest element less than or equal to 10^6 are generated on my slow machine in about 1.4 seconds. (And the list m never grew beyond 18 elements.)

提交回复
热议问题