-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtips_and_tricks.txt
105 lines (77 loc) · 1.89 KB
/
tips_and_tricks.txt
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
Python Tips and Tricks:
=======================
1. In-Place Swapping Of Two Numbers.
Snippet:
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
2. Reversing a string in Python
Snippet:
a ="GeeksForGeeks"
print("Reverse is", a[::-1])
3. Create a single string from all the elements in list
Snippet:
a = ["Geeks", "For", "Geeks"]
print(" ".join(a))
4. Chaining Of Comparison Operators.
Snippet:
n = 10
result = 1 < n < 20
print(result)
result = 1 > n <= 9
print(result)
5. Print The File Path Of Imported Modules.
Snippet:
import os;
import socket;
print(os)
print(socket)
6. Use Of Enums In Python.
Snippet:
class MyName:
Geeks, For, Geeks = range(3)
print(MyName.Geeks)
print(MyName.For)
print(MyName.Geeks)
7. Return Multiple Values From Functions.
Snippet:
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
8. Find The Most Frequent Value In A List.
Snippet:
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
9. Check The Memory Usage Of An Object.
Snippet:
import sys
x = 1
print(sys.getsizeof(x))
10. Print string N times.
Snippet:
n = 2;
a ="GeeksforGeeks";
print(a * n);
11. Checking if two words are anagrams
Snippet:
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
print(is_anagram('geek', 'eegk'))
print(is_anagram('geek', 'peek'))
12. Finding the list of functions in python module
Snippet:
from inspect import getmembers, isfunction
import re
functions_list = [o[0] for o in getmembers(re) if isfunction(o[1])]
print(functions_list)
13. Most frequent element in a list.
Snippet:
a = [1, 2, 3, 1, 2, 3, 2, 2, 4, 5, 1]
print(max(set(a), key=a.count))
Using Counter from collections
cnt = Counter(a)
print(cnt.most_common(3))
14.