Python for competitive programming


In [1]:
# This is a comment in Python

print("Hello World!")


Hello World!

Numbers


In [2]:
2 + 2


Out[2]:
4

In [3]:
x = 5

In [4]:
x / 2


Out[4]:
2.5

In [5]:
x // 2


Out[5]:
2

In [6]:
2 ** 10


Out[6]:
1024

In [7]:
2 ** 10000


Out[7]:
19950631168807583848837421626835850838234968318861924548520089498529438830221946631919961684036194597899331129423209124271556491349413781117593785932096323957855730046793794526765246551266059895520550086918193311542508608460618104685509074866089624888090489894838009253941633257850621568309473902556912388065225096643874441046759871626985453222868538161694315775629640762836880760732228535091641476183956381458969463899410840960536267821064621427333394036525565649530603142680234969400335934316651459297773279665775606172582031407994198179607378245683762280037302885487251900834464581454650557929601414833921615734588139257095379769119277800826957735674444123062018757836325502728323789270710373802866393031428133241401624195671690574061419654342324638801248856147305207431992259611796250130992860241708340807605932320161268492288496255841312844061536738951487114256315111089745514203313820202931640957596464756010405845841566072044962867016515061920631004186422275908670900574606417856951911456055068251250406007519842261898059237118054444788072906395242548339221982707404473162376760846613033778706039803413197133493654622700563169937455508241780972810983291314403571877524768509857276937926433221599399876886660808368837838027643282775172273657572744784112294389733810861607423253291974813120197604178281965697475898164531258434135959862784130128185406283476649088690521047580882615823961985770122407044330583075869039319604603404973156583208672105913300903752823415539745394397715257455290510212310947321610753474825740775273986348298498340756937955646638621874569499279016572103701364433135817214311791398222983845847334440270964182851005072927748364550578634501100852987812389473928699540834346158807043959118985815145779177143619698728131459483783202081474982171858011389071228250905826817436220577475921417653715687725614904582904992461028630081535583308130101987675856234343538955409175623400844887526162643568648833519463720377293240094456246923254350400678027273837755376406726898636241037491410966718557050759098100246789880178271925953381282421954028302759408448955014676668389697996886241636313376393903373455801407636741877711055384225739499110186468219696581651485130494222369947714763069155468217682876200362777257723781365331611196811280792669481887201298643660768551639860534602297871557517947385246369446923087894265948217008051120322365496288169035739121368338393591756418733850510970271613915439590991598154654417336311656936031122249937969999226781732358023111862644575299135758175008199839236284615249881088960232244362173771618086357015468484058622329792853875623486556440536962622018963571028812361567512543338303270029097668650568557157505516727518899194129711337690149916181315171544007728650573189557450920330185304847113818315407324053319038462084036421763703911550639789000742853672196280903477974533320468368795868580237952218629120080742819551317948157624448298518461509704888027274721574688131594750409732115080498190455803416826949787141316063210686391511681774304792596709376

In [8]:
len(str(2 ** 100000))


Out[8]:
30103

Strings


In [9]:
s = "python"

In [10]:
s + s


Out[10]:
'pythonpython'

In [11]:
s * 3


Out[11]:
'pythonpythonpython'

In [12]:
s = input() # type infoclock


infoclock

In [13]:
s[0]


Out[13]:
'i'

In [14]:
s[1]


Out[14]:
'n'

In [15]:
s[-1]


Out[15]:
'k'

In [16]:
s[-2]


Out[16]:
'c'

In [17]:
s[1:]


Out[17]:
'nfoclock'

In [18]:
s[:1]


Out[18]:
'i'

In [19]:
s[2:]


Out[19]:
'foclock'

In [20]:
s[:2]


Out[20]:
'in'

In [21]:
s[:-1]


Out[21]:
'infocloc'

In [22]:
s[:-2]


Out[22]:
'infoclo'

In [23]:
s[2 : -2]


Out[23]:
'foclo'

In [24]:
s[2 : -2 : 2]


Out[24]:
'fco'

Lists


In [25]:
l = [2, 3, 5, 7, 11]

In [26]:
l[0] * l[-1]


Out[26]:
22

