Skip to content

Instantly share code, notes, and snippets.

View s1monw1's full-sized avatar
☁️
Hello, cloud.

Simon Wirtz s1monw1

☁️
Hello, cloud.
View GitHub Profile
fun <T> countOccurrences(values: Collection<T>): Map<T, Int> =
mutableMapOf<T, Int>().withDefault { 0 }.apply {
for (e in values) {
put(e, getValue(e) + 1)
}
}
fun <T> countOccurrences(values: Collection<T>): Map<T, Int> {
val countMap = mutableMapOf<T, Int>().withDefault { 0 }
for (e in values) {
countMap[e] = countMap.getValue(e) + 1
}
return countMap
}
fun <K, V> MutableMap<K, V>.withDefault(defaultValue: (key: K) -> V): MutableMap<K, V>
fun <T> countOccurrences(values: Collection<T>): Map<T, Int> {
val countMap = mutableMapOf<T, Int>()
for (e in values) {
countMap.putIfAbsent(e, 0)
// getValue, as an alternative to index operator,
// makes sure a non-nullable type is returned
countMap[e] = countMap.getValue(e) + 1
}
return countMap
}
fun <T> countOccurrences(values: Collection<T>): Map<T, Int> {
val countMap = mutableMapOf<T, Int>()
for (e in values) {
val current = countMap[e]
if (current == null) countMap[e] = 1
else countMap[e] = current + 1
}
return countMap
}
fun <T> countOccurrences(values: Collection<T>): Map<T, Int>
from collections import defaultdict
d = defaultdict(int)
print(d["someKey"]) // prints 0
from collections import defaultdict
data = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
d = defaultdict(set)
for k, v in data:
d[k].add(v)
print(d.items()) # dict_items([('red', {1, 3}), ('blue', {2, 4})])
inline fun <T, R> with(receiver: T, block: T.() -> R): R
inline fun T.apply(block: T.() -> Unit): T