Skip to content

Instantly share code, notes, and snippets.

View hsleonis's full-sized avatar
🏝️
Travellers unite.

Hasan Shahriar hsleonis

🏝️
Travellers unite.
View GitHub Profile
@hsleonis
hsleonis / inverse_dict.md
Created May 25, 2020 22:41
Inverts a dictionary with non-unique hashable values.
def inverse_dict(obj):
  inv_obj = {}
  for key, value in obj.items():
    inv_obj.setdefault(value, list()).append(key)
  return inv_obj
ages = {
@hsleonis
hsleonis / batch.md
Created May 25, 2020 22:26
Chunks a list into smaller lists of a specified size.
from math import ceil

def batch(lst, size):
  return list(
    map(lambda x: lst[x * size:x * size + size],
      list(range(0, ceil(len(lst) / size)))))
@hsleonis
hsleonis / check_prop.md
Created May 25, 2020 22:24
Check property of object
def check_prop(fn, prop):
  return lambda obj: fn(obj[prop])
check_age = check_prop(lambda x: x >= 18, 'age')
user = {'name': 'Mark', 'age': 18}

check_age(user) # True
@hsleonis
hsleonis / str_capitalize.md
Created May 25, 2020 21:58
Capitalizes the first letter of a string.
def str_capitalize(s, lower_rest=False):
  return s[:1].upper() + (s[1:].lower() if lower_rest else s[1:])
str_capitalize('fooBar') # 'FooBar'
str_capitalize('fooBar', True) # 'Foobar'
@hsleonis
hsleonis / str_camelcase.md
Created May 25, 2020 21:49
Converts a string to camelcase.
from re import sub

def str_camelcase(s):
  s = sub(r"(_|-)+", " ", s).title().replace(" ", "")
  return s[0].lower() + s[1:]
str_camelcase('some_database_field_name') # 'someDatabaseFieldName'
@hsleonis
hsleonis / byte_size.md
Created May 25, 2020 21:47
Returns the length of a string in bytes.
def byte_size(s):
  return len(s.encode('utf-8'))
byte_size('😀') # 4
byte_size('Hello World') # 11
@hsleonis
hsleonis / split_by.md
Last active May 25, 2020 21:37
Splits values into two groups according to a function.
def split_by(lst, fn):
  return [
    [x for x in lst if fn(x)],
    [x for x in lst if not fn(x)]
  ]
split_by(
@hsleonis
hsleonis / split_list.md
Last active May 25, 2020 21:45
Splits list values into two groups.
def split_list(lst, filter):
  return [
    [x for i, x in enumerate(lst) if filter[i] == True],
    [x for i, x in enumerate(lst) if filter[i] == False]
  ]
split_list(['beep', 'boop', 'foo', 'bar'], [True, True, False, True]) # [ ['beep', 'boop', 'bar'], ['foo'] ]
@hsleonis
hsleonis / mean_by.md
Last active May 25, 2020 22:14
Returns the average of a list, after mapping each element to a value using the provided function.
def mean_by(lst, f=lambda el: el):
  return sum(map(f, lst), 0.0) / len(lst)
mean_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda p: p['n']) # 5.0
@hsleonis
hsleonis / mean.md
Last active May 25, 2020 22:11
Returns the average of two or more numbers.
def mean(*args):
  return sum(args, 0.0) / len(args)
mean(*[1, 2, 3]) # 2.0
mean(1, 2, 3) # 2.0