Python code cheatsheet

Default Min and Max

  • Use float('inf') for positive infinity.

  • Use float('-inf') for negative infinity.xfcha

dict

nodeInfo = dict()
nodeInfo[ng] = nodeInfo.get(ng, 0) + 1 #有则返回vaL 无则返回0 这样可以无需初始化

de'que

一般 qfs里使用, 用popleft取代list.pop(0), time complexity: o(n) => o(1)

q = deque()
cur = q.popleft()

数组slicing

reverse : s[::-1] start:stop:step

s = "hello"
reversed_s = s[::-1]
print(reversed_s)  # Output: "olleh"
presums[-1] will return last element of the list

二维数组

dp = [[0]*(m+1) for _ in range(n+1)]
n//2 vs n/2
n//2 floor, return int
n/2 true division, return float

Ord(): return unicode code point of a charactor

print(ord('a'))  # Output: 97

sort 自定义函数

        pairs.sort(key = lambda x: (x[1],x[0]))#记得要加括号!!!!

*list will unpack the list

workers = [1, 2, 3, 4]
# Using *workers in a print statement
print(*workers)    # Output: 1 2 3 4

default: Functions: max() and min() support the default parameter.

min/max([], default=0)  # Returns 0

遍历dictionary:

```python
for k,v in d.items():
    v.reserse() #v is a list
```

number char coversion

s = "a3b7Z!"

for char in s:
    if char.isdigit():
        print(f"'{char}' is a number.")
    elif char.isalpha():
        print(f"'{char}' is a letter.")
    else:
        print(f"'{char}' is neither a number nor a letter.")

Convert a Character to its ASCII/Unicode Number

char = 'A' number = ord(char) print(number) # Output: 65

Convert a Numeric Character to its Integer Value

char = '7' number = int(char) print(number) # Output: 7

Counter

returnr dict, most_common(k) returns a list of (element, count) tuples sorted by counts.


return [i for i,_ in collections.Counter(nums).most_common(k)]

Sort

Define a lambda function to sort various data structures like lists, dictionaries, and tuples.

In-place vs. Copy:

  • sorted() returns a new sorted list.

  • .sort() sorts the list in place and returns None.

Sorting a List

# Example list of tuples
data = [(1, 3), (4, 1), (5, 2)]

# Sorting the list based on the second element of each tuple
sorted_data = sorted(data, key=lambda x: x[1])

# Output: [(4, 1), (5, 2), (1, 3)]
print(sorted_data)

Sorting a Dictionary by Value

# Example dictionary
data = {'a': 3, 'b': 1, 'c': 2}

# Sorting the dictionary by its values
sorted_data = sorted(data.items(), key=lambda x: x[1])

# Output: [('b', 1), ('c', 2), ('a', 3)]
print(sorted_data)

Sorting a List of Dictionaries

# Example list of dictionaries
data = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}, {'name': 'Doe', 'age': 30}]

# Sorting by the 'age' key
sorted_data = sorted(data, key=lambda x: x['age'])

# Output: [{'name': 'Jane', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Doe', 'age': 30}]
print(sorted_data)

deque

整个list 加入deque, extend()

d.extend(lst)

use cache in DP

from functools import lru_cache  # Import lru_cache
@lru_cache(None)

Last updated