Skip to content

Commit ad8c0d1

Browse files
committed
Leetcode Python3
1 parent ac99210 commit ad8c0d1

17 files changed

+689
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# 1396. Design Underground System
2+
3+
An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.
4+
5+
## Implement the **UndergroundSystem** class:
6+
7+
- `void checkIn(int id, string stationName, int t)`
8+
- A customer with a card ID equal to `id`, checks in at the station `stationName` at time `t`.
9+
- A customer can only be checked into one place at a time.
10+
- `void checkOut(int id, string stationName, int t)`
11+
- A customer with a card ID equal to `id`, checks out from the station `stationName` at time `t`.
12+
- `double getAverageTime(string startStation, string endStation)`
13+
- Returns the average time it takes to travel from `startStation` to `endStation`.
14+
- The average time is computed from all the previous traveling times from `startStation` to `endStation` that happened **directly**, meaning a check in at `startStation` followed by a check out from `endStation`.
15+
- The time it takes to travel from `startStation` to `endStation` **may be different** from the time it takes to travel from `endStation` to `startStation`.
16+
- There will be at least one customer that has traveled from `startStation` to `endStation` before `getAverageTime` is called.
17+
18+
You may assume all calls to the `checkIn` and `checkOut` methods are consistent. If a customer checks in at time `t1` then checks out at time `t2`, then `t1 < t2`. All events happen in chronological order.
19+
20+
21+
### Example 1:
22+
23+
**Input**
24+
```json
25+
["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]
26+
27+
[[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]]
28+
```
29+
30+
**Output**
31+
```json
32+
[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]
33+
```
34+
35+
**Explanation**
36+
```python
37+
UndergroundSystem undergroundSystem = new UndergroundSystem();
38+
undergroundSystem.checkIn(45, "Leyton", 3);
39+
undergroundSystem.checkIn(32, "Paradise", 8);
40+
undergroundSystem.checkIn(27, "Leyton", 10);
41+
undergroundSystem.checkOut(45, "Waterloo", 15); // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12
42+
undergroundSystem.checkOut(27, "Waterloo", 20); // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10
43+
undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14
44+
undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14
45+
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11
46+
undergroundSystem.checkIn(10, "Leyton", 24);
47+
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000
48+
undergroundSystem.checkOut(10, "Waterloo", 38); // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14
49+
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12
50+
```
51+
52+
### Example 2:
53+
54+
**Input**
55+
```json
56+
["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"]
57+
[[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]]
58+
```
59+
60+
**Output**
61+
```json
62+
[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]
63+
```
64+
65+
**Explanation**
66+
```
67+
UndergroundSystem undergroundSystem = new UndergroundSystem();
68+
undergroundSystem.checkIn(10, "Leyton", 3);
69+
undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5
70+
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5
71+
undergroundSystem.checkIn(5, "Leyton", 10);
72+
undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6
73+
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5
74+
undergroundSystem.checkIn(2, "Leyton", 21);
75+
undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9
76+
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667
77+
```
78+
79+
## Constraints:
80+
81+
- `1 <= id, t <= 106`
82+
- `1 <= stationName.length, startStation.length, endStation.length <= 10`
83+
- All strings consist of uppercase and lowercase English letters and digits.
84+
- There will be at most `2 * 104` calls in total to `checkIn`, `checkOut`, and `getAverageTime`.
85+
- Answers within `10^-5` of the actual value will be accepted.
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import argparse
2+
import collections
3+
from typing import Dict, List, Tuple
4+
5+
6+
class UndergroundSystem:
7+
def __init__(self):
8+
# (start, end): [totalTime, samples]
9+
self.station_times: Dict[Tuple[str, str], List[int, int]] = collections.defaultdict(
10+
lambda: [0, 0])
11+
# id: (stationName, checkInTime)
12+
self.current_passengers: Dict[int, Tuple[str, int]] = dict()
13+
14+
def checkIn(self, id: int, stationName: str, t: int) -> None:
15+
if id in self.current_passengers:
16+
return
17+
self.current_passengers[id] = (stationName, t)
18+
19+
def checkOut(self, id: int, stationName: str, t: int) -> None:
20+
if id not in self.current_passengers:
21+
return
22+
startStation, checkInTime = self.current_passengers[id]
23+
24+
self.current_passengers.pop(id)
25+
26+
self.station_times[(startStation, stationName)][0] += t-checkInTime
27+
self.station_times[(startStation, stationName)][1] += 1
28+
29+
def getAverageTime(self, startStation: str, endStation: str) -> float:
30+
totalTime, samples = self.station_times[(startStation, endStation)]
31+
if samples == 0:
32+
return 0
33+
return totalTime/samples
34+
35+
36+
# Your UndergroundSystem object will be instantiated and called as such:
37+
# obj = UndergroundSystem()
38+
# obj.checkIn(id,stationName,t)
39+
# obj.checkOut(id,stationName,t)
40+
# param_3 = obj.getAverageTime(startStation,endStation)
41+
42+
def test1():
43+
undergroundSystem = UndergroundSystem()
44+
45+
# Customer 10 "Leyton" -> "Paradise" in 8-3 = 5
46+
undergroundSystem.checkIn(10, "Leyton", 3)
47+
undergroundSystem.checkOut(10, "Paradise", 8)
48+
49+
# return 5.00000, (5) / 1 = 5
50+
r1 = undergroundSystem.getAverageTime("Leyton", "Paradise")
51+
assert r1 == 5
52+
53+
# Customer 5 "Leyton" -> "Paradise" in 16-10 = 6
54+
undergroundSystem.checkIn(5, "Leyton", 10)
55+
undergroundSystem.checkOut(5, "Paradise", 16)
56+
57+
# return 5.50000, (5 + 6) / 2 = 5.5
58+
r2 = undergroundSystem.getAverageTime("Leyton", "Paradise")
59+
assert r2 == 5.5
60+
61+
# Customer 2 "Leyton" -> "Paradise" in 30-21 = 9
62+
undergroundSystem.checkIn(2, "Leyton", 21)
63+
undergroundSystem.checkOut(2, "Paradise", 30)
64+
65+
# return 6.66667, (5 + 6 + 9) / 3 = 6.66667
66+
r3 = undergroundSystem.getAverageTime("Leyton", "Paradise")
67+
assert r3 == (5 + 6 + 9) / 3
68+
69+
print(r1, r2, r3)
70+
71+
72+
args_parser = argparse.ArgumentParser()
73+
args_parser.add_argument('--test', action='store_true',
74+
default=False, required=False)
75+
76+
args = args_parser.parse_args()
77+
78+
if args.test:
79+
test1()

