Created
August 12, 2017 01:50
-
-
Save abehmiel/0defd8d3ba7389f8d09c19ab07de7748 to your computer and use it in GitHub Desktop.
Library for hackerrank challenges
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
""" GCD/ LCD """ | |
# greatest common divisor | |
from fractions import gcd | |
gcd(x,y) | |
# least common multiple | |
def lcm(x, y): | |
""" This function takes two | |
integers and returns the L.C.M. """ | |
lcm = (x*y)//gcd(x,y) | |
return lcm | |
""" Prime numbers """ | |
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 | |
def primes(n): | |
""" Input n>=6, Returns a list of primes, 2 <= p < n """ | |
correction = (n%6>1) | |
n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6] | |
sieve = [True] * (n//3) | |
sieve[0] = False | |
for i in range(int(n**0.5)//3+1): | |
if sieve[i]: | |
k=3*i+1|1 | |
sieve[ ((k*k)//3) ::2*k]=[False]*((n//6-(k*k)//6-1)//k+1) | |
sieve[(k*k+4*k-2*k*(i&1))//3::2*k]=[False]*((n//6-(k*k+4*k-2*k*(i&1))//6-1)//k+1) | |
return [2,3] + [3*i+1|1 for i in range(1,n//3-correction) if sieve[i]] | |
""" Bit operations """ | |
# bitfield | |
def bitfield(n): | |
""" Takes an integer as input and returns a bitfield as a list""" | |
return [1 if digit=='1' else 0 for digit in bin(n)[2:]] | |
""" Strings """ | |
# reverse a string | |
reverse(s) | |
""" Sorting """ | |
# simple sorting | |
a.sort() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment