Common Python Operations

intervals.sort(key=lambda p: p[0])

LC 189 [:] slicing operation

dict

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Dictionary with initial key-value pairs
filled_dict = {'key1': 'value1', 'key2': 'value2'}

# Using dict() constructor
constructed_dict = dict(key1='value1', key2='value2')

valueList=list(filled_dict.values())

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
for key in my_dict.keys():
    print(f"Key: {key}")

LC 49

defaultdict

defaultdict(int) is more suitable for general scenarios where a default value is needed when a key does not exist, not necessarily just for counting.

1
2
3
dd = defaultdict(int)  # int type, default value is 0
dd = defaultdict(lambda: 'default_value')
defaultdict(lambda: [0, 0]) # key is an array

Counter

Counter is more suitable for frequency statistics and occurrence analysis of iterables. Its built-in counting methods can simplify many scenarios. Counter(p) means creating a counter from an iterable.

Iterable: list, tuple, str, dict, set, range, enumerate, map

del cnt[x] deletes the count for x. len(cnt) gets the number of elements counted.

Create a new Counter

1
collections.Counter(nums)

list

index()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
numbers = [1, 2, 3, 4, 5]

# Find the position of number 3
position = numbers.index(3)
print(position)  # Output: 2

# Find number 3 between index 1 and 4
position = numbers.index(3, 1, 4)
print(position)  # Output: 2

# Try to find a non-existent number
try:
    position = numbers.index(7)
except ValueError as e:
    print("Not found")  # Output: Not found

sort()

It sorts the list in place and does not create a new list. It can only be applied to lists.

String comparison

Independent of length

1
print("apple" < "apricot")  # False

iterable

Iterable: list, tuple, str, dict, set, range, enumerate, map sorted(iterable) returns a new sorted list. The original iterable is not modified. Time complexity is O(nlogn)

deque = collections.deque()

ACM Mode

Zhihu compilation

zip

1
2
3
4
5
names = ['Alice', 'Bob', 'Charlie']
scores = [90, 85, 88]

zipped = zip(names, scores)
print(list(zipped))

Output: [(‘Alice’, 90), (‘Bob’, 85), (‘Charlie’, 88)]

heapq

1
2
3
import heapq

heap = []