leetcode/python/biasButFair.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
from random import randint
2+
3+
HEADS, TAILS = 1, 0
4+
5+
6+
def biased():
7+
"""
8+
HEADS with 20% probability
9+
A biased function that returns TAILS with 80% probability and
10+
11+
Returns:
12+
Int: 1 if HEADS, 0 if TAILS
13+
"""
14+
15+
# generate a random number between 0–99, both inclusive
16+
r = randint(0, 99)
17+
18+
# return TAILS if we got a number between [0–79]; otherwise, return HEADS
19+
return TAILS if (r <= 79) else HEADS
20+
21+
22+
# Return HEADS and TAILS with equal probability using the specified function
23+
def generate():
24+
while True:
25+
first = biased()
26+
second = biased()
27+
if first is not second:
28+
return first # or return second
29+
30+
31+
if __name__ == '__main__':
32+
x = y = 0
33+
bx = by = 0
34+
for i in range(100000):
35+
val = generate()
36+
print(val)
37+
if val > 0:
38+
x += 1
39+
else:
40+
y += 1
41+
42+
bval = biased()
43+
if bval > 0:
44+
bx += 1
45+
else:
46+
by += 1
47+
48+
print('HEADS ~', x / 1000, '%') # ~50%
49+
print('TAILS ~', y / 1000, '%') # ~50%
50+
print()
51+
print('B_HEADS ~', bx / 1000, '%')
52+
print('B_TAILS ~', by / 1000, '%')

