Skip to content

Commit be78565

Browse files
authored
Add functions to manipulate lists and dictionaries
1 parent 5ae1705 commit be78565

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Week03/sequences_heval_sogut.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def remove_duplicates(seq: list) -> list:
2+
"""
3+
Remove duplicate elements from a list while preserving the original order.
4+
Only the first occurrence of each element is kept.
5+
"""
6+
seen = set()
7+
result = []
8+
for item in seq:
9+
if item not in seen:
10+
seen.add(item)
11+
result.append(item)
12+
return result
13+
14+
15+
def list_counts(seq: list) -> dict:
16+
"""
17+
Count how many times each element appears in a list.
18+
Returns a dictionary where keys are elements and values are counts.
19+
"""
20+
counts = {}
21+
for item in seq:
22+
counts[item] = counts.get(item, 0) + 1
23+
return counts
24+
25+
26+
def reverse_dict(d: dict) -> dict:
27+
"""
28+
Reverse the keys and values of a dictionary.
29+
If multiple keys have the same value, the last one overwrites the earlier ones.
30+
"""
31+
reversed_dict = {}
32+
for key, value in d.items():
33+
reversed_dict[value] = key
34+
return reversed_dict

0 commit comments

Comments
 (0)