This file contains hidden or 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
from itertools import tee, chain | |
# ABC -> (None, A) (A, B) (B, C) | |
def prev_curr_iter(iterable): | |
a, b = tee(iterable) | |
return zip(chain([None], a), b) | |
# use case | |
for prev, curr in prev_curr_iter("ABC"): | |
print(f"{prev=}\t{curr=}") |
This file contains hidden or 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
const getDefault = (o, key, defaultVal) => key in o ? o[key] : o[key] = defaultVal | |
// Prototype version of above. Allows for usage: o.getDefault(key, def) | |
Object.defineProperty(Object.prototype, "getDefault", { | |
value: function(key, defaultVal) { | |
return key in this ? this[key] : this[key] = defaultVal | |
} | |
}) |
This file contains hidden or 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
const indexOfMin = numbers => { | |
return numbers.indexOf(Math.min(...numbers)) | |
} |
This file contains hidden or 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
function* range(start, stop, step=1) { | |
if(typeof stop === 'undefined') [start, stop] = [0, start] | |
for(let i = start; step > 0 ? i < stop : i > stop; i += step) | |
yield i | |
} | |
/* | |
[...range(0, 10, 2)] | |
[0, 2, 4, 6, 8] |
This file contains hidden or 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 int_float_or_string(string): | |
try: | |
int(string) # strict and nice | |
return int | |
except ValueError: | |
# float() is too permissive, this is better | |
return float if is_strictly_float(string) else str | |
def is_strictly_float(string): | |
if string.startswith("-"): |