Skip to content

Instantly share code, notes, and snippets.

@tupton
Last active December 12, 2017 21:28
Show Gist options
  • Save tupton/63ec34c03e1c81e1f6eb775c1c45a6d7 to your computer and use it in GitHub Desktop.
Save tupton/63ec34c03e1c81e1f6eb775c1c45a6d7 to your computer and use it in GitHub Desktop.
Example excerpt from jupyter notebook
# get_tracks is an api method to get recent tracks for a user, with paging and caching
# get_track is an api method to get a single track from mbid or artist+name, with caching
import itertools
from operator import itemgetter
def track_to_artist_and_duration(track):
api_track = get_track(track)
return (track.get('artist').get('name'), track.get('name'), api_track.get('duration'))
def ms_to_time(ms):
seconds = ms / 1000
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return "{:d}:{:02d}:{:02d}".format(h, m, s)
track_artist_duration = itertools.imap(track_to_artist_and_duration, get_tracks())
with_duration = itertools.ifilter(lambda t: t[2] is not None and t[2] != "0", track_artist_duration)
grouped_by_artist = [[n, sum(itertools.imap(lambda d: long(d[2]), g))] for n,g in itertools.groupby(sorted(with_duration, key=itemgetter(0)), key=itemgetter(0))]
grouped_sorted = reversed(sorted(grouped_by_artist, key=itemgetter(1)))
for g in itertools.islice(grouped_sorted, 10):
print(u'{}, {}'.format(g[0], ms_to_time(g[1])))
# Brian Eno, 34:05:03
# This American Life, 11:11:35
# Elder, 7:41:53
# These Arms Are Snakes, 7:32:11
# Brand New, 7:05:50
# King Gizzard & The Lizard Wizard, 6:44:53
# Aviator, 5:52:44
# The War on Drugs, 5:32:47
# Graves at Sea, 5:04:12
# Tigers Jaw, 4:44:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment