Skip to content

Instantly share code, notes, and snippets.

View brettfreer's full-sized avatar

Brett Freer brettfreer

View GitHub Profile
@brettfreer
brettfreer / maxvalue.py
Last active July 6, 2016 10:43
Return the key with the maximum value in a dictionary
import operator
def max_value(m):
return max(m.iteritems(), key=operator.itemgetter(1))[0]
@brettfreer
brettfreer / totient.py
Created June 11, 2016 10:30
Euler's Totient
from fractions import gcd
def eulers_totient(n):
p = 0
for k in range(1, n+1):
if gcd(n,k) == 1:
p += 1
return p
@brettfreer
brettfreer / swap.py
Last active June 12, 2016 09:02
Swap positions i and j in string s
def swap(s, i, j):
return ''.join((s[:i], s[j], s[i+1:j], s[i], s[j+1:]))
@brettfreer
brettfreer / remove_duplicate.py
Last active June 12, 2016 09:02
Remove duplicate characters from a string
import itertools
def remove_duplicate(s):
return ''.join(ch for ch, _ in itertools.groupby(s))
@brettfreer
brettfreer / remove_spaces.py
Created June 20, 2016 22:08
Remove all spaces from a string
def remove_spaces(s):
return s.replace(' ', '')
@brettfreer
brettfreer / remove_leading_zeros.py
Created June 20, 2016 22:09
Remove leading zeros from a string
def remove_leading_zeros(s):
while s[0] == '0':
s = s[1:]
return s
@brettfreer
brettfreer / remove_trailing_zeros.py
Created June 20, 2016 22:11
Remove trailing zeros from a string
def remove_trailing_zeros(s):
while s[-1] == '0':
s = s[:-1]
return s
@brettfreer
brettfreer / isDate.py
Last active July 6, 2016 10:38
Validate if a text string is a valid date with a supplied format string
import datetime
def isDate(date_text, fmt):
try:
datetime.datetime.strptime(date_text, fmt)
except ValueError:
return False
return True
@brettfreer
brettfreer / sum_of_digits.py
Created June 27, 2016 08:29
Return the sum of digits in an integer
def sum_of_digits(n):
s = 0
while n > 0:
s += n % 10
n /= 10
return s
@brettfreer
brettfreer / dynamodb_rename_attribute.py
Last active November 10, 2023 00:43
Rename an AWS dynamodb table attribute with an exponential timing backoff
#!/usr/bin/env python3
""" Rename an AWS dynamodb table attribute with an exponential timing back-off
"""
import logging
from time import sleep
import boto3
from boto3.dynamodb.conditions import Attr