Created
November 20, 2019 06:10
-
-
Save mitghi/1e1690f0131dad3d8bdc159ecdff9e5e to your computer and use it in GitHub Desktop.
Discrete mathematics in Python
This file contains 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 digits(n): | |
result = [] | |
l = 0 | |
while n > 0: | |
d = n % 10 | |
result.insert(0, d) | |
n = n // 10 | |
l += 1 | |
return (l, result) | |
def digitalroot(n, trace=False): | |
if trace: | |
tr = [] | |
l, n = digits(n) | |
while l > 1: | |
s = sum(n) | |
if trace: | |
tr.insert(0, s) | |
l, n = digits(s) | |
if trace: | |
return (n, tr) | |
return n | |
def perfectsquare(n): | |
return sum(map(lambda x: pow(x, 2), range(1, n+1))) | |
def ismonotonic(n, increasing=True): | |
fncmp = lambda a, b: a < b if increasing else a > b | |
prev = n[0] | |
for i in n[1:]: | |
if not fncmp(prev, i): | |
return False | |
prev = i | |
return True | |
def strhaspairs(s, pairs): | |
lv, rv = pairs | |
lpn, rpn = 0, 0 | |
for c in s: | |
if c == lv: | |
lpn += 1 | |
elif c == rv: | |
rpn += 1 | |
return lpn == rpn | |
def wordcount(s): | |
count = 0 | |
ws = 0x20 | |
ca, cz = 0x41, 0x5a | |
cA, cZ = ca+0x20, cz+0x20 | |
i, l = 0, len(s) - 1 | |
wb = False | |
while i <= l: | |
if ord(s[i]) == ws and wb == True: | |
wb = False | |
count += 1 | |
elif (ord(s[i]) >= ca and ord(s[i]) <= cz) or (ord(s[i]) >= cA and ord(s[i]) <= cZ): | |
wb = True | |
i += 1 | |
else: | |
if wb: | |
count += 1 | |
return count | |
def xorswap(a, b): | |
a ^= b | |
b ^= a | |
a ^= b | |
return (a, b) | |
def simple_swap(n): | |
for i in range(len(n)-1): | |
if n[0] > n[i+1]: | |
a, b = n[i], n[i+1] | |
n[i], n[i+1] = xorswap(a, b) | |
return n | |
def collatz_conjecture(n): | |
result = [] | |
while n != 1: | |
if n&0x1 == 0: | |
n = n // 2 | |
result.append(n) | |
else: | |
n = 3*n+1 | |
result.append(n) | |
return result | |
def tobinary(n): | |
result = [] | |
while n != 0 : | |
d = n % 2 | |
n = n // 2 | |
result.insert(0, d) | |
return result | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment