-
Notifications
You must be signed in to change notification settings - Fork 891
/
problem_318.py
73 lines (55 loc) · 1.76 KB
/
problem_318.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import random
from copy import deepcopy
class Node:
def __init__(self, val):
self.val = val
self.prev = None
self.next = None
def __hash__(self):
return hash(self.val)
def __eq__(self, other):
return self.val == other.val
def __repr__(self):
return str(self.val)
class LRUCache:
def __init__(self, size):
self.head = Node(None)
self.tail = Node(None)
self.head.next = self.tail
self.tail.prev = self.head
self.size = size
self.recent_nodes = dict()
def use(self, val):
if val in self.recent_nodes:
used_node = self.recent_nodes[val]
used_node.prev = used_node.next
elif len(self.recent_nodes) == self.size:
used_node = Node(val)
del self.recent_nodes[self.head.next.val]
self.head.next = self.head.next.next
else:
used_node = Node(val)
before_tail = self.tail.prev
before_tail.next = used_node
used_node.next = self.tail
used_node.prev = before_tail
self.tail.prev = used_node
self.recent_nodes[val] = used_node
def count_playlists(song_ids, cache, plays_left):
if plays_left == 0:
return 1
total = 0
for song_id in song_ids:
if song_id in cache.recent_nodes:
continue
new_cache = deepcopy(cache)
new_cache.use(song_id)
total += count_playlists(song_ids, new_cache, plays_left - 1)
return total
def get_valid_playlists(plays, songs, buffer):
song_ids = set(range(songs))
lru_cache = LRUCache(buffer)
total = count_playlists(song_ids, lru_cache, plays)
return total
# Tests
assert get_valid_playlists(6, 4, 2) > get_valid_playlists(6, 4, 3)