# 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()))