leetcode/python/check-eq-trees.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Node(object):
2+
def __init__(self, heap, current=0) -> None:
3+
right = 2 * current + 2
4+
self.right = Node(heap, right) if right < len(
5+
heap) and heap[right] is not None else None
6+
7+
left = 2 * current + 1
8+
self.left = Node(heap, left) if left < len(
9+
heap) and heap[left] is not None else None
10+
11+
self.value = heap[current]
12+
13+
14+
def are_equal(tree1: Node, tree2: Node):
15+
if tree1 is None and tree2 is None:
16+
return True
17+
18+
if tree1 is None or tree2 is None:
19+
return False
20+
21+
if tree1.value != tree2.value:
22+
return False
23+
24+
return are_equal(tree1=tree1.left, tree2=tree2.left) and \
25+
are_equal(tree1=tree1.right, tree2=tree2.right)
26+
27+
28+
tree1 = Node([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
29+
tree2 = Node([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
30+
res = are_equal(tree1, tree2)
31+
print(res)
32+
33+
tree1 = Node([1, 2, 3, 4])
34+
tree2 = Node([1, 2, 3, ])
35+
res = are_equal(tree1, tree2)
36+
print(res)
37+
38+
tree1 = Node([1, 2, 3, 4])
39+
tree2 = Node([1, 2, 3, 5])
40+
res = are_equal(tree1, tree2)
41+
print(res)
42+
43+
tree1 = Node([1, 2, 3, 4])
44+
tree2 = Node([1, -1, 3, 5])
45+
res = are_equal(tree1, tree2)
46+
print(res)
47+
48+
tree1 = Node([1, 2, 3, 4, None, None, 7, 8, 9, 10])
49+
tree2 = Node([1, 2, 3, 4, None, None, 7, 8, 9, 10])
50+
res = are_equal(tree1, tree2)
51+
print(res)

leetcode/python/combination_sum.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import queue
2+
from typing import List
3+
4+
5+
def combinationSum4(nums: List[int], target: int) -> int:
6+
combs = []
7+
8+
q = queue.Queue()
9+
for num in nums:
10+
q.put((num, [num]))
11+
12+
while not q.empty():
13+
curr, comb = q.get()
14+
15+
if curr == target:
16+
combs.append(comb)
17+
continue
18+
19+
for num in nums:
20+
if (num + curr) == target:
21+
combs.append(comb + [num])
22+
elif (num + curr) < target:
23+
q.put((curr+num, comb + [num]))
24+
25+
return len(combs)
26+
27+
28+
COMB = None
29+
30+
31+
def helper(nums: List[int], target: int) -> int:
32+
global COMB
33+
34+
if COMB[target] != 0:
35+
return COMB[target]
36+
37+
c = 0
38+
for num in nums:
39+
if target >= num:
40+
c += helper(nums, target-num)
41+
42+
COMB[target] = c
43+
44+
return c
45+
46+
47+
def comb_sum(nums: List[int], target: int) -> int:
48+
global COMB
49+
COMB = [0 for _ in range(target+1)]
50+
COMB[0] = 1
51+
return helper(nums, target)
52+
53+
54+
def cs(nums: List[int], target: int) -> int:
55+
combs = [0 for _ in range(target+1)]
56+
combs[0] = 1
57+
58+
for i in range(len(combs)):
59+
for num in nums:
60+
if (i - num) >= 0:
61+
combs[i] += combs[i - num]
62+
63+
return combs[target]
64+
65+
66+
l = [1, 2, 3]
67+
t = 4
68+
r = combinationSum4(l, t)
69+
print('Result 1 ->', r, cs(l, t))
70+
71+
l = [9]
72+
t = 3
73+
r = combinationSum4(l, t)
74+
print('Result 2 ->', r, cs(l, t))
75+
76+
l = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
77+
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
78+
t = 10
79+
r = combinationSum4(l, t)
80+
print('Result 3 ->', r, cs(l, t))
81+
82+
83+
l = [4, 2, 1]
84+
t = 32
85+
r = comb_sum(l, t)
86+
print('Result 4 ->', r)
87+
print('Result 4.1 ->', cs(l, t))

leetcode/python/emptyMain.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from typing import Any
2+
3+
4+
class A():
5+
def __init__(self) -> None:
6+
print('Hello World')
7+
8+
9+
A()

leetcode/python/equal.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def equal(a, b):
2+
return a ^ b
3+
4+
5+
print(equal(5, 9))
6+
print(equal(4, 8))
7+
print(equal(4, 4))

leetcode/python/evenOdd.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
def isEven(number: int):
2+
return bool(number % 2)
3+
4+
5+
def isEvenBit(number: int):
6+
return number & 1
7+
8+
9+
print(isEven(3))
10+
print(isEven(4))
11+
12+
print(isEvenBit(3))
13+
print(isEvenBit(4))

0 commit comments

Comments
 (0)