Basic Operations and Tricks in Python

python tricks

Read Data From Stdin

Input from stdin.

# python3
import sys

# data is a string
data = sys.stdin.read()
# now, data is a list of string
data = data.split()
# press ctrl+D after you complete the input

Input from stdin.

# python2
n_tables, n_queries = map(int, input().split())
counts = list(map(int, input().split()))

Read Data in Bash Shell

$ python3 main.py < tests/test.txt

Create a List of Numbers

n = 10
# initial all the values of an array to the same number
# but don't use this way in two dimensional array
# use numpy instead, for two dimensional array.
l1 = [1] * n
# [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

# initial an array as a sequence of numbers
l2 = list(range(n))
#  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Floor of a Number(下取整)

# what is floor
Floor(2.4) = 2
Floor(2.8) = 2
Floor(2) = 2
Floor(3) = 3

# floor in python
3 // 2 = 1
4 // 2 = 2

Swap the Value of Tow Variables

a = 1
b = 2

a, b = b, a
# result
# a = 2
# b = 1

Line Break(The Line of Code is Too Long)


a = 1 + 1
# same as
a = 1 + \
 1

a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, 
            blahblah6, blahblah7)

if a == True and \
   b == False

a = '1' + '2' + '3' + \
    '4' + '5'

a = ('1' + '2' + '3' +
    '4' + '5')

Quick Debug

# add one line
import pdb; pdb.set_trace()

# then the program will be stop at this line.
# you can use these commands: 
# n : next
# l : peek the code 
# s : step into a function
# p : print some variable
# b n : set a breakpoint
# display : monitor some variable when they are changed
# q : quit the debug mode