Python Common Code

Frequently used python code

Python Quick Start

Ternary operator

1
p_max_count = len(i['prompt']) if p_max_count < len(i['prompt']) else p_max_count

Calculate time spent

1
2
3
4
5
6
7
8
import datetime

start_time = datetime.datetime.now()

# target function

end_time = datetime.datetime.now()
print("it takes {} seconds".format((end_time - start_time).seconds))

Random

Int

1
2
3
4
import random

# generate integer from 1 to 20
print (random.randint(1, 20))

Sort

Sort 2D list

1
2
3
4
5
6
7
8
9
10
11
12
13
employees = [[10, 'Jack', 1997], [3, 'Jack', 1998], [8, 'Smith', 2001]]

sorted_e_a = sorted(employees, key=(lambda x:x[0]))
sorted_e_b = sorted(employees, key=(lambda x:[x[2], x[1]]), reverse=True)

print(employees)
print(sorted_e_a)
print(sorted_e_b)

# output
# [[10, 'Jack', 1997], [3, 'Jack', 1998], [8, 'Smith', 2001]]
# [[3, 'Jack', 1998], [8, 'Smith', 2001], [10, 'Jack', 1997]]
# [[8, 'Smith', 2001], [3, 'Jack', 1998], [10, 'Jack', 1997]]

Sort dictionary

1
2
3
4
5
6
7
8
9
10
11
dic = {2: 56, 1: 2, 7: 12, 4: 24, 5: 12, 3: 323}
sorted_dict_1 = sorted(dic.items(), key = lambda kv:(kv[0]))
sorted_dict_2 = sorted(dic.items(), key = lambda kv:(kv[1]))
sorted_dict_3 = sorted(dic.items(), key = lambda kv:(kv[1], kv[0]))
print(sorted_dict_1)
print(sorted_dict_2)
print(sorted_dict_3)

# [(1, 2), (2, 56), (3, 323), (4, 24), (5, 12), (7, 12)]
# [(1, 2), (7, 12), (5, 12), (4, 24), (2, 56), (3, 323)]
# [(1, 2), (5, 12), (7, 12), (4, 24), (2, 56), (3, 323)]

Reverse

1
2
3
a = "54321"
print(a[::-1])
# 12345

List

List generator

1
2
3
4
5
6
a = [1, 2, 3, 4, 5, 6]
b = [i+1 for i in a]
# b = [2, 3, 4, 5, 6, 7]

c = [i+1 for i in a if i % 2 == 0]
# c = [3, 5, 7]

For

For-Else

The only way that the code would run to “else”, is that there is no break in the for-loop.

1
2
3
4
5
6
7
8
for item in container:
if search_something(item):
# Found it!
process(item)
break
else:
# Didn't find anything..
not_found_in_container()

String

Case

1
2
3
4
5
6
a = "String"
print(a.lower())
print(a.upper())

# string
# STRING

Component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
a = "123asJIjg"
b = "123"
c = "asJIjg"

print(a.isdigit(), a.isalpha(), a.isalnum())
print(b.isdigit(), b.isalpha(), b.isalnum())
print(c.isdigit(), c.isalpha(), c.isalnum())

# False False True
# True False True
# False True True

# isdigit(): if totally made of number
# isalpha(): if totally made of alpha
# isalnum(): if totally made of number or alpha

Initilization

Dictionary

1
2
3
x = dict.fromkeys(['A', 'B', 'C'], 0)
print(x)
# {'A': 0, 'B': 0, 'C': 0}

Simplify

Dictionary Count

1
2
3
4
5
6
7
if char not in unigram_counts:
unigram_counts[char] = 1
else:
unigram_counts[char] += 1

# can be replace by
unigram_counts[char] = unigram_counts.get(char, 0) + 1

Visualization

Matplotlib

1
import matplotlib.pyplot as plt
Draw by one list
1
2
3
4
import matplotlib.pyplot as plt
a = [17, 15, 1479, 76, 1485, 68, 1493, 10, 1500, 1492, 1478, 86, 1515, 1518, 1520, 1502, 1519, 1497, 1525, 87]
plt.figure(1)
plt.plot(a)

Draw by two list
1
2
3
4
5
6
import matplotlib.pyplot as plt
a = [17, 15, 1479, 76, 1485, 68, 1493, 10, 1500, 1492, 1478, 86, 1515, 1518, 1520, 1502, 1519, 1497, 1525, 87]
b = a[::-1]
plt.figure(1)
plt.plot(a, color="r", marker="*")
plt.plot(b, color="b", marker="o")