Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Compution
#2
I think you can improve code I just wrote; it is about finding GCD of several values:
def gcd(*x):
    """Returns greatest common divisor"""

    def _gcd2(x, y):
        # FIXME: ensuring that x > y should be moved somewhere else, e.g. in
        # decorator called ensure_sorted
        x, y = max(x, y), min(x, y)
        while True:
            a, b = divmod(x, y)
            x, y = y, b
            if b == 0:
                break
        return x

    if len(x) == 2:
        return _gcd2(*x)
    else:
        return _gcd2(x[0], gcd(*x[1:]))

if __name__ == "__main__":
    print("Should return GCD of a set of numbers")
    print("Result of GCD(2, 4, 8) is ", gcd(2, 4, 8))
Reply


Messages In This Thread
Compution - by lekuru01 - Apr-02-2019, 12:47 AM
RE: Compution - by scidam - Apr-02-2019, 10:17 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020