Last active
January 15, 2018 06:16
-
-
Save SBNBON005/58503c4d3c9b769211fb671c29559618 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_even(n): | |
"""uses bitwise operator to check if number is even or odd | |
Args: | |
n (int): | |
Returns: | |
answer (bool): True if even, False otherwise | |
""" | |
return n & 1 == 0 | |
def is_even2(n): | |
""" | |
Args: | |
n (int): | |
Returns: | |
answer (bool): True if even, False otherwise | |
""" | |
return n % 2 == 0 | |
def exponentiation_by_squaring_recursively(x, n): | |
"""The following recursive algorithm computes x^n for integer values of n: | |
https://en.wikipedia.org/wiki/Exponentiation_by_squaring | |
Time and space complexity: O(log N) | |
""" | |
if n < 0: | |
return exponentiation_by_squaring_recursively(1.0 / x, -n) | |
elif n == 0: | |
return 1 | |
elif n == 1: | |
return x | |
elif is_even(n): | |
return exponentiation_by_squaring_recursively(x * x, n / 2) | |
elif not is_even(n): | |
return x * exponentiation_by_squaring_recursively(x * x, (n - 1) / 2) | |
def exponentiation_by_squaring_recursively2(x, n): | |
""" https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms/ | |
""" | |
if n < 0: | |
return exponentiation_by_squaring2(1.0/x, -n) | |
elif n == 0: | |
return 1 | |
elif n % 2 == 1: | |
return x * exponentiation_by_squaring2(x, n - 1) | |
else: | |
p = exponentiation_by_squaring2(x, n / 2) | |
return p * p | |
#raymondh - In Python3.6 the fastest way to eliminate hashable duplicates while retaining insertion order: | |
list(dict.fromkeys('uppdattemoma')) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment