# Python
## Python String Formatting
```python
print("{hh:02d}:{mm:02d}".format(hh=hh, mm=mm))
```
`"{hh:02d}"` and `"{mm:02d}"` are placeholders where variables will be inserted.
`02d` is a format specification.
`d` means the variable is expected to be an integer.
`02` means the integer should be formatted to have at least 2 digits. If the integer is only one digit, it will be padded with a leading zero.
```python
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Alice and I am 30 years old.
```
```python
# Limit the decimal places to 2
print("{:.2f}".format(3.14159265))
# Output: 3.14
```
```python
# Use comma as a thousand separator
print("{:,}".format(1000000))
# Output: 1,000,000
```
**Using f-string**
```python
name = "Eve"
age = 28
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Eve and I am 28 years old.
# Using expressions inside f-string
print(f"Five times two is {5 * 2}.")
# Output: Five times two is 10.
```
## String Parsing
1. Tokenization
```python
string = "Hello, World!"
token = string.split(", ")
print(token) # ['Hello', 'world!']
```
2. Searching for Substrings
```python
string = "Hello, world!"
print("world" in string) # True
```
3. Join
```python
fruits = ['apple', 'banana', 'orange']
s = ",".join(fruits) # 'apple,banana,orange'
```
4. startwith(prefix) & endswith(suffix)
```python
s = "apple pie"
s.startswith("apple") # True
s.endswith("pie") # True
```
5. replace(old, new):
Replaces all occurrences of a substring with another substring.
```python
s = "apple pie"
s.replace("apple", "cherry") # 'cherry pie'
```
6. find(substring):
```python
s = "apple pie"
s.find("pie") # 6
```
7. String Slicing:
```python
s = "Hello, world!"
first_five_chars = s[:5] # "Hello"
last_five_chars = s[-5:] # "orld!"
```
8. String Concat
```python
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!" # "Hello, Alice!"
strings = ["Hello", "World", "from", "Python"]
result = " ".join(strings)
```
9. f-string
```python!
name = "World"
result = f"Hello {name} !"
print(result) # 打印出来 Hello World !
```
## Array 和 String的相互转换
**Array -> String**
```python!
char_list = ['H', 'e', 'l', 'l', 'o']
string = ''.join(char_list)
print(string) # Output: Hello
```
**String -> Array**
```python!
string = "Hello"
char_list = list(string)
print(char_list) # Output: ['H', 'e', 'l', 'l', 'o']
```
## Python Array Operation
**Slicing**
`arr[start: stop]` gets elements from `start` to `stop-1`
`arr[start: stop: step]` gets elements from `start` to `stop - 1` with a step of `step`.
eg. arr[::-1] , start = 默认值0, stop = 默认值 len(arr), 所以经常用arr[::-1]来做reversing。
**Deep Copy**
arr[:]
最典型的就是在backtracking里 path[:] 深度拷贝
**典型题**
[271. Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/description/)
## Python Dictionary View Object 视图对象
在 Python 中,当您调用字典(dict)的 `.keys(), values(), items()` 方法时,返回的是一个“视图对象”(view object)。这个视图对象提供了一个字典的键(keys)的动态视图。这意味着:
1. **动态连接**:视图对象与原始字典是动态连接的。也就是说,如果您更改了原始字典,视图对象也会相应地显示这些更改。例如,如果您向字典添加或删除键,这些更改会立即反映在其 `.keys()` 视图上。
2. **不是一个独立的列表**:与返回所有键的独立列表不同,视图对象不会创建键的副本。因此,它在内存使用上更高效,特别是对于大型字典。
3. **支持集合操作**:由于视图对象类似于集合,您可以对其执行某些集合操作,如并集、交集等。
[215. Kth Largest Element in an Array](https://leetcode.com/problems/top-k-frequent-elements/)
```python!
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# 很明显的quick select
freq = collections.Counter(nums)
unique = list(freq.keys())
# freq.keys() 是个view object
def quick_select(keys, k):
left, right = [], []
random_key = random.choice(keys)
# random.choice() 这个api不支持view object
pivot = freq[random_key]
for key in keys:
if freq[key] >= pivot:
left.append(key)
elif freq[key] < pivot:
right.append(key)
if len(left) > k:
return quick_select(left, k)
if len(left) < k:
return left + quick_select(right, k - len(left))
return left
return quick_select(unique, k)
```
## 易错点
[49. Group Anagrams](https://leetcode.com/problems/group-anagrams/description/)
**错误答案**
```python!
# 这个是错的!!!!
class Solution:
def getkey(self, s: str):
return sort ed(s) # 这里返回的是一个list,list不能被hash,所以不能作为hashmap的key
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = collections.defaultdict(list)
for s in strs:
key = self.getkey(s)
res[key].append(s)
return [res.values()] # res.values 返回的已经是list of list了,不需要再多一层
```
**正确答案**
```python
class Solution:
def getkey(self, s: str):
return tuple(sorted(s))
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = collections.defaultdict(list)
for s in strs:
key = self.getkey(s)
res[key].append(s)
return res.values()
```