4 ms·
Here you go # You have a music player that should be playing a 900 song list randomly. # You notice that you keep hearing a song being repeated during your
by hereyougo 4y ago
Here you go
# You have a music player that should be playing a 900 song list randomly.
# You notice that you keep hearing a song being repeated during your drive and
# you are curious if its truly random.
from collections import Counter
import random
r = random.Random()
songs = range(1,900)
unplayed = set(songs)
# You also keep hitting skip in the hopes a particular song comes up.
# Write a piece of code that simulates this. You should tell me three things;
# 1) the number of songs played before a repeat occurs
# 2) how many songs needed to be played before you played them all
# 3) after you succeed in playing them all, how many times has the most common song been played.
counter = Counter()
firstrepeat = None
totalplays = 0
while unplayed:
song = r.choice(songs)
unplayed -= set([song])
if firstrepeat is None and song in counter:
firstrepeat = len(counter)
counter[song] += 1
totalplays += 1
print(f"""
Number of songs played before a repeat: {firstrepeat}
Total number songs played: {totalplays}
Most common song: {counter.most_common()[0][0]}
How many times has the most common song was played: {counter.most_common()[0][1]}
""")
Sample run
$ python3 foo.py
Number of songs played before a repeat: 50
Total number songs played: 7263
Most common song: 375
How many times has the most common song was played: 17
- fuzzythinker 4y agoNice. I would add % of it played vs. median and how many std.deviations from it.
- visarga 4y agoI'm wondering why would the music player implement sampling with replacement and not without replacement? Sampling without replacement would shuffle the list and then play the tracks in shuffled order, no repeats until all songs are played once.
- jboy55 4y agoThis is what I was thinking, as I was driving in, and heard the same song. It was an iPhone, and it was my impression that this is how the iPhone worked. Now, my iPhone did something else weird, it randomly dropped songs from being downloaded, so songs 'disappeared'. One other thing, I just got a new car, and this was the first time I was using 'next' using bluetooth. So, as I was driving in, I was in my head trying to figure out whether the phone now only had 100 songs downloaded, or whether this bluetooth 'next' function on shuffle was picking a random song from the list, rather than 'next' on a shuffled list.
- jboy55 4y agoThat would have been perfect. That's what I would have wanted checked in. I would have quickly turned to telling you how awesome the company was.