In [27]:
l.append(13)
print(l)


[2, 3, 5, 7, 11, 13]

In [28]:
l2 = [2, 4, 6, 8]
l + l2


Out[28]:
[2, 3, 5, 7, 11, 13, 2, 4, 6, 8]

In [29]:
v = [0] * 10
print(v)


[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

In [30]:
v = [1] * 10
v[0] = 33
print(v)


[33, 1, 1, 1, 1, 1, 1, 1, 1, 1]

In [31]:
# s[0] = 'x' # this will fail

In [32]:
s = "python is awesome"
v = s.split()
print(v)


['python', 'is', 'awesome']

In [33]:
v.append(100)
print(v)


['python', 'is', 'awesome', 100]

Dictionaries


In [34]:
d = {}
d['a'] = 'alex'
d['f'] = 'fmi'
d[3] = 42
print(d)


{3: 42, 'f': 'fmi', 'a': 'alex'}

In [35]:
for key in d:
    print ('Key: {0}; Value: {1}'.format(key, d[key]))


Key: 3; Value: 42
Key: f; Value: fmi
Key: a; Value: alex

In [36]:
d[3] += 1
print(d[3])


43

Conditionals and loops


In [37]:
for x in range(5):
    print("I want " + str(x + 1) + " apples.")


I want 1 apples.
I want 2 apples.
I want 3 apples.
I want 4 apples.
I want 5 apples.

In [38]:
this_is_true = True
if this_is_true:
    print("the answer to life, the universe and everything is 42")
else:
    whatever # change this_is_true to False


the answer to life, the universe and everything is 42

In [39]:
x = 0
while x <= 5:
    x += 1
    
    if x == 1:
        continue

    print("I am number", x)
    
    if x == 4:
        break


I am number 2
I am number 3
I am number 4

List Comprehension


In [40]:
v = [2, 3, 5, 7, 11]
doubles = [x*2 for x in v]
print(doubles)


[4, 6, 10, 14, 22]

In [41]:
[x*x for x in range(30) if x % 2 == 1]


Out[41]:
[1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841]

In [42]:
N = 10
[0] * N


Out[42]:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

In [43]:
[[0]*N for i in range(N)]


Out[43]:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

Sexy stuff


In [44]:
# Syntax for importing
from random import randint

v = [randint(1, 100) for i in range(10)]
print(v)


[25, 63, 96, 81, 90, 39, 23, 54, 8, 86]

In [45]:
v.sort()
print(v)


[8, 23, 25, 39, 54, 63, 81, 86, 90, 96]

In [46]:
line = "1 3 7 13 2\n"
line.strip()


Out[46]:
'1 3 7 13 2'

In [47]:
line.strip().split()


Out[47]:
['1', '3', '7', '13', '2']

In [48]:
[int(x) for x in line.strip().split()]


Out[48]:
[1, 3, 7, 13, 2]

In [49]:
sorted([int(x) for x in line.strip().split()])


Out[49]:
[1, 2, 3, 7, 13]

In [50]:
[alfa, beta, gamma, epsilon, omega] = sorted([int(x) for x in line.strip().split()])
print(alfa, omega)


1 13

In [51]:
beta, epsilon = epsilon, beta
print(beta)


7

Smart stuff


In [52]:
# How to count number of appearances
from collections import defaultdict

v = [randint(1, 10) for i in range(100)]
d = defaultdict(int)

for x in v:
    d[x] += 1

for key in d:
    print(key, d[key])


1 8
2 10
3 10
4 12
5 8
6 7
7 8
8 10
9 10
10 17

Combinatorics


In [53]:
v = 'ABCD'

from itertools import permutations

for p in permutations(v):
    print(" ".join(p))


A B C D
A B D C
A C B D
A C D B
A D B C
A D C B
B A C D
B A D C
B C A D
B C D A
B D A C
B D C A
C A B D
C A D B
C B A D
C B D A
C D A B
C D B A
D A B C
D A C B
D B A C
D B C A
D C A B
D C B A

In [54]:
from itertools import combinations
for c in combinations(v, 2):
    print(" ".join(c))


A B
A C
A D
B C
B D
C D

The End


In [55]:
import this


The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!