Skip to content

Instantly share code, notes, and snippets.

@tungd
Last active September 24, 2018 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tungd/68f4cddcd07b1cf93acdd8b3f7cf8657 to your computer and use it in GitHub Desktop.
Save tungd/68f4cddcd07b1cf93acdd8b3f7cf8657 to your computer and use it in GitHub Desktop.
from functools import reduce
# count
reduce(lambda i, _: i + 1, [1, 2, 3, 4, 5, 6, 2, 3], 0)
# max
reduce(lambda a, b: a if a > b else b, [1, 2, 3, 4, 5, 6, 2, 3])
# min
reduce(lambda a, b: a if a < b else b, [1, 2, 3, 4, 5, 6, 2, 3])
# sum
reduce(lambda i, a: i + a, [1, 2, 3, 4, 5, 6, 2, 3])
# remove
filter(lambda i: i % 3 != 0, [1, 2, 3, 4, 5, 6, 2, 3])
# flatten
reduce(
lambda output, kv: output + kv,
{'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}.values(),
[]
)
# group
def group(groups, i):
if (len(groups[-1]) < 3):
groups[-1].append(i)
else:
groups.append([i])
return groups
reduce(group, [1, 2, 3, 4, 5, 6, 2, 3], [[]])
# frequency
def frequency(result, i):
if i not in result:
result[i] = 1
else:
result[i] += 1
return result
reduce(frequency, [1, 2, 3, 4, 5, 6, 2, 3], {})
# split
def split(result, i):
if i % 2 == 0:
result[0].append(i)
else:
result[1].append(i)
return result
reduce(split, [1, 2, 3, 4, 5, 6, 2, 3], [[], []])
# group_by
def group_by_age(groups, i):
if i['age'] not in groups:
groups[i['age']] = [i]
else:
groups[i['age']].append(i)
return groups
reduce(group_by_age, [
{'age': 1, 'name': 'Alice'},
{'age': 2, 'name': 'Bob'},
{'age': 2, 'name': 'Clark'}
], {})
def group_recursive(items, groups=[[]]):
if len(items) == 0:
return groups
if len(groups[-1]) < 3:
groups[-1].append(items[0])
else:
groups.append([items[0]])
return group_recursive(items[1:], groups)
print(group_recursive([1, 2, 3, 4, 5, 6, 2, 3]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment