Skip to content

Instantly share code, notes, and snippets.

@faif
Last active December 10, 2015 12:48
Show Gist options
  • Save faif/4436181 to your computer and use it in GitHub Desktop.
Save faif/4436181 to your computer and use it in GitHub Desktop.
queue
class myqueue:
def __init__(self):
self._contents = list()
def __str__(self):
return '{}'.format(self._contents[::-1])
def __iter__(self):
return iter(self._contents)
def __len__(self):
return len(self._contents)
def enqueue(self, item):
self._contents.append(item)
def dequeue(self):
last = None
try:
last = self._contents.pop(0)
except Exception:
print('Empty queue!')
return last
def front(self):
return self._contents[0] if len(self) else None
def back(self):
return self._contents[-1] if len(self) else None
if __name__ == '__main__':
q1 = myqueue()
print(q1)
print(len(q1))
[q1.enqueue(x) for x in range(5)]
print(q1)
print('front:', q1.front())
print('back:', q1.back())
[print('dequeue:', q1.dequeue()) for _ in range(len(q1))]
x = q1.dequeue()
print('x:', x)
print('back:', q1.back())
from myqueue import myqueue
class song:
def __init__(self, name, artist, duration):
self.name = name
self.artist = artist
self.duration = duration # in seconds
def __str__(self):
return '{} -- {} ({})'.format(self.name, self.artist, self.duration)
class playlist:
def __init__(self):
self._songs = myqueue()
def __str__(self):
songs = []
[songs.append(str(idx + 1) + '. ' + str(song)) for idx, song in enumerate(self._songs)]
return '\n'.join(songs)
def now_playing(self):
if len(self._songs):
print('Now playing: {}'.format(self._songs.front()))
def song_finished(self):
self._songs.dequeue()
def add(self, song):
self._songs.enqueue(song)
if __name__ == '__main__':
songs = ( ("Singin' in the rain", 'Gene Kelly', 173),
('My way', 'Frank Sinatra', 277),
("It's the end of the world", 'R.E.M.', 244) )
p = playlist()
for (title, artist, duration) in songs:
s = song(title, artist, duration)
p.add(s)
print(p)
p.now_playing()
print()
p.song_finished()
print(p)
p.now_playing()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment