<jupyter_start><jupyter_text>Magic Commands<jupyter_code>%lsmagic
pwd
!pwd<jupyter_output>/Users/hadoop/eda/notebook/python<jupyter_text>The following are just a collection of some useful shortcuts and tools I've found in Python over the years. Hopefully you find them helpful.   Swapping variables<jupyter_code>x = 1
y = 2
x, y
x, y = y, x
x, y<jupyter_output><empty_output><jupyter_text>If statement within a line<jupyter_code>print("Hello") if True else "World"
print("Hello") if False else "World"<jupyter_output><empty_output><jupyter_text>Join<jupyter_code>List1 = ['a', 'b']
List2 = ['c', 'd']
List3 = List1 + List2
List3
print(List1, List2, 'Hello', 8888)<jupyter_output>['a', 'b'] ['c', 'd'] Hello 8888<jupyter_text>Compute skill<jupyter_code>5.0/2
5.0//2
2 ** 5<jupyter_output><empty_output><jupyter_text>Float number divid<jupyter_code>0.3/0.1
0.3//0.1<jupyter_output><empty_output><jupyter_text>Number comparing<jupyter_code>x = 2
3 > x >1
1 < x > 0<jupyter_output><empty_output><jupyter_text>Iterating two list once<jupyter_code>for tmp1, tmp2 in zip(List1, List2):
    print(tmp1, tmp2)<jupyter_output>a c
b d<jupyter_text>List iteration with index<jupyter_code>for index, element in enumerate(List3):
    print(index, element)<jupyter_output>0 a
1 b
2 c
3 d<jupyter_text>List comprehension<jupyter_code>numbers = [1, 2, 3, 4, 5]
even = [number for number in numbers if number%2 == 0]
even<jupyter_output><empty_output><jupyter_text>Dictionary comprehension<jupyter_code>Chars = ['a', 'b', 'c', 'd', 'e']
{key: value for value, key in enumerate(Chars)}
Dict = {value: key for key, value in enumerate(Chars)}
Dict<jupyter_output><empty_output><jupyter_text>Initializing list<jupyter_code>items = [0] * 3
items<jupyter_output><empty_output><jupyter_text>Get the element from the dictionary<jupyter_code>Dict.get('a', False)
Dict.get('f', False)<jupyter_output><empty_output><jupyter_text>List slice<jupyter_code>List3[:]
List3[::]
## previous 3
List3[:3]
## Middle 4
List3[1:5]
## Last 3
List3[-3:]
## Even No.
List3[1::2]
## Odd No.
List3[::2]<jupyter_output><empty_output><jupyter_text>FizzBuzz<jupyter_code>for x in range(101):
    print("fizz"[x%3*4::] + "buzz"[x%5*4::] or x)<jupyter_output>fizzbuzz
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzz
fizz
22
23
fizz
buzz
26
fizz
28
29
fizzbuzz
31
32
fizz
34
buzz
fizz
37
38
fizz
buzz
41
fizz
43
44
fizzbuzz
46
47
fizz
49
buzz
fizz
52
53
fizz
buzz
56
fizz
58
59
fizzbuzz
61
62
fizz
64
buzz
fizz
67
68
fizz
buzz
71
fizz
73
74
fizzbuzz
76
77
fizz
79
buzz
fizz
82
83
fizz
buzz
86
fizz
88
89
fizzbuzz
91
92
fizz
94
buzz
fizz
97
98
fizz
buzz<jupyter_text>collections<jupyter_code>from collections import Counter
print(Counter('Hello'))<jupyter_output>Counter({'l': 2, 'o': 1, 'e': 1, 'H': 1})<jupyter_text>itertools<jupyter_code>from itertools import combinations
for game in combinations(List3, 2):
    print(game)
for game in combinations(List3, 3):
    print(game)
for game in combinations(List3, 4):
    print(game)
for game in combinations(List3, 5):
    print(game)<jupyter_output><empty_output><jupyter_text>True & False<jupyter_code>## In Python2, True and False are global variables.
