🌑

Stephen Cheng

Awesome Programming Skills for Python User

 

Stephen Cheng

Intro

Here are some awesome programming skills shared for Python users. Hopefully it’s useful to you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# most frequent element in  a list

a = [1,2,3,1,2,3,2,2,2,4,5,1]

print(max(set(a), key = a.count))

# use Counter

from collections import Counter

cnt = Counter(a)
print(cnt.most_common(3))

# check two strings have same characters

from collections import Counter

str1 = "I see him"
str2 = "him I see"

print(Counter(str1) == Counter(str2))

# reverse string

b = 'abcdefghijklmnopqrstuvwxyz'
print(b[::-1])

for char in reversed(b):
print(char)

num = 123456789
print(int(str(num)[::-1]))

# transpose 2d array

original = [['a','b'], ['1','2'],['A','B']]
transposed = zip(*original)
print(list(transposed))

# call different functions with same arguments

def product(a,b):
return a*b

def add(a,b):
return a+b

x = True
print((product if x else add)(5,7))


# a shallow copy
e = [1,2,3,4,5]
d = e
d[0] = 10
print(d,e)

d2 = e[:]
d2[0] = 11
print(d2,e)

# deep copy

from copy import deepcopy

f = [[1,2],[3,4]]
f2 = deepcopy(f)
f[0] = ['x','y']
print(f,f2)

# sort a dict by its value with built-in sorted func

g = {'apple':50, 'banana':25, 'orange': 20, 'watermelon':10}

print(sorted(g.items(), key = lambda x:x[1]))

# use itemgetter instead of a lambda

from operator import itemgetter

print(sorted(g.items(), key=itemgetter(1)))

# sort dict by value

print(sorted(g, key = g.get))

# merge dict

d1 = {'x':1}
d2 = {'y':2}


print({**d1, **d2}) #python 3.5

print(dict(d1.items() | d2.items())) #python 3.5

d1.update(d2) #python 3.5
print(d1)

# convert list to comma separated string

data = [1,'re', 3, 'fa', 5]
print(','.join(map(str, data)))

# find index of min/max element

h = [40, 30, 20, 10, 50]

def minIndex(lst):
return min(range(len(lst)), key = lst.__getitem__)

def maxIndex(lst):
return max(range(len(lst)), key = lst.__getitem__)

print(minIndex(h))
print(maxIndex(h))

# remove duplicate items from list

i = [6,2,2,3,4,4,4,5]

print(list(set(i)))

from collections import OrderedDict

print(list(OrderedDict.fromkeys(i).keys()))

, , — Dec 24, 2018

Search

    Made with ❤️ and ☀️ on Earth.