-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolutions.txt
More file actions
2188 lines (1902 loc) · 54.7 KB
/
Copy pathsolutions.txt
File metadata and controls
2188 lines (1902 loc) · 54.7 KB
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
**1. Write a program to find the length of the string without using inbuilt function (len)**
```python
def _len(iterable):
_count = 0
for item in iterable:
_count += 1
return _count
>>> _len('Hello')
5
>>> _len([1, 2, 3, 4])
4
>>>
>>> _len({1, 2, 3})
3
>>> _len((1, 2, 3, 4))
4
>>>
**2. Write a program to reverse a string without using any inbuilt functions.**
```python
def reverse(any_string):
temp = []
for i in range(len(any_string)-1, -1, -1):
temp.append(any_string[i])
return ''.join(temp)
>>> reverse('Hello world')
'dlrow olleH'
>>>
>>> reverse('Python')
'nohtyP'
>>>
>>> reverse('racecar')
'racecar'
>>>
```
**3. Write a program to replace one string with another. e.g. "Hello World" replace "World" with "Universe".**
```python
>>> s = 'Hello world'
>>> s.replace('world', 'universe')
'Hello universe'
>>>
```
**4. How to convert a string to a list and vice-versa.**
```python
def convert_to_string(any_list):
return ''.join(any_list)
def convert_to_list(any_string):
return any_string.split()
>>> convert_to_list('steve')
['steve']
>>> convert_to_string(['steve', 'jobs'])
'stevejobs'
```
**5. Convert the string "Hello welcome to Python" to a comma separated string.**
```python
>>> s = "Hello welcome to Python"
>>>
>>> s
'Hello welcome to Python'
>>>
>>> temp = s.split()
>>> temp
['Hello', 'welcome', 'to', 'Python']
>>> ','.join(temp)
'Hello,welcome,to,Python'
```
```python
>>> s = "Hello welcome to Python"
>>> words = s.split()
>>> print(*words, sep=',')
```
**6. Write a program to print alternate characters in a string.**
```python
>>> s = 'hello world'
>>> print(s[::2]) # Using Slicing Syntax
Hlowrd
**7. Write a Program to print ascii values of the characters present in a string.**
```python
>>> s = 'hello'
>>>
>>> for c in s:
print(ord(c))
104
101
108
108
111
**8. Write program to convert upper case to lower case and vice-versa without using inbuilt method.**
```python
def convert(any_string):
l = []
for c in any_string:
temp = ord(c) # Get the ASCII value of the character
if temp>= 97 and temp<=122:
l.append(chr(temp - 32))
elif temp>=65 and temp<=90:
l.append(chr(temp+32))
return ''.join(l)
>>> convert('Hello WorlD')
'hELLOwORLd'
```
```python
def convert(any_string):
l = []
for c in any_string:
temp = ord(c)
if temp in range(97, 123):
l.append(chr(temp-32))
elif temp in range(65, 91):
l.append(chr(temp+32))
else:
l.append(chr(temp))
return ''.join(l)
>>> convert('Hello WorlD')
'hELLOwORLd'
```
**9. Write program to swap two numbers without using 3rd variable.**
```python
>>> a = 10
>>> b = 20
>>>
>>> b, a = a, b
>>> a
20
>>> b
10
>>>
```
**10. Write program to merge two different lists.**
```python
>>> a = [1, 2, 3]
>>>
>>> b = [4, 5, 6]
>>>
>>> c = [*a, *b]
>>> c
[1, 2, 3, 4, 5, 6]
>>>
```
```python
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
```
```python
>>> a + b
[1, 2, 3, 4, 5, 6]
```
```python
# Using chain
>>> from itertools import chain
>>> s = chain(a, b) # Returns an iterator
>>> list(s)
>>> [1, 2, 3, 4, 5, 6]
```
**11. Write program to read a random line in a file. (ex. 50, 65, 78th line)**
```python
from itertools import islice
def read_random_line(lineno):
with open('Data/access-log.txt') as f:
line = islice(f, lineno, lineno+1)
return list(line)
print(read_random_line(2))
```
**Alternate Solution**
```python
def read_random_line(lineno):
f = open('Data/sample.txt')
for index, line in enumerate(f, start=1):
if index == lineno:
return line
print(read_random_line(10))
```
**12. Write program to read a random lines in a file. (ex. I want read all lines 10th to 15th line)**
```python
from itertools import islice
def read_n_lines(start_line, end_line):
with open('Data/access-log.txt') as f:
s = islice(f, start_line,end_line)
for line in s:
print(line)
read_n_lines(10, 15)
```
**Alternate Solution**
```python
def read_n_lines(start_line, end_line):
with open('Data/access-log.txt') as enumerate(f, start=1):
if index in range(start_line, end_line):
print(line)
read_n_lines(10, 15)
```
**13 Program to print last "N" lines of a file.**
```python
from itertools import islice
def last_n_lines(n):
with open('sample.txt') as f:
for line in f:
line_count += 1
f.seek(0)
lines = islice(f, line_count-n, None)
return list(lines)
```
```python
from collections import
def tail(n):
with open('sample.log') as f:
d = deque(f, n) # only last 'n' lines will be loaded to the deque
return d
last_10_lines = tail(10) # returns last 10 lines of the file
for line in last_10_lines:
print(line)
```
**14. Write a program to check if the given string is Palindrome or not without using reversed method.**
```python
>>> def is_palindrome(iterable):
rev_iter = iterable[::-1]
if iterable == rev_iter:
return True
else:
return False
>>> is_palindrome('racecar')
True
>>> is_palindrome('malayalam')
True
>>> is_palindrome('hello')
False
>>>
```
**15 Write a program to search for a character in a given string and return the corresponding index.**
```python
>>> def search_character(string, key):
for index, c, in enumerate(string):
if c == key:
print(f'Character {c} is at index {index}')
>>> search_character('hello world', 'w')
Character w is at index 6
>>>
>>> search_character('hello world', 'd')
Character d is at index 10
>>>
>>>
```
```python
def search(string, key):
if string.find(key) > -1:
return string.find(key)
else:
print('Key not found')
```
```python
def search(string, key):
try:
return string.index(key)
except ValueError:
return "Key Not Found"
```
**16 Write a program to get the below output**
```python
sentence = "hello world welcome to python programming hi there"
d = {'h': ['hello', 'hi'], 'w': ['world', 'welcome'], 't': ['to', 'there'], 'p': ['python', 'programming'] }
from collections import defaultdict
d = defaultdict(list)
words = sentence.split()
for word in words:
d[word[0]].append(word)
```
**17 Write a to replace all the characters with - if the character occurs more than once in a string**
```python
my_string = 'hellohai' # O/P should be '-e--o-ai'
my_string = 'hellohai'
new_string = ''.join(['-' if s.count(c) > 1 else c for c in my_string])
print(new_string)
```
**18 write a decorator that returns only positive values of subtraction**
```python
def positive(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return abs(result)
return wrapper
@positive
def sub(a, b):
return a - b
>>> sub(1, 2)
1
>>> sub(-1, 100)
101
>>> sub(-100, 1)
101
>>> sub(3, 1)
2
>>> sub(-1, -2)
1
>>> sub(-2, 1)
3
>>>
```
**19 How to get the count of number of instances of a class that is being created.**
```python
class Login:
login_count = 0 # Class Variable that keeps count of login counts
def __init__(self):
Login.login_count += 1
>>> u1 = Login()
>>> Login.login_count
1
>>> u2 = Login()
>>> Login.login_count
2
>>> u3 = Login()
>>> Login.login_count
3
>>>
```
**20 Write a function which takes a list of strings and integers.If the item is a string it should print as is and if the item is integer of float it should reverse it.**
```python
def spam(items):
for item in items:
if isinstance(item, str): # Check if the item is an instance of String
print(item)
else:
temp = str(item) # Typecast Integer to String
print(temp[::-1]) # Reverse the String
>>> spam(['apple', 'yahoo', '1234', 100, 123.76, '26.23'])
apple
yahoo
1234
001
67.321
26.23
>>>
```
**21 Write a class named Simple and it should have iteration capability.**
```python
class Simple:
def __init__(self, items):
self._items = items
def __iter__(self):
return iter(self._items)
>>> s = Simple([1, 2, 3, 4, 5])
>>>
>>> for item in s:
print(item)
1
2
3
4
5
>>>
```
**22 Write a Custom class which can access the values of dictionaries using d['a'] and d.a**
```python
class MyDict:
def __init__(self, d):
self._dict = d
def __getitem__(self, item):
return self._dict[item]
# __getattr__ method is called only for missing attributes.(i.e. if you try to access an attribute which is not in instance dict)
def __getattr__(self, name):
return self._dict[name]
>>> d = MyDict({'a': 1, 'b': 2})
>>> d.a
1
>>> d.b
2
>>> d['a']
1
>>> d['b']
2
>>>
```
**23 Write a python program to get the below output**
```python
sentence = "Hi How are you"
o/p should be "iH woH era uoy"
>>> sentence = "Hi How are you"
>>> words = sentence.split()
>>> words
['Hi', 'How', 'are', 'you']
>>> reversed_words = [word[::-1] for word in words]
>>> reversed_words
['iH', 'woH', 'era', 'uoy']
>>> ' '.join(reversed_words)
'iH woH era uoy'
>>>
```
**24 Write a python program to get the below output**
```python
sentence = "Hi How are you"
o/p should be "ouy era woH iH"
>>> sentence = "Hi How are you"
>>> sentence[::-1]
'uoy era woH iH'
>>>
```
**25 Write a lambda function to add two numbers (a, b)**
```python
>>> add = lambda a, b: a + b
>>> add(1, 2)
3
>>> add(100, 300)
400
>>>
```
**26 What is the output of the following**
```python
a = [1, 2, 3]
b = [4, 5, 6]
print([a, b])
print((a, b))
>>> print((a, b))
([1, 2, 3], [4, 5, 6]) # Tuple of Lists
>>> print([a, b])
[[1, 2, 3], [4, 5, 6]] # List of Lists
>>>
```
**27 How to remove duplicates from the list without using inbuilt functions**
```python
>>> items = [1, 2, 3, 4, 1, 2, 3, 4, 5]
>>> uniques = []
>>> for item in items:
if item not in uniques:
uniques.append(item)
>>> print(uniques)
[1, 2, 3, 4, 5]
>>>
```
**28 Find the longest word in the sentence**
```python
sentence = "Hello world. Welcome to Python"
>>> sentence = "Hello world. Welcome to Python"
>>> words = sentence.split()
>>> d = {word: len(word) for word in words}
>>> max(d.items(), key= lambda item: item[-1])
('Welcome', 7)
>>>
```
```python
sentence = "hello world welcome to programming"
words = sentence.split()
max_len = 0
max_word = ''
for word in words:
if len(word) > max_len:
max_len = len(word)
max_word = word
print(max_len, max_word)
```
```python
>>> sentence = "hello world welcome to programming"
>>> max(sentence.split(), key=len)
>>> 'programming'
```
**29 write a program to reverse the values in the dictionary if the value is of type String**
```python
>>> d = {'a': 'hello', 'b': 100, 'c': 10.1, 'd': 'world'}
>>> rev = { key: value[::-1] if isinstance(value, str) else value for key, value in d.items()}
>>> rev
{'a': 'olleh', 'b': 100, 'c': 10.1, 'd': 'dlrow'}
```
**30 write a program to get 1234**
```python
t = ('1', '2', '3', '4')
>>> t = ('1', '2', '3', '4')
>>> ''.join(t) # Use join function
'1234'
>>>
```
**31 How to get the elements that are in list b but not in list a**
```python
a = [1, 2, 3] b = [1, 2, 3, 4]
>>> a = [1, 2, 3]
>>> b = [1, 2, 3, 4]
>>> set_a = set(a) # Convert the list to set
>>> set_b = set(b)
>>> set_b.difference(set_a)
{4}
>>>
```
```python
a = [1, 2, 3]
b = [1, 2, 3, 4]
for item in b:
if item not in a:
print(item)
```
**32 A function takes a variable number of positional arguments as input. How to check if the arguments that are passed are more than 5**
```python
>>> def spam(*args):
if len(args) > 5:
print('Length of arguments passed is greater than 5')
else:
print('Length Argument passed is less than 5')
>>> spam(1, 2, 3, 4, 5, 6, 7)
Length of arguments passed is greater than 5
>>>
>>> spam(1, 2)
Length Argument passed is less than 5
>>>
>>> spam()
Length Argument passed is less than 5
>>>
>>> spam(1, 2, 3, 4, 5)
Length Argument passed is less than 5
>>>
```
**33 Count the number of occurrences of "CRITICAL", "INFO" and "ERROR" lines in a log file.**
```python
# Assume Below is the contents of the log file
lines = """CRITICAL:Hello world
INFO: This is an info
ERROR: This is an error
CRITICAL: This is critical
CRITICAL:Hello world
INFO: This is an info
ERROR: This is an error
CRITICAL: This is critical
CRITICAL:Hello world
INFO: This is an info
ERROR: This is an error
CRITICAL: This is critical
CRITICAL:Hello world
INFO: This is an info
ERROR: This is an error
CRITICAL: This is critical"""
>>> from collections import defaultdict
>>> _errors = defaultdict(int)
>>> for line in lines.split('\n'): # Split the line based on newline character
# Split each line based on ":" to separate out error message part.
error_type, other = line.strip().split(':')
_errors[error_type] +=1
>>> _errors
defaultdict(<class 'int'>, {'CRITICAL': 8, 'INFO': 4, 'ERROR': 4})
>>> _errors['INFO']
4
>>> _errors['ERROR']
4
>>> _errors['CRITICAL']
8
>>>
```
**34 Write a function to reverse any iterable without using reverse function.**
```python
>>> a = [1, 2, 3, 4, 5]
>>> _reversed = []
>>> for i in range(len(a)-1, -1,-1):
_reversed.append(a[I])
>>> _reversed
[5, 4, 3, 2, 1]
>>>
```
**35 Write a function to print the output below.**
```python
# func("TRACXN", 0) # Should print RCN
# func("TRACXN", 1) # Should print TAX
>>> def func(string, flag):
if flag:
return string[0::2]
return string[1::2]
>>> func('TRACXN', 0)
'RCN'
>>> func('TRACXN', 1)
'TAX'
>>>
```
```python
def func(string, flag):
return string[::2] if flag else string[1::2]
```
**36 Sum all the numbers in the below string.**
```python
import re
s = "Sony12India567Pvt2ltd"
total = 0.00
>>> r = re.findall(r'[\d]', s)
>>> r
['1', '2', '5', '6', '7', '2']
>>> for item in r:
total += int(item)
>>> total
23.0
```
**37 Write a program to sum all the numbers in below string.**
```python
import re
s = "Sony12India567Pvt2ltd" # eg.12+567+2
>>> rr = re.findall(r'[\d]+', s)
>>> rr
['12', '567', '2']
>>> total = 0.00
>>> for item in rr:
total += int(item)
>>> total
581.0
```
**38 Print all the numbers in the below list**
```python
a = ['abc', '123', 'hello', '23']
>>> for item in a:
if item.isnumeric():
print(item)
123
23
```
**39 Program to print the number of occurrences of characters in a String without using inbuilt functions.**
```python
>>> s = 'helloworld'
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for c in s:
d[c] +=1
>>> print(d)
defaultdict(<class 'int'>, {'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1})
```
**40 Program to print only the repeated characters and count of the same.**
```python
>>> s = 'helloworld'
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for c in s:
d[c] +=1
>>> for key, value in d.items():
if value > 1:
print(key, value)
```
```python
d = {ch: s.count(ch) for ch in s if s.count(ch) > 1}
```
**41 Write a program to get alternate characters of a string in list format.**
```python
>>> s = 'hello world welcome to python'
>>> alternate_chrs = [ c for c in s[::2]]
>>> alternate_chrs
['h', 'l', 'o', 'w', 'r', 'd', 'w', 'l', 'o', 'e', 't', ' ', 'y', 'h', 'n']
```
**42 Write a program to get square of list of number's using lambda function .**
```python
>>> a = [1, 2, 3, 4, 5]
>>> squares = lambda number: number ** 2
>>> b = [ squares(item) for item in a]
>>> b
[1, 4, 9, 16, 25]
```
**43 Write a function that accepts two strings and returns True if the two strings are anagrams of each other.**
```python
def is_anagram(str1, str2):
if str1.upper() == str2.upper(): # Return False if both words are same
return False
s_str1 = sorted(str1.upper()) # Convert to upper case and sort
s_str2 = sorted(str2.upper())
if s_str1 == s_str2: # Return True if both the lists are same
return True
else:
return False
>>> is_anagram('ate', 'eat')
True
>>> is_anagram('racecar', 'racecar')
False
>>> is_anagram('file', 'life')
True
>>> is_anagram('hello', 'world')
False
>>> is_anagram("sinks", "skin")
False
>>> is_anagram("Listen", "silent")
True
```
**44 Write a program to iterate through list and build a new list, only if the items of the list has even number of characters.**
```python
>>> names = ['apple', 'yahoo', 'google', 'gmail', 'walmart', 'flipkart', 'facebook', 'amazon']
>>> [ name for name in names if len(name) % 2 == 0]
['google', 'flipkart', 'facebook', 'amazon']
```
**45 Write a program to iterate through list and build a new dictionary, only if the items of the list has even number of characters.**
```python
>>> names
['apple', 'yahoo', 'google', 'gmail', 'walmart', 'flipkart', 'facebook', 'amazon']
>>> { name: len(name) for name in names if len(name) % 2 == 0}
{'google': 6, 'flipkart': 8, 'facebook': 8, 'amazon': 6}
```
**46 Write a program which squares the numbers in a list using map object**
```python
# Squares of numbers using map
# map is used to map a function with a iterable
a = [1, 2, 3, 4, 5]
def squares(item):
return item ** 2
# Returns a map object, which happens to be an iterator.
m = map(squares, a)
# To get the squares of numbers, feed the map object to for loop
for item in m:
print(item)
# Mapping lambda function to map object
m = map(lambda item: item ** 2, a)
```
**47 Count number of lines in a file without loading the file to the memory**
```python
# Counting number of lines in a file without loading the file to the memory
with open('sample.txt') as f:
_count = 0
# Iterate over a file object and increment the _count
for line in f:
_count +=1
print(f'No of Lines: {_count}')
```
**48 Printing line and line no's**
```python
with open('sample.txt') as f:
for line_no, line in enumerate(f, start=1):
print(line_no, line)
```
**49 Write a Program to print the sum of entire list and sum of only internal list**
```python
l = [[1,2,3],[4,5,6],[7,8,9]]
# Add the contents of internal list. ([6, 15, 24])
sum_internal = [sum(item) for item in l]
# Add the contents of entire list. (45)
sum_iternal = [sum(item) for item in l]
sum_whole_list = sum(sum_internal)
```
```python
items = [[1,2,3],[4,5,6],[7,8,9]]
# Using List Comprehension
total = sum([each_item for each_internal_list in items for each_item in each_internal_list])
```
**50 Write a program to reverse the list as below**
```python
words = ["hi", "hello", "python"]
# o/p ['nohtyp', 'olleh', 'ih']
words = words[::-1]
words = [word[::-1] for word in words]
```
**51 Write a program to update the tuple**
```python
t1 = (1, 2, 3, 4)
t2 = (100, 200, 300)
# o/p (1, 2, 3, 4, 100, 200, 300)
t = t1 + t2
```
**52 Write a program to replace value present in nested dictionary.**
```python
d = {'a': 100, 'b': {'m': 'man', 'n': 'nose', 'o': 'ox', 'c': 'cat'}}
# Replace "nose" with "net"
for key, value in d.items():
if isinstance(value, dict):
d[key]['n'] = "net"
print(d)
```
**53 Write a program to count the number of white spaces in a file.**
```python
import re
white_spaces = 0
with open('data/sample.txt') as f:
for line in f:
match = re.findall(r'\s', line)
if match:
white_spaces += len(match)
print(white_spaces)
```
**54 Grouping anagrams.**
```python
>>> from collections import defaultdict
>>> words = ['eat', 'ate', 'tea', 'hello', 'silent', 'listen']
>>> d = defaultdict(list)
>>> for word in words:
s = ''.join(sorted(word))
d[s].append(word)
>>> print(d)
defaultdict(<class 'list'>, {'aet': ['eat', 'ate', 'tea'], 'ehllo': ['hello'], 'eilnst': ['silent', 'listen']})
>>> group = list(d.values())
>>> group
[['eat', 'ate', 'tea'], ['hello'], ['silent', 'listen']]
>>>
```
**55 What is the difference between defaultdict and normal dictionary.**
```python
"""
Defaultdict
-----------
1. When each key is encountered for the first time, it will not be there in the mapping.
2. So an entry is automatically created with default value (an empty list in case of defaultdict of list and zero in case of defaultdict int).
3. When keys are encountered again, the look-up proceeds normally as like a normal dictionary.
4. So, in defaultdict, creation of key, initialisation will happen simultaneously.
Normal Dictionary
------------------
1. In case of normal dictionary, if the key does not exist, "KeyError" is raised.
2. In order to work on the value, first the key needs to be created and initialised.
"""
```
**56 Explain property decorator in python.**
```python
#
```
**57 What is Mutable and Immutable datatypes.**
```python
"""
1. Mutable datatypes are objects whose value can be changed after creation. e.g. list, dict, set, user defined classes.
2. Immutable datatypes are objects whose value can not be changed after creating. e.g. int, float, bool, tuple, namedtuple
"""
```
**58 Explain get() method in dictionaries.**
```python
"""
point = {'a': 1, 'b': 2}
1. Values of dictionary can be accessed in two different ways. using square bracket syntax and the other one is using get() method.
2. When we try to access a key of a dictionary which does not exist using square bracket syntax (point['c']), "KeyError" exception is raised.
3. When we try to access a key of a dictionary which does not exist using get() method (point.get('c')), None is returned and no exception is raised.
4. We can pass a positional argument to get() method as custom message, so that get() method returns the custom message if the key does not exist.
e.g. profile.get('c', 'Sorry the key does not exist')
"""
```
**59 Write a list comprehension to get a list of even numbers from 1-50**
```python
evens = [ item for item in range(1, 51) if item % 2 == 0]
```
**60 Find the longest non-repeated substring in the below string**
```python
>>> s = "This is a Programming language and Programming is fun"
# make dictionary with word and its length pair for only those words which are not repeated.
>>> d = { word: len(word) for word in s.split() if s.count(word) == 1}
>>> d
{'This': 4, 'language': 8, 'and': 3, 'fun': 3}
# Sort the dictionary based on values and get the last item
>>> sorted(dd.items(), key=lambda item: item[-1])[-1]
('language', 8)
```
**61 Write a program to find the duplicate elements in the list without using inbuilt functions**
```python
names = ['apple', 'google', 'apple', 'yahoo', 'google']
unique_items = set(names)
for item in unique_items:
_count = 0
for name in names:
if item == name:
_count += 1
if _count > 1:
print(item)
```
**62 Write a program to count the number occurrences of each item in the list without using any inbuilt functions**
```python
names = ['apple', 'google', 'apple', 'yahoo', 'google', 'facebook', 'gmail', 'yahoo']
# Get the unique elements present in the list
unique_items = set(names)
# declare an empty dictionary
d = {}
for item in unique_items:
_count = 0
for name in names:
if item == name:
_count += 1
d[item] = _count
```
**63 Write a function to check if the number is Prime**
```python
>>> def is_prime(number):
# any is a builtin function that returns True if any one item in iterable evaluates to boolean True
return not any([number % 2 == 0 for i in range(2, number)])
>>> is_prime(10)
False
>>> is_prime(11)
True
>>> is_prime(13)
True
>>> is_prime(1)
True
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(5)
True
>>> is_prime(6)
False
>>>
```
**64 How to create a tuple using range function**
```python
>>> tuple(range(10))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
```
**65 Write a program to find the largest number in the list without using any inbuilt functions**
```python
>>> numbers = [10, 20, 30, 40, 50]