False = True
print("Hello") if False else "World"<jupyter_output><empty_output><jupyter_text>Unboxing<jupyter_code>a, b, c = 1, 2, 3
a, b, c
a, b, c = [1, 2, 3]
a, b, c
# a, (b, c), d = [1, 2, 3, 4]
a, (b, c), d = [1, (2, 3), 4]
a, b, c, d
a, *b, c = [1, 2, 3, 4]
a, b, c
? slice
a = [0, 1, 2, 3, 4, 5]
hello = slice(-3, 7, 1)
hello
a[hello]<jupyter_output><empty_output><jupyter_text>Formatting Output Log<jupyter_code>print("Success".center(20, "="))
print("Fail".center(20, "="))<jupyter_output>========Fail========<jupyter_text>Raw<jupyter_code>print("\\abc")
print(r"\\abc")<jupyter_output>\\abc<jupyter_text>Zip and Unzip in List and Iterator<jupyter_code>a = [1, 2, 3]
b = ['a', 'b', 'c']
# Python 2
print a
print b
z = zip(a, b)
print z
print zip(*z)
# Python 3
print(a)
print(b)
z = zip(a, b)
print(list(z))
print(list(zip(*z)))
iz = iter(z)
a = [1, 2, 3, 4, 5, 6]
print(list(zip(*([iter(a)] * 2))))
group_adjacent = lambda a, k : zip(*([iter(a)] * k))
print(list(group_adjacent(a, 3)))
print(list(group_adjacent(a,2)))
print(list(group_adjacent(a,1)))
print(a[::2], a[1::2])
print(list(zip(a[::2], a[1::2])))
print(list(zip(a[::3], a[1::3], a[2::3])))<jupyter_output>[(1, 2, 3), (4, 5, 6)]<jupyter_text>Values Window<jupyter_code>def n_grams(a, n):
    z = [iter(a[i:]) for i in range(n)]
    return zip(*z)
a = [1, 2, 3, 4, 5, 6]
list(n_grams(a, 3))
list(n_grams(a, 2))
list(n_grams(a, 4))<jupyter_output><empty_output><jupyter_text>Reverse Dictionary with Zip<jupyter_code>m = {'a' : 1, 'b' : 2, 'c' : 3}
m.items()
m.values()
m.keys()
list(zip(m.values(), m.keys()))
dict(zip(m.values(), m.keys()))<jupyter_output><empty_output><jupyter_text>Generator Expression<jupyter_code>g = (x ** 2 for x in range(10))
g
next(g)
sum(x for x in range(10))<jupyter_output><empty_output><jupyter_text>Dictionary Comprehension<jupyter_code>m = {x : x ** 2 for x in range(10)}
m
n = {v : k for k, v in m.items()}
n<jupyter_output><empty_output><jupyter_text>Named Touple<jupyter_code>import collections
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(x = 1.0, y = 1.0)
p.x
q = Point(x = 1.0, y = 2.0)
q.y
p + q<jupyter_output><empty_output><jupyter_text>Inherited Named Touple<jupyter_code>class Point(collections.namedtuple('PointBase', ['x', 'y'])):
    __slot__ = ()
    def __add__(self, other):
        return Point(x = self.x + other.x, y = self.x + other.y)
p = Point(x = 1.0, y = 2.0)
p
q = Point(x = 2.0, y = 3.0)
q
p + q<jupyter_output><empty_output><jupyter_text>Set<jupyter_code>a = {1, 2, 3, 3}
b = {2, 3, 4, 4}
a | b
a & b
a - b
b - a
a ^ b
(a ^ b) == ((a -b) | (b -a))<jupyter_output><empty_output><jupyter_text>Multiple Set<jupyter_code>a = collections.Counter([1, 2, 2])
a
b = collections.Counter([2, 2, 3])
b
a | b
a & b
a + b
a - b
b - a<jupyter_output><empty_output><jupyter_text>The Most Frequent Element<jupyter_code>a = collections.Counter([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 5, 6, 7])
a
a.most_common(1)
a.most_common(3)<jupyter_output><empty_output><jupyter_text>Deque<jupyter_code>q = collections.deque()
q
q.append(2)
q
q.appendleft(3)
q.extend([3, 4])
q
q.extendleft([4, 5])
q
q.pop()
q
q.popleft()
q.rotate(3)
q
q.rotate(-3)
q
import json
__
import itertools
for p in itertools.product([1, 2, 3], [4, 5]):
    print(p)<jupyter_output>(1, 4)
(1, 5)
(2, 4)
(2, 5)
(3, 4)
(3, 5)
{'fraction_non_alphanumeric': 0.1763437548128754, 'fraction_numerical': 0.054058216540890186, 'mean_word_length': 5.857444561774023, 'pattern_counts': {'":': 0, '<': 120, '<?xml version=': 0, '>': 122, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '32', 'dir': 'jupyter-structured-clean-dedup', 'id': '255941', 'license': 'MIT', 'n_tokens_mistral': 3151, 'n_tokens_neox': 2946, 'n_words': 706, 'path': 'python/Python_Code-python3.ipynb', 'repo_name': 'hepingtao/eda', 'size': '6493'}