-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenericRoutines.py
235 lines (196 loc) · 6.5 KB
/
genericRoutines.py
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#####################################################################################################################
"""Find the uniqe elements in a list of elements"""
def uniqueList(inp_list):
uniq_list = list(set(inp_list))
return uniq_list
#####################################################################################################################
"""Generate a fibonacci series using a generator"""
def fibonacci_by_generator(num):
a,b = 0,1
for i in xrange(0,num):
yield "{}:{}".format(i+1,a)
a,b = b, a+b
"""
###calling the fibonacci function
for item in fibonacci_by_generator(10):
print(item)
"""
#####################################################################################################################
"""print the number and its count in a list in order of their appearances
example : [ 1,2,3,3,2,3,4,2,1] => 1:2,2:3,3:3,4:1
"""
def countOccurancesInList(inp_list=None):
s=set()
res = []
for x in inp_list:
#print(x)
print(f"current value is {x}")
if x in s:
pass
else:
res.append("{}:{}".format(x,inp_list.count(x)))
s.add(x)
return ','.join(res)
"""test the function
countOccurancesInList([1,2,3,4,3,2,3,5,6,2,3,5,2,4,6,32,5,1,43,32,2,3,4,21,1,2,4,45,32,1,3,0])
output:
1:4,2:6,3:6,4:4,5:3,6:2,32:3,43:1,21:1,45:1,0:1
"""
############### OR ###############
def countOccurancesInList(l):
d = {}
for item in l:
if item in d:
d[item] = d[item] + 1
else:
d[item] = 1
print(d)
##OR
def countOccurancesInList(l):
d = {}
for item in l:
try:
d[item] = d[item] + 1
except:
d[item] = 1
print(d)
#OR
def countOccurancesInList(l):
d = {}
for item in l:
d[item] = d.get(item, 0) + 1
print(d)
#####################################################################################################################
"""Transpose a multidimensional list
for example -> [ [1,2,3],[4,5,6],[7,8,9] ]
should be transposed to [ [1,4,7],[2,5,8],[3,6,9] ]
"""
def transpose(l):
#method1
res1 = [ [row[i] for row in l] for i in range(len(l)) ]
#method2
res2 = [ list(i) for i in zip(*l) ]
#####################################################################################################################
"""Inverting a dictionary""""""
def invert_dict(m):
print(m.items())
######[('a', 1), ('c', 3), ('b', 2), ('d', 4)]
print(zip(m.values(), m.keys()))
####[(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
mi = dict(zip(m.values(), m.keys()))
print(mi)
###{1:'a',2:'b',3:'c',4:'d'}
####OR####
mi = {v:k for k,v in m.items()}
print(mi)
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
invert_dict(m)
#####################################################################################################################
"""Flateen a multidimensional list to one dimensional list
for example: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
def flatten_list(l):
##method 1 using comprehension
res = [ item for row in l for item in row ]
print(res)
##method 2 using loop
res = []
for row in l:
for item in row:
res.append(item)
print(res)
#####################################################################################################################
"""create a list of anagrams from a list of strings
For example: ['eat', 'ate', 'done', 'tea', 'soup', 'node']
=> [['done', 'node'], ['eat', 'ate', 'tea'], ['soup']]
"""
def anagram(words):
anagrams = {}
for word in words:
sword = ''.join(sorted(word))
try:
anagrams[sword].append(word)
except KeyError:
anagrams[sword] = [word]
anagrams_list = [v for v in anagrams.values() ]
print(anagrams_list)
words = ['eat', 'ate', 'done', 'tea', 'soup', 'node']
anagram(words)
#####################################################################################################################
###Given a string, repeatedly remove adjacent pairs of matching characters and then print the reduced result.
##aaabccddd → abccddd
##abccddd → abddd
##abddd → abd
def super_reduced_string(s):
if not s:
return 'Empty String'
stack = ''
for i, c in enumerate(s):
if stack and stack[-1] == c:
stack = stack[:-1]
else:
stack += c
if stack:
return stack
return 'Empty String'
print(super_reduced_string('aaabccddd') )
OR
def super_reduced_string(s):
stack = []
for i,c in enumerate(s):
if not stack or c != stack[-1]:
stack.append(c)
else:
stack.pop()
if stack:
return ''.join(stack)
else:
return 'Empty String'
print(super_reduced_string('aaabccddd') )
###########################################################################################################################
#we want to write a program that takes a list of filenames as arguments and to print only the line which has a particular substring,
like grep command in unix.
def readfiles(filenames):
for f in filenames:
with open(f) as fr:
for line in fr:
yield line
def grep(pattern, lines):
return (line for line in lines if pattern in line)
def printlines(lines):
for line in lines:
print(line)
def main(pattern, filenames):
lines = readfiles(filenames)
lines = grep(pattern, lines)
printlines(lines)
#########################################################################################################################
# Find the longest non repeating substring in a string
#input 'pwwkew'
#output 'wke'
def max_substring(string):
last_substring = ''
max_substring = ''
for x in string:
k = find_index(x,last_substring)
last_substring = last_substring[(k+1):]+x
print(f'last substrin = {last_substring}')
if len(last_substring) > len(max_substring):
max_substring = last_substring
return max_substring
def find_index(x, lst):
k = 0
while k <len(lst):
if lst[k] == x:
return k
k +=1
return -1
###flatten any dimension list
def flatten(items):
for x in items:
if isinstance(x, list):
for sub_x in flatten(x):
yield sub_x
else:
yield x
print(list(flatten([1,2,3,[4,5,[6,7]]])))