0%

Start to Use Python to Solve Algorithm Problems

Basic functions

For

1
2
3
a = ["hello", 1, 0.5]
for i, v in enumerate(a):
print(i, v)

Output:

0 hello
1 1
2 0.5


While

1
2
3
4
5
6
while True:
try:
n = int(input())
...
except EOFError:
break

Operations

1
2
3
4
5
x = 5 #101(Base2)
y = 3 #011(Base2)
print(x + y, x - y, x * y, x / y)
print(x ** y, x // y, x % y)
print(x & y, x | y, x ^ y, x << y, x >> y)

Output:

8 2 15 1.6666666666666667
125 1 2
1 7 6 40 0


Min Max

1
2
3
4
a, b, c = 1, 3, 2
mn = min(a, b, c)
mx = max(a, b, c)
print(mn, mx)

Output

1 3


Numerical Base

1
2
3
4
5
6
7
x = int("144", 8)
a, b, c, d = bin(x), oct(x), int(x), hex(x)
print(a, b, c, d)
print(a[2:])
print(b[2:])
print(c)
print(d[2:])

Output:

0b1100100 0o144 100 0x64
1100100
144
100
64

Basic Types and Useful Types

String

Escape Character

1
2
3
4
5
6
7
8
\'      Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab

s = '\# \' \\ """'
print(s)

Output:

# ' \ """


String Cut

1
2
3
v = 12345
s = str(v)
print(s[1:], s[2:3], s[:-1], s[-2], s[::2], s[::-1])

Output:

2345 3 1234 4 135 54321


String Internal Methods

link

List

1
2
3
4
5
6
7
l = ["hello", 1, [2, 3]]
la = [2, 1, 0, -1, -2]
lb = ["apple", "banana", "orange"]
la.sort()
lb.sort(reverse=True)
print(la)
print(lb)

Output:

[-2, -1, 0, 1, 2]
['orange', 'banana', 'apple']


queue.PriorityQueue

1
2
3
4
5
6
7
8
9
10
from queue import PriorityQueue
q = PriorityQueue()

q.put((2, "eat"))
q.put((1, "get up"))
q.put((3, "sleep"))

while not q.empty():
next_item = q.get()
print(next_item)

Array (Numpy)

1
2
3
4
5
import numpy as np
n, m = 2, 3
a = np.zeros((n, m), dtype=int)
print(type(a))
print(a)

Output:

<class 'numpy.ndarray'>
[ [0 0 0]
&emsp;[0 0 0] ]

Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class A:
def __init__(self, cnt, chr):
self.cnt = cnt
self.chr = chr
def __lt__(self, other):
if self.cnt != other.cnt:
return self.cnt > other.cnt
else:
return self.chr < other.chr
def __str__(self):
return str(self.cnt) + " " + str(self.chr)

a = []
a.append(A(1, "apple"))
a.append(A(2, "banana"))
a.sort()
for i in range(len(a)):
print(a[i])

Output:

2 banana
1 apple


Input

String

1
2
3
s = input()
print(type(s))
sa, sb = input().split(maxsplit=1)

Output:

<class 'str'>


List

1
2
3
4
5
6
l = []
print(type(l))
l = list(map(int, input().split()))
l2 = [[] for i in range(10000)] # = cpp l2 = list[10000]
lm = [[[0 for i in range(3)] for j in range(4)] for k in range(5)]
print(lm[4][3][2])

Output:

<class 'list'>
0


Dict

1
2
d = {}
print(type(d))

Output:

<class 'dict'>


Int

1
2
n, m = map(int, input().split())
print(type(n))

Output:

<class 'int'>


Output

One line

1
2
3
4
5
6
7
n = 5
a = []
for i in range(n):
a.append(i*i)
for i in range(n):
print(a[i],end=" " if i != n - 1 else "")
print()

Output:

0 1 4 9 16