-
Notifications
You must be signed in to change notification settings - Fork 0
/
python competative import backup
1230 lines (902 loc) · 36.8 KB
/
python competative import backup
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
n=int(input())
n=raw_input()
[1,2,3,4]
a=map(int,raw_input().split())
a=[i for i in raw_input().split()]
d={name:'mohit'}
a[1]
d['name']
d.keys()
d.values()
t=(1,2,3,4)#tules are immutable means a new object will be created if you update any index value
t[2]=3 #it is hashable
x = chr(ord(ch) + 3) #ord will give the char ascii value and chr will provide the character associated with that ascii value
//replace all occurance of all
string=string.replace('a','$')
//finding most occuring character in string
import collections
s=raw_input()
max1=collections.Counter(s).most_common(1)[0][0]
//tip:use sort() to find min element instead of max()
//to copy an list use b=a[:]
//to check wheter a string is char or not "c".isalpha() True
//isupper() "a".islower lower() upper()
//'a'<'b' True #we can directly compare character
//"dssd".capitalize() Dssd #it will make first character capital
//s.find("1233","3") 2 str.find(sub,start,end)
//a={"mohit":1,"singh":2} a.values() a.keys()
//a.sort(reverse=True)
//a.replace(2,1,1) //last is no of time you want to replace string
//converting array into string " ".join(map(str,a))
str=u"ndkv"
>>> str.isnumeric()
//for _ in range(10):
print("h")
//
for i in range(len(a)):
for j in range(i+1,len(a)+1):
find_odd_even(a[i:j]) //susets
arr = [1 if int(i) % 2 == 1 else -1 for i in inp.split()] //get element as we want using if
(-1 if (0 == 0) else 1) //shortcut for if
//"mo dkjfjk mo".strip() output:" dkjfjk "
--------------
nt fact(int n) { return n > 1 ? n * fact(n –1) : 1; } ///factorial
--------------------
------taking infinite input
while True:
try:
line = input()
print solve(int(line))
except:
exit()
=============== no of binary string divisible by 2 after rotation
n=int(input())
for i in range(n):
m=int(input())
s=raw_input()
count=m-s.count("1")
print(count)
----------------------sorting string
m="gvmv"
>>> sorted(m)
['g', 'm', 'v', 'v']
"".join(sorted(m))//gmvv
---------------
a="mohit singh".split() //direct converting into string array
--------finding gcd in python 2.7
import fractions
>>> fractions.gcd(2,3)
1
---gcd of 3 no
>>> reduce(fractions.gcd,(12,2,3)) //reduce() in Python. The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along.This function is defined in “functools” module. Working : At first step, first two elements of sequence are picked and the result is obtained.
1
--------lcm of 3 no
abc = n//lcm(a,lcm(b,c))
-------------------dictionary getting key which is not present
dict.get(key[, default])
1
dict.get(key[, default])
If given key exists in dictionary then it returns its value,
If given key does not exists in dictionary then it returns the passed default value argument.
If given key does not exists in dictionary and Default value is also not passed in get() function, then get() function will return None.
-------
>>> dict(x=3,y=4)
{'y': 4, 'x': 3}
--------------
An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict() and OrderedDict() is that:
OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order, and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict.
# A Python program to demonstrate working of OrderedDict
from collections import OrderedDict
dictionari=OrderedDict()
----iterating over 3 list
for (a, b, c) in zip(num, color, value):
print a, b, c
---------------all combinations
import itertools
x=itertools.combinations("mohit//iterable any",r)
y=[i for i in x]
>>> y
[('m', 'f'), ('m', 'm'), ('m', 'g'), ('m', 'f'), ('m', 'g'), ('f', 'm'), ('f', 'g'), ('f', 'f'), ('f', 'g'), ('m', 'g'), ('m', 'f'), ('m', 'g'), ('g', 'f'), ('g', 'g'), ('f', 'g')]
//other iterable functions
itertools.cycle("itertools") //itertoolsitertools....
itertools.combinations_with_replacement()
itertools.permutations("cc")
product('ABCD', repeat=2) AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
-----------------joning two list
c=itertools.chain([1,2,3],[13,66])
>>> c
<itertools.chain object at 0x0000000005554828>
>>> c=list(c)
>>> c
[1, 2, 3, 13, 66]
--------------------return false if all elements are o or [] or false
any([0,0,0]) false
any([]) flase
any([23,2,0]) true
--------------------set
x=set([1,23,4])
x.add(2) //set is sorted
x.remove(2)
x.defference()
#!/usr/bin/env python
x = set(["Postcard", "Radio", "Telegram"])
y = set(["Radio","Television"])
print( x.difference(y) )
print( y.difference(x) )
x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issubset(y) )<b>
x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issuperset(y) )
x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.intersection(y) )
-----------last element
>> s=[7,799,78]
>>> s[-1]
78
----------comulative sum
for i in range(1,n):
s.append(i+s[-1])
------initialise dict with -1
mi = {k:-1 for k in arr}
conditions to apply binary search is
1.it should be monotonic
2.condition to move left right
-----------------maxsplit
>>> s = "this is my string"
>>> s.split(maxsplit=1)
['this', 'is my string']
-------lambda expression
>>> f = lambda x , y : x + y
>>> f(1,1)
2
-----------removing all occurance of an element
def remove_values_from_list(the_list, val):
return [value for value in the_list if value != val]
x = [1, 2, 3, 4, 2, 2, 3]
x = remove_values_from_list(x, 2)
print x
# [1, 3, 4, 3]
-------------sorting adict
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
for key in sorted(mydict.iterkeys()):
print "%s: %s" % (key, mydict[key])
---------------------iteRATION
>>> d = {'a': 1, 'b': 2}
>>> dki = d.iterkeys()
>>> dki.next()
'a'
>>> dki.next()
'b'
>>> dki.next()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
StopIteration
mydict.iterkeys().next()
'bob'
-------------sorting dictionary on the bases of values
>>>from operator import itemgetter
sorted(d.items(), key=itemgetter(1))
[('bob', 1), ('alan', 2), ('danny', 3), ('carl', 40)]
---------------------------------
bisect.bisect_left returns the leftmost place in the sorted list to insert the given element. bisect.bisect_right returns the rightmost place in the
sorted list to insert the given element.
An alternative question is when are they equivalent? By answering this, the answer to your question becomes clear.
They are equivalent when the the element to be inserted is not present in the list. Hence, they are not equivalent when the element to be inserted is
in the list.
import bisect
bisect.bisect_right(list2,i)
-----------------defining global sum
global accumulated_sum
-------------
map(str,a) //conver each element of array to another data type
//set are much faster to use when element are not dublicate in in operation because it uses hash table
>> langs = ["haskell", "clojure", "apl"]
>>> langs.extend(["scala", "F#"])
>>> print(langs)
['haskell', 'clojure', 'apl', 'scala', 'F#']
-----------
# loop over the companies and print both the index as youll as the name.
>>> for indx, name in enumerate(companies):
... print("Index is %s for company: %s" % (indx, name))
...
Index is 0 for company: hackerearth
Index is 1 for company: google
Index is 2 for company: facebook
----------------------
list.pop()
list.pop(1)
setA.add(8)
>>> print(setA)
{1, 2, 3, 4, 5, 6, 7, 8}
# pass a list with elements 11 and 12
>>> setA.update([11, 12])
>>> # check if setA is updated with the elements.
>>> print(setA)
{1, 2, 3, 4, 5, 6, 7, 8, 11, 12, (9, 10)}
>>> # removes element 7 from set
>>> setA.discard(7)
>>> print(setA)
{1, 2, 3, 4, 5, 6, 8, 11, 12, 14, 15, (9, 10), 16}
>>> # removes element 8 from set
>>> setA.remove(8)
>>> print(setA)
{1, 2, 3, 4, 5, 6, 11, 12, 14, 15, (9, 10), 16}
Both discard and remove take a single argument, the element to be deleted from the set.
If the value is not present, discard() does not do anything. Whereas, remove will raise a KeyError exception.
shallow_copy_of_setA = setA.copy()
>>> print(shallow_copy_of_setA)
{1, 2, 3, 4, 5, 6, 11, 12, 14, 15, (9, 10), 16}
Using assignment here instead of copy() will create a pointer to the already existing set.
Python set clear() Will remove all elements from set
>>> # clear the set shallow_copy_of_setA created before using copy() operation
>>> shallow_copy_of_setA.clear()
>>> print(shallow_copy_of_setA)
set()
Python set pop() Removes an arbitrary set element
>>> # popping an element from setA
>>> setA.pop()
1
>>> # pop raises a KeyError exception if the set is empty
>>> shallow_copy_of_setA.pop()
Traceback (most recent call last):
File "python", line 1, in <module>
KeyError: 'pop from an empty set'
Set Operations
Set Intersection using intersection(s) Returns element present in both sets; this can also be achieved using the ampersand operator (&).
>>> # create a new set setB
>>> setB= set()
>>> # update setB with values
>>> setB.update([1, 2, 3, 4, 5, 10, 15, 22])
>>> print(setB)
{1, 2, 3, 4, 5, 10, 15, 22}
>>> # print a new set with the values present in both setA and setB
>>> print(setA & setB)
{2, 3, 4, 5, 15}
>>> # above operation and using method name intersection shows same results
>>> setA.intersection(setB)
{2, 3, 4, 5, 15}
Set Difference using difference() Returns the difference of two sets; “-” operator can also be used to find the set difference.
>>> # print a new set with values present in setA but not in setB
>>> setA.difference(setB)
{6, 11, 12, 14, (9, 10), 16}
>>> # this returns empty set
>>> setB.difference(setA)
set()
setB is a proper subset of setA to setB - setA is empty set.
Other Set Operations
Python set isdisjoint() Returns true if intersection of sets is empty otherwise false
>>> # returns false as both have common elements
>>> setA.isdisjoint(setB)
False
>>> # create a new empty set setC
>>> setC = set()
>>> # update setC with values
>>> setC.update([100, 99])
>>> # returns true as setA and setC has no elements in common
>>> setA.disjoint(setC)
True
Python set difference_update() setA.difference_update(setB) removes all elements of y from setA; ‘-=’ can be used in place of the difference_update method.
>>> # update setA by removing elements present in setB from setA
>>> setA.difference_update(setB)
>>> # check the result set
>>> print(setA)
{6, 11, 12, 14, (9, 10), 16}
Similarly, setA.intersection_update(setB) removes elements from setA which are not present in the intersection set of setA and setB. ‘&=’ can be used in place of the intersection_update method.
Python set issubset() and issuperset() setA.issubset(setB) returns True if setA is subset of setB, False if not. “<=” operator can be used to test for issubset. To check for proper subset “<” is used.
>>> # check if setA is a subset of setB
>>> setA.issubset(setB)
False
>>> # check if set B is a subset of setA
>>> setB.issubset(setA)
False
Let’s make setB a subset of setA by removing values 1, 10, and 22.
>>> # remove few elements to make setB a subset of setA
>>> setB.remove(1)
>>> setB.remove(10)
>>> setB.remove(22)
>>> # check the values present in setB now
>>> print(setB)
{2, 3, 4, 5, 15}
>>> #issubset now returns true
>>> setB.issubset(setA)
True
>>> setB < setA
True
>>> #setA now becomes a superset of setB
>>> setA.issuperset(setB)
True
------------------2d array
for _ in xrange(3):
a.append(map(int, raw_input().rstrip().split()))
-------------------------no of sub array
for ex A[]={1,2,3} the subarrays are:- {1},{2},{3},{1,2},{2,3},{1,2,3}
(3*(3+1))/2 i.e, 6 non-empty subarrays
--------------to check array is sorted or not
all(l[i] <= l[i+1] for i in xrange(len(l)-1))
------eucled method of gcd
def gcd(x, y):
while(y):
x, y = y, x % y
return x
print gcd(12,25)
---------extend the dict
a.update({3:4})
----------------2d array
a = [[0] * m] * n
-----all accourance of same degit
for i,j in enumerate(mymatrix):
for k,l in enumerate(j):
if l==1:
print i,k
-------------------finding noof perfect squares in between no a<b
count=(int)(math.floor(math.sqrt(b))- math.ceil(math.sqrt(a)))+1
This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).
>>> print 'ab123'.isalnum()
True
>>> print 'ab123#'.isalnum()
False
This method checks if all the characters of a string are alphabetical (a-z and A-Z).
>>> print 'abcD'.isalpha()
True
>>> print 'abcd1'.isalpha()
False
This method checks if all the characters of a string are digits (0-9).
>>> print '1234'.isdigit()
True
>>> print '123edsd'.isdigit()
False
str.islower()
This method checks if all the characters of a string are lowercase characters (a-z).
>>> print 'abcd123#'.islower()
True
>>> print 'Abcd123#'.islower()
False
str.isupper()
This method checks if all the characters of a string are uppercase characters (A-Z).
>>> print 'ABCD123#'.isupper()
True
>>> print 'Abcd123#'.isupper()
False
-----------taking name along with array as input
line = raw_input().split()
name, scores = line[0], line[1:]
---- aligning
.ljust(width)
This method returns a left aligned string of length width.
>>> width = 20
>>> print 'HackerRank'.ljust(width,'-')
HackerRank----------
.center(width)
This method returns a centered string of length width.
>>> width = 20
>>> print 'HackerRank'.center(width,'-')
-----HackerRank-----
.rjust(width)
This method returns a right aligned string of length width.
>>> width = 20
>>> print 'HackerRank'.rjust(width,'-')
----------HackerRank
alpha = string.ascii_lowercase
>>> alpha
'abcdefghijklmnopqrstuvwxyz'
------------lambda is similar to function
g=lambda x,y:x+y
>>> g(2,3)
5
>>>
---creatiing a list of n no
a=list(map(lambda x:x,range(0,10)))
------multipliying two list
g=list(map(lambda x,y:x*y,[1,2,3,4,5],[1,2,3,4,5]))
a=list(filter(lambda x:x>0,[1,2,1,-3,4,5,-6,7]))
>>> a
[1, 2, 1, 4, 5, 7]
a=reduce(lambda x,y:max(x,y),[1,2,3,4,2,7,3,4,7])
>>> a
7
a=reduce(lambda x,y:x*y,[1,2,3,4,5,7])
>>> a
840
---new about itertool permutations
itertools.permutations(iterable[, r])
This tool returns successive length permutations of elements in an iterable.
If is not specified or is None, then defaults to the length of the iterable, and all possible full length permutations are generated.
Permutations are printed in a lexicographic sorted order. So, if the input iterable is sorted, the permutation tuples will be produced in a sorted order.
----------
itertools.combinations_with_replacement(iterable, r)
This tool returns length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order
----------------cartition product --very useful if u want to make combination within 3 or more tuples
itertools.product()
This tool computes the cartesian product of input iterables.
It is equivalent to nested for-loops.
For example, product(A, B) returns the same as ((x,y) for x in A for y in B).
Sample Code
>>> from itertools import product
>>>
>>> print list(product([1,2,3],repeat = 2))
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
>>>
>>> print list(product([1,2,3],[3,4]))
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
>>>
>>> A = [[1,2,3],[3,4,5]]
>>> print list(product(*A))
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5)]
>>>
>>> B = [[1,2,3],[3,4,5],[7,8]]
>>> print list(product(*B))
[(1, 3, 7), (1, 3, 8), (1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 3, 7), (2, 3, 8), (2, 4, 7) etc
-------------groupby
In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools . To read more about this function, Check this out .
You are given a string . Suppose a character '' occurs consecutively times in the string. Replace these consecutive occurrences of the character '' with in the string.
For a better understanding of the problem, check the explanation.
Input Format
A single line of input consisting of the string .
Output Format
A single line of output consisting of the modified string.
Constraints
All the characters of denote integers between and .
Sample Input
1222311
Sample Output
(1, 1) (3, 2) (1, 3) (2, 1)
----------------------------index and element
>> list(enumerate("rank"))
[(0, 'r'), (1, 'a'), (2, 'n'), (3, 'k')]
----set union operator
>>> s = set("Hacker")
>>> print s.union("Rank")
set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n'])
>>> print s.union(set(['R', 'a', 'n', 'k']))
set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n'])
>>> print s.union(['R', 'a', 'n', 'k'])
set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n'])
>>> print s.union(enumerate(['R', 'a', 'n', 'k']))
set(['a', 'c', 'r', 'e', (1, 'a'), (2, 'n'), 'H', 'k', (3, 'k'), (0, 'R')])
>>> print s.union({"Rank":1})
set(['a', 'c', 'r', 'e', 'H', 'k', 'Rank'])
>>> s | set("Rank")
set(['a', 'R', 'c', 'r', 'e', 'H', 'k', 'n'])
---
.intersection()
The .intersection() operator returns the intersection of a set and the set of elements in an iterable.
Sometimes, the & operator is used in place of the .intersection() operator, but it only operates on the set of elements in set.
The set is immutable to the .intersection() operation (or & operation).
------------sorting ordered dict
d=sorted(d.items(), key=lambda x: x[1])
print divmod(177,10)
(17, 7)
-----------------collections.Counter()
collections.Counter()
A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values.
Sample Code
>>> from collections import Counter
>>>
>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
>>> print Counter(myList)
Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
>>>
>>> print Counter(myList).items()
[(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
>>>
>>> print Counter(myList).keys()
[1, 2, 3, 4, 5]
>>>
>>> print Counter(myList).values()
[3, 4, 4, 2, 1]
----pow modified
It's also possible to calculate .
>>> pow(a,b,m)
---exception
#Code
try:
print 1/0
except ZeroDivisionError as e:
print "Error Code:",e
---------------set-------
>> myset.add((5, 4))
>> myset
{'a', 'c', 'b', (5, 4)}
---
>> myset.update([1, 2, 3, 4]) # update() only works for iterable objects
>> myset
{'a', 1, 'c', 'b', 4, 2, (5, 4), 3}
>> myset.update({1, 7, 8})
>> myset
{'a', 1, 'c', 'b', 4, 7, 8, 2, (5, 4), 3}
>> myset.update({1, 6}, [5, 13])
>> myset
{'a', 1, 'c', 'b', 4, 5, 6, 7, 8, 2, (5, 4), 13, 3}
----
Both the discard() and remove() functions take a single value as an argument and removes that value from the set. If that value is not present, discard() does nothing, but remove() will raise a KeyError exception.
>> myset.discard(10)
>> myset
{'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 13, 11, 3}
>> myset.remove(13)
>> myset
{'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 11, 3}
-----
COMMON SET OPERATIONS Using union(), intersection() and difference() functions.
>> a = {2, 4, 5, 9}
>> b = {2, 4, 11, 12}
>> a.union(b) # Values which exist in a or b
{2, 4, 5, 9, 11, 12}
>> a.intersection(b) # Values which exist in a and b
{2, 4}
>> a.difference(b) # Values which exist in a but not in b
{9, 5}
----
The union() and intersection() functions are symmetric methods:
>> a.union(b) == b.union(a)
True
>> a.intersection(b) == b.intersection(a)
True
>> a.difference(b) == b.difference(a)
False
=-------
.symmetric_difference()
The .symmetric_difference() operator returns a set with all the elements that are in the set and the iterable but not both.
Sometimes, a ^ operator is used in place of the .symmetric_difference() tool, but it only operates on the set of elements in set.
The set is immutable to the .symmetric_difference() operation (or ^ operation).
>>> s = set("Hacker")
>>> print s.symmetric_difference("Rank")
set(['c', 'e', 'H', 'n', 'R', 'r'])
>>> print s.symmetric_difference(set(['R', 'a', 'n', 'k']))
set(['c', 'e', 'H', 'n', 'R', 'r'])
>>> print s.symmetric_difference(['R', 'a', 'n', 'k'])
set(['c', 'e', 'H', 'n', 'R', 'r'])
>>> print s.symmetric_difference(enumerate(['R', 'a', 'n', 'k']))
set(['a', 'c', 'e', 'H', (0, 'R'), 'r', (2, 'n'), 'k', (1, 'a'), (3, 'k')])
>>> print s.symmetric_difference({"Rank":1})
set(['a', 'c', 'e', 'H', 'k', 'Rank', 'r'])
>>> s ^ set("Rank")
set(['c', 'e', 'H', 'n', 'R', 'r'])
------------------default dict
rom collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
print i
This prints:
('python', ['awesome', 'language'])
('something-else', ['not relevant'])
------------
.update() or |=
Update the set by adding elements from an iterable/another set.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.update(R)
>>> print H
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
.intersection_update() or &=
Update the set by keeping only the elements found in it and an iterable/another set.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.intersection_update(R)
>>> print H
set(['a', 'k'])
.difference_update() or -=
Update the set by removing elements found in an iterable/another set.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.difference_update(R)
>>> print H
set(['c', 'e', 'H', 'r'])
.symmetric_difference_update() or ^=
Update the set by only keeping the elements found in either set, but not in both.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.symmetric_difference_update(R)
>>> print H
set(['c', 'e', 'H', 'n', 'r', 'R'])
--------------*argv
*args
The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list.
The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.
What *args allows you to do is take in more arguments than the number of formal arguments that you previously defined. With *args, any number of extra arguments can be tacked on to your current formal parameters (including zero extra arguments).
For example : we want to make a multiply function that takes any number of arguments and able to multiply them all together. It can be done using *args.
Using the *, the variable that we associate with the * becomes an iterable meaning you can do things like iterate over it, run some higher order functions such as map and filter, etc.
Example for usage of *arg:
filter_none
edit
play_arrow
brightness_4
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print (arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Hello
Welcome
to
GeeksforGeeks
------
The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is because the double star allows us to pass through keyword arguments (and any number of them).
A keyword argument is where you provide a name to the variable as you pass it into the function.
One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out.
Example for usage of **kwargs:
filter_none
edit
play_arrow
brightness_4
# Python program to illustrate
# *kargs for variable number of keyword arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
myFun(first ='Geeks', mid ='for', last='Geeks')
----------
class Person:
age = 23
name = "Adam"
person = Person()
# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))
# when no default value is provided
print('The sex is:', getattr(person, 'sex'))
------------geattr()
//if u have function name given and argument also then u can use getattr like this
getattr(a,"intersection")(set(b)) >> a.intersection(b)
getattr(a,q)(b)
-------------regex
Regular expressions are extremely useful in extracting information from text such as: code, log files, spreadsheets, documents, etc.
We can match a specific string X in a test string S by making our regex pattern X
. This is one of the simplest patterns.
Regex_Pattern = r'hackerrank' # Do not delete 'r'.
import re
Test_String = raw_input()
match = re.findall(Regex_Pattern, Test_String)
print "Number of matches :", len(match)
import re
text = "Python for beginner is a very cool website"
pattern = re.sub("cool", "good", text)
print text2
Subn. Usually re.sub() is sufficient. But another option exists. The re.subn method has an extra feature. It returns a tuple with a count of substitutions in the second element.
Tuple
Tip:
If you must know the number of substitutions made by re.sub, using re.subn is an ideal choice.
However:
If your program has no use of this information, using re.sub is probably best. It is simpler and more commonly used.
---- .
The dot (.) matches anything (except for a newline).
. incateany character
> import re
>>> pattern=r'mohit'
>>> text="hello mohit how are u mohit"
>>> res=re.findall(pattern,text);
>>> print res
['mohit', 'mohit']
>>> print len(res)
2
>>> pattern=r'mo.it'
>>> res=re.findall(pattern,text);
>>> res
['mohit', 'mohit']
Note: If you want to match (.) in the test string, you need to escape the dot by using a slash \..
In Java, use \\. instead of \..
----
str(res)
"['mohit', 'mohit']"
>>> str(res).upper()
"['MOHIT', 'MOHIT']"
to limit the no of character we use ^ in the begining and $ at the end
-mathes any degit- /d
-mathes any non degit - /D
It's easier to group digits like \d{2} rather than \d\d
\s matches any whitespace character [ \r\n\t\f ].
word characters \w 0-9 a-z A-Z (_)underscore
\W any non word charcters
The character class [ ] matches only one out of several characters placed inside the square brackets.
The negated character class [^] matches any character that is not in the square brackets.
Fourth character should not be a whitespace character ( \r, \n, \t, \f or <space> ).
--------------------------
Matching Character Ranges
__________________________
In the context of a regular expression (RegEx), a character class is a set of characters enclosed within
square brackets that allows you to match one character in the set.
A hyphen (-) inside a character class specifies a range of characters where the left and right
operands are the respective lower and upper bounds of the range. For example:
In addition, if you use a caret (^) as the first character inside a character class,
it will match anything that is not in that range. For example,[0-9] matches any character
that is not a digit in the inclusive range from 0 to 9. It's important to note that,
when used ^ outside of (immediately preceding) a character or character class,
the caret matches the first character in the string against that character or set of characters.
(str(bool(re.search(Regex_Pattern, raw_input()))).lower())
-------------------------------
Matching {x} Repetitions
--------------------------------
The tool {x} will match exactly x repetitions of character/character class/groups.
The {x,y} tool will match between x and y (both inclusive) repetitions of character/character class/group.
w{3,5} : It will match the character w , 3,4 or 5 times.
[xyz]{5,} : It will match the character x, y or z 5 or more times.
\d{1, 4} : It will match any digits , 1,2 , 3or 4 times.
The * tool will match zero or more repetitions of character/character class/group.
w* : It will match the character w 0 or more times.
[xyz]* : It will match the characters x, y or z 0 or more times.
\d* : It will match any digit 0 or more times.
The + tool will match one or more repetitions of character/character class/group.
\b assert position at a word boundary.
Three different positions qualify for word boundaries :
► Before the first character in the string, if the first character is a word character.
► Between two characters in the string, where one is a word character and the other is not a word character.
► After the last character in the string, if the last character is a word character.
Parenthesis ( ) around a regular expression can group that part of regex together. This allows us to apply different quantifiers to that group.
These parenthesis also create a numbered capturing. It stores the part of string matched by the part of regex inside parentheses.
These numbered capturing can be used for backreferences. ( We shall learn about it later )