utils.py 984 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from ..node import ExpressionNode as Node
  2. def nary_node(operator, scope):
  3. """
  4. Create a binary expression tree for an n-ary operator. Takes the operator
  5. and a list of expression nodes as arguments.
  6. """
  7. return scope[0] if len(scope) == 1 \
  8. else Node(operator, nary_node(operator, scope[:-1]), scope[-1])
  9. def is_prime(n):
  10. """
  11. Check if the given integer n is a prime number.
  12. """
  13. if n == 2:
  14. return True
  15. if n < 2 or not n & 1:
  16. return False
  17. for i in xrange(3, int(n ** .5) + 1, 2):
  18. if not divmod(n, i)[1]:
  19. return False
  20. return True
  21. def gcd(a, b):
  22. """
  23. Return greatest common divisor using Euclid's Algorithm.
  24. """
  25. while b:
  26. a, b = b, a % b
  27. return a
  28. def lcm(a, b):
  29. """
  30. Return least common multiple of a and b.
  31. """
  32. return a * b // gcd(a, b)
  33. def least_common_multiple(*args):
  34. """
  35. Return lcm of args.
  36. """
  37. return reduce(lcm, args)