Skip to content

Instantly share code, notes, and snippets.

@kayalshri
Last active March 15, 2019 12:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kayalshri/c396369b66cb75d07dd5886808a192a5 to your computer and use it in GitHub Desktop.
Save kayalshri/c396369b66cb75d07dd5886808a192a5 to your computer and use it in GitHub Desktop.
Interview QA in python
## Get Number of unique elements in a list
x = ['f', 'e', 'e', 'f', 'f']
# output: {'e': 2, 'f': 3}
# Solution
o = {i:x.count(i) for i in x}
print(o)
#-----------------------------------------------------------------------------------------------------
## Get Number of unique elements in dict
y = {'a': 1, 'c': 5, 'b': 4, 'd': 6, 'e':5, 'f':4, 'g':1, 'h':5}
# output {1: 2, 4: 2, 5: 3, 6: 1}
# Solution
o = {i:y.values().count(i) for i in y.values()}
print(o)
#-----------------------------------------------------------------------------------------------------
## Get Number of unique values in a dict
y = {'a': 1, 'c': 5, 'b': 4, 'd': 6, 'e':5, 'f':4, 'g':1, 'h':5}
# output: [1, 4, 5, 6]
# Solution
list(set(y.values()))
#-----------------------------------------------------------------------------------------------------
## Replace an existing item value with a new key in a dictionary
y = {'a': 1, 'c': 5, 'b': 4}
# output: {'c': 5, 'b': 4, 'anc': 1}
# Solution
y['anc'] = y.pop('a')
#-----------------------------------------------------------------------------------------------------
## csv file with first row has column name, other rows contain data for each column. generate array of dict and JSON
'''
Eg.
name, city,age, country , language ,phone
abc,xyz, 23 , sdf, sdf, 3454
dg, reer,43, dfgf , were,3454
sdf, rtert , 26, sdfdf, fgf,43454
'''
inf = open('csv2json.csv', 'r')
lines = inf.readlines()
cols = [x.strip() for x in lines.pop(0).strip().split(',')]
out = [{j:d.strip().split(',')[i] for i,j in enumerate(cols)} for d in lines]
print(out)
## [{'city': 'xyz', 'name': 'abc', 'language': ' sdf', 'country': ' sdf', 'age': ' 23 ', 'phone': ' 3454'}, {'city': ' reer', 'name': 'dg', 'language': ' were', 'country': ' dfgf ', 'age': '43', 'phone': '3454'}, {'city': ' rtert ', 'name': 'sdf', 'language': ' fgf', 'country': ' sdfdf', 'age': ' 26', 'phone': '43454'}]
import json
json.dumps(out)
## '[{"city": "xyz", "name": "abc", "language": " sdf", "country": " sdf", "age": " 23 ", "phone": " 3454"}, {"city": " reer", "name": "dg", "language": " were", "country": " dfgf ", "age": "43", "phone": "3454"}, {"city": " rtert ", "name": "sdf", "language": " fgf", "country": " sdfdf", "age": " 26", "phone": "43454"}]'
#-----------------------------------------------------------------------------------------------------
## give example for pass by value, and pass by reference
# all primitive datatypes arguments are 'passed by value'
# others (list, dict, ...) are 'passed by reference'
#-----------------------------------------------------------------------------------------------------
## what is the use of r prefix?
# remove tab (\\t)
x = 'abc\\tsdkfk\\ndkfjk'
re.sub(r'\\t', '', abc)
# output: 'abcsdkfk\\ndkfjk'
# re.sub('\\t', '', abc) - Fail
# re.sub('\t', '', abc) - Fail
#-----------------------------------------------------------------------------------------------------
# Merge two dict uniq values
x = {'a':1, 'b':2}
y = {'e':3, 'y':2}
# output: {'a': 1, 'y': 2, 'b': 2, 'e': 3}
x.update(y)
{**x,**y}
# {'a': 1, 'y': 2, 'b': 2, 'e': 3}
{**y,**x}
#{'b': 2, 'y': 2, 'e': 3, 'a': 1}
# Merge two dict with same key
x = {'a':1, 'b':2}
y = {'b':7, 'y':8}
#{'a': 1, 'y': 8, 'b': 7}
#{'a': 1, 'y': 8, 'b': 7}
# Merge & Update Value in Dict
x = {'a':1, 'b':2}
c = ['b','c','d']
v = [4,5,6]
# output: {'a': 1, 'c': 5, 'b': 4, 'd': 6}
x.update({a:v[i] for i, a in enumerate(c)})
#-----------------------------------------------------------------------------------------------------
# sort list / dates:
arr = ['05', '15', '01', '27', '07', '16', '03', '25', '08', '21', '30', '17', '04']
#output = ['01', '03', '04', '05', '07', '08', '15', '16', '17', '21', '25', '27', '30']
def sortDates(inArr):
lyStrip = lambda a: int(str(a).lstrip("0"))
lyAdd = lambda w: '0'+str(w) if len(str(w)) == 1 else str(w)
sortedArr = map(lyAdd, sorted(map(lyStrip,inArr)))
return sortedArr
#arr = ['05', '15', '01', '27', '07', '16', '03', '25', '08', '21', '30', '17', '04']
sarr = sortDates(arr)
print(list(sarr))
#-----------------------------------------------------------------------------------------------------
## Remove an element from the list
x = [3,4,2,5,6,1]
#output: [3,2,5,6,1]
x.remove(4)
## remove an element by index
x = [3,4,7,5,6,1]
x.pop(2)
x # output: [3,4,5,6,1] ## 7
x.pop() # default remove the last element [3,4,5,6]
## add/append an element to the list
x.append(6)
## get the index of an element
x.index(6) ## 3
# add an element by index
x[10] = 82 ## error: list index out of range
x[3] = 82
x ## [3, 4, 5, 82, 6]
#-----------------------------------------------------------------------------------------------------
# remove an item from the dict
y = {'a': 1, 'c': 5, 'b': 4, 'd': 6}
y.pop('a') ## {'c': 5, 'd': 6, 'b': 4}
del y['a'] ## {'c': 5, 'b': 4}
# get the key of a given value (eg. 4) from the dictionary
y = {'a': 1, 'c': 5, 'b': 4, 'd': 6,'e':4}
search_age = 4
for name, age in y.items():
if age == search_age:
print(name)
# output:'b' ,'e'
# replace lowercase keys to uppercase
y = {'a': 1, 'c': 5, 'b': 4}
{k.upper():y[k] for k in y} # output: {'A': 1, 'C': 5, 'B': 4} ## solution 1
for k in y:
print({k.upper():y[k]}) ## solution 2
{k.upper():v for k,v in y.items()} ## solution 3
# change camelCase to snake_case of keys in dict
d = {'aBc':1, 'cDe': 4, 'eFg': 5}
lda = lambda x: '_' + x.group(1).lower()
{re.sub('([A-Z])', lda, k) : d[k] for k in d}
# output: {'e_fg': 5, 'c_de': 4, 'a_bc': 1}
# duplicate uppercase in keys in dict
d = {'aBc':1, 'cDe': 4, 'eFg': 5}
lda = lambda x: x.group(1)*2
{re.sub('([A-Z])', lda, k) : d[k] for k in d}
# output: {'cDDe': 4, 'eFFg': 5, 'aBBc': 1}
# replace 0 in the list to 'null'
x = [0,3,4,0,2,6,0]
["null" if a == 0 else a for a in x] ## solution 1
map(lambda a: "null" if a == 0 else a, x) ## solution 2
## output ['null', 3, 4, 'null', 2, 6, 'null']
# remove spl characters from a string
ab = 'sdfjkh@ghjg#$sdjfkl&hjh*kkj^kkj!@~kjkd<kjk,KJ;:lk '
re.sub('[^\w]', '' ,ab) ## output: 'sdfjkhghjgsdjfklhjhkkjkkjkjkdkjkKJlk'
# excape all spl characters
ab = 'sdfjkh@ghjg#$sdjfkl&hjh*kkj^kkj!@~kjkd<kjk,KJ;:lk'
re.excape(ab) ## output: 'sdfjkh\\@ghjg\\#\\$sdjfkl\\&hjh\\*kkj\\^kkj\\!\\@\\~kjkd\\<kjk\\,KJ\\;\\:lk'
# remove all white space from a string
x = 'abc\t hdnf sdf\ndslfk\n\tddff'
re.sub('\s+', '', x) ## output: 'abchdnfsdfdslfkddff'
# replace a string from an input string -> to be case insensitive
x = 'cancer and Tumor are the same'
re.sub('tumor|cancer', '', v, flags=re.IGNORECASE) ##output: ' and are the same'
# replace if 'tumor', or 'cancer' present in the string elements in the list
x = ['lung Cancer', 'brain tumor', 'kidney tumor', 'lung Tumor', 'blood cancer']
map(lambda y: re.sub(' cancer| tumor', '', y, flags=re.IGNORECASE), x) #output: ['lung', 'brain', 'kidney', 'lung', 'blood']
# convert all elements to string
n = [['a', 1], ['b', 2], ['c', 3]]
[[str(j) for j in i] for i in n] ## solution 1
map(lambda i: map(lambda j: str(j), i), n) ## solution 2
## output: [['a', '1'], ['b', '2'], ['c', '3']]
# can we merge list, tuple, and set?
a = [1,2,3]
b = (4,5,6)
c = set([6,7,8])
a.extend(b)
a.extend(c)
## output: [1, 2, 3, 4, 5, 6, 8, 6, 7]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment