-
Notifications
You must be signed in to change notification settings - Fork 0
/
assignment2.py
469 lines (425 loc) · 12.6 KB
/
assignment2.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
from collections import defaultdict
from collections import Counter
class TrieNode():
def __init__(self):
self.children = defaultdict(TrieNode)
self.isWord = None
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
root = self.root
for c in word:
root = root.children[c]
root.isWord = word
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
root = self.root
for c in word:
root = root.children.get(c)
if not root:
return False
return root.isWord
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
root = self.root
for c in prefix:
root = root.children.get(c)
if root == None:
return False
return True
def helperLongestWord(self, word):
root = self.root
for c in word:
root = root.children.get(c)
if not root.isWord:
return False
return root.isWord
class MyHashSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.capacity = 10000
self.size = 0
self.set = [None] * self.capacity
def hash(self, value):
return value % self.capacity
def add(self, value):
"""
:type value: int
:rtype: None
"""
if self.contains(value):
return
hashKey = self.hash(value)
if not self.set[hashKey]:
self.set[hashKey] = [value]
self.size += 1
else:
self.set[hashKey].append(value)
self.size += 1
def remove(self, value):
"""
:type value: int
:rtype: None
"""
if not self.contains(value):
return
hashKey = self.hash(value)
for v in self.set[hashKey]:
if v == value:
self.set[hashKey].remove(value)
self.size -= 1
def contains(self, value):
"""
Returns true if this set contains the specified element
:type value: int
:rtype: bool
"""
hashKey = self.hash(value)
if self.set[hashKey] == None:
return False
for v in self.set[hashKey]:
if v == value:
return True
return False
class MyHashMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.buckets = 10000
self.size = 0
self.maps = [[] for x in range(self.buckets+1)]
def hash(self, key):
return key % self.buckets
def put(self, key, value):
"""
value will always be non-negative.
:type key: int
:type value: int
:rtype: None
"""
hashKey = self.hash(key)
for i, pair in enumerate(self.maps[hashKey]):
if pair[0] == key:
self.maps[hashKey][i][1] = value
return
self.maps[hashKey].append([key, value])
def get(self, key):
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
:type key: int
:rtype: int
"""
hashKey = self.hash(key)
for pair in self.maps[hashKey]:
if pair[0] == key:
return pair[1]
return -1
def remove(self, key):
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
:type key: int
:rtype: None
"""
hashKey = self.hash(key)
bucket = self.maps[hashKey]
for i, pair in enumerate(bucket):
if pair[0] == key:
if i < len(bucket)-1:
bucket[i] = bucket[-1]
bucket.pop()
return
class Solution(object):
def findWordsHelper(self, board, i, j, node, found):
"""
:type board: List[List[str]]
:type node: TrieNode
:type i: int
:type j: int
:type path: str
:type found: List[str]
"""
if node.isWord:
found.append(node.isWord)
node.isWord = None
if i < len(board) and i >= 0 and j < len(board[0]) and j >= 0 and board[i][j] in node.children:
temp = board[i][j]
board[i][j] = '#'
self.findWordsHelper(board, i+1, j, node.children[temp], found)
self.findWordsHelper(board, i-1, j, node.children[temp], found)
self.findWordsHelper(board, i, j-1, node.children[temp], found)
self.findWordsHelper(board, i, j+1, node.children[temp], found)
board[i][j] = temp
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
found = []
trie = Trie()
for word in words:
trie.insert(word)
root = trie.root
for i in range(len(board)):
for j in range(len(board[0])):
self.findWordsHelper(board, i, j, root, found)
return found
def longestWord(self, words):
"""
:type words: List[str]
:rtype: str
"""
trie = Trie()
for word in words:
trie.insert(word)
longest = ""
for word in words:
if len(word) < len(longest) or len(word) == len(longest) and word > longest:
continue
if trie.helperLongestWord(word):
longest = word
return longest
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
startIs = []
pCounter = Counter(p)
sCounter = Counter(s[:len(p)-1])
for i in range(len(p)-1,len(s)):
sCounter[s[i]] += 1
if sCounter == pCounter:
startIs.append(i-len(p)+1)
sCounter[s[i-len(p)+1]] -= 1
if sCounter[s[i-len(p)+1]] == 0:
del sCounter[s[i-len(p)+1]]
return startIs
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
sCounter = Counter(s)
for i in range(len(s)):
if sCounter[s[i]] == 1:
return i
return -1
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
sCounter = Counter(s)
tCounter = Counter(t)
return list(tCounter - sCounter)[0]
def mostCommonWord(self, paragraph, banned):
"""
:type paragraph: str
:type banned: List[str]
:rtype: str
"""
for c in "!?',;.":
paragraph = paragraph.replace(c, " ")
ban = set(banned)
words = paragraph.lower().split()
pCounter = Counter(word for word in words if word not in ban).most_common(1)
return pCounter[0][0]
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
freq = ""
sCounter = Counter(s).most_common(len(s))
for i in sCounter:
freq += i[0]*i[1]
return freq
def findErrorNums(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
aimSum = sum(range(1, len(nums)+1))
sumNumsSet = sum(set(nums))
sumNums = sum(nums)
missing = aimSum - sumNumsSet
repeated = sumNums - sumNumsSet
return [repeated, missing]
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
subCount = []
counter = Counter()
for cpd in cpdomains:
n, d = cpd.split()
counter[d] += int(n)
for i in range(len(d)):
if d[i] == '.':
counter[d[i + 1:]] += int(n)
for i in counter:
subCount.append(str(counter[i]) + " " + i)
return subCount
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return set(nums1).intersection(set(nums2))
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
s = set()
while n != 1:
n = sum([int(i) ** 2 for i in str(n)])
if n in s:
return False
s.add(n)
return True
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
total = sum([S.count(j) for j in J])
return total
def uncommonFromSentences(self, A, B):
"""
:type A: str
:type B: str
:rtype: List[str]
"""
orig = []
c = Counter((A + " " + B).split())
for w in c:
if c[w] == 1:
orig.append(w)
return orig
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
return min(len(candies) / 2, len(set(candies)))
def numSpecialEquivGroups(self, A):
"""
:type A: List[str]
:rtype: int
"""
B = ["".join(sorted(a[0::2])) + "".join(sorted(a[1::2])) for a in A]
s = set(B)
return len(s)
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
sD = {}
tD = {}
for i, val in enumerate(s):
sD[val] = sD.get(val, []) + [i]
for i, val in enumerate(t):
tD[val] = tD.get(val, []) + [i]
return sorted(sD.values()) == sorted(tD.values())
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
pD = {}
sD = {}
for i, val in enumerate(pattern):
pD[val] = pD.get(val, []) + [i]
for i, val in enumerate(str.split(" ")):
sD[val] = sD.get(val, []) + [i]
return sorted(pD.values()) == sorted(sD.values())
def uniqueMorseRepresentations(self, words):
"""
:type words: List[str]
:rtype: int
"""
morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
ws = []
for word in words:
w=''
for i in word:
l = morse[ord(i) - ord('a')]
w += l
ws.append(w)
return len(set(ws))
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
seen = []
for i, row in enumerate(board):
for j, n in enumerate(row):
if n != '.':
seen += [(n,j),(i,n),(i/3,j/3,n)]
return len(seen) == len(set(seen))
def countOfAtoms(self, formula):
"""
:type formula: str
:rtype: str
"""
reverse = formula[::-1]
num = ''
element = ""
multipliers = [1]
counts = Counter()
for char in reverse:
if char.isdigit():
num = char + num
elif char == ")":
multipliers.append(int(num)*int(multipliers[-1]))
num = ''
elif char == "(":
multipliers.pop()
elif char.isalpha() and char.islower():
element = char+element
elif char.isalpha() and char.isupper():
element =char+element
if num != '':
counts[element] += int(num)*int(multipliers[-1])
else:
counts[element] +=1*int(multipliers[-1])
element = ''
num = ''
ret = []
for key in sorted(counts.keys()):
if counts[key] > 1:
ret.append(key+str(counts[key]))
else:
ret.append(key)
return "".join(ret)