Tips (control structure) that you should know when programming competitive programming with Python2

The part about the control structure of tips you should know when programming competition with Python2 has been divided.

The version of Python is 2.7.5 (In Python3, specifications such as input / output are significantly different, so it is recommended to refer to other articles).

Conditional branch

Pass a variable to a conditional expression

Personally, I don't like it very much, but to reduce the amount of code

while 1:
    a = input()
    if not a: 
        break
    # ...   

I feel that variables are often passed to conditions such as if statements and while statements.

Result of putting a variable in If statement in Python --LIFE WITH PYTHON

Mold result
int False if 0, True otherwise
float 0.False if 0, True otherwise
str ''(Empty string)False if not, True otherwise
list []False if not, True otherwise
tuple ()False if not, True otherwise
dict {}False if not, True otherwise
set set()False if not, True otherwise
None False

I want to end the process in the middle

In some cases, it may be easier to end the script execution in the middle, such as when a symbol indicating the end of input or a corner case is input. In such cases, use quit () or sys.exit ().

a = input()
if a == 0:
    quit()
# ...
import sys

a = input()
if a == 0:
    sys.exit()
# ...  

repetition

range () and xrange ()

2. Built-in functions — Python 2.7ja1 documentation

If you want to implement a simple iteration like "do XX n times" in Python,

n = 5

for i in range(n):
  print i
# 0
# 1
# 2
# 3
# 4

Or

n = 5

for i in xrange(n):
  print i
# 0
# 1
# 2
# 3
# 4

It is common to write like this.

Here, range (n) and xrange (n) return a list object and an xrange object in which integers from 0 to n are arranged in ascending order, respectively. The xrange object is an object that can be retrieved when a value is needed by using lazy evaluation. If n is very large, range (n) will generate a list and then loop, which will increase memory usage, butxrange (n)can avoid that. Also, regarding speed, xrange () is faster except in some cases. [python - Should you always favor xrange() over range()? - Stack Overflow] (http://stackoverflow.com/questions/135041/should-you-always-favor-xrange-over-range)

Also, in (x) range, various ranges can be expressed by using the 2nd and 3rd arguments or by using reversed ().

# range(start, stop)So, start to stop-Returns a list of all integers up to 1 in ascending order
print range(2, 6) # [2, 3, 4, 5]

# range(start, stop, step)So, among the integers obtained by increasing the value every step from start, stop-Returns a list of everything up to 1 in ascending order
print range(5, 30, 5) # [5, 10, 15, 20, 25]

# reversed()You can reverse the list with
for i in reversed(range(5)):
    print i
# 4
# 3
# 2
# 1
# 0

Expanding variables in a for statement

With a for statement

l = [1, 2, 3, 4, 5]
for e in l:
    print e

output


1
2
3
4
5

You can expand each element of the list as in, but this is

l = [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
for i, e in l:
    print '#{0}: #{1}'.format(i, e)

output


0: a
1: b
2: c
3: d

You can also do like this.

enumerate

When turning the for loop, it may be nice to be able to get the index and value of the list at the same time.

ʻEnumerate ()` returns an iterator with an index and its value for a list of arguments.

l = ['a', 'b', 'c', 'd']
for elem in enumerate(l):
    print elem
# (0, 'a')
# (1, 'b')
# (2, 'c')
# (3, 'd')

#The above code is equivalent to the following code
for i in range(len(l)):
    print (i, l[i])

for-else, while-else statement

In Python, else clauses can be added to for and while statements. At this time, the else clause is called only if it has never been internally broken by the end of the loop.

a = [1, 2, 3, 4, 5]
b = [1, 2, 4, 5]
x = 3

def find_val(l, x):
    for i in range(len(l)):
        if l[i] == x:
            print i
            break
    else:
        print 'Not found...'

#Find on_val()Equivalent code
def find_val2(l, x):
    flag = False
    for i in range(len(l)):
        if l[i] == x:
            print i
            flag = True
            break
    if not flag:
        print 'Not found...'

find_val(a, x) # 2
find_val(b, x) # Not found...

It is very easy and convenient to write because it is not necessary to have a flag when asking a question such as "Find x. If not found, output'hoge'". However, if there are multiple loops, the visibility will be worse, so it is better not to use it.

Recommended Posts

Tips (control structure) that you should know when programming competitive programming with Python2
Tips (data structure) that you should know when programming competitive programming with Python2
Tips (input / output) that you should know when programming competitive programming with Python2
Tips you should know when programming competitive programming with Python2 (useful library)
Knowledge you need to know when programming competitive programming with Python2
Tips to know when programming competitively with Python2 (Other language specifications)
Competitive programming with python
Knowledge of linear algebra that you should know when doing AI
Competitive programming with python Local environment settings
I made a competitive programming glossary with Python
Personal tips when doing various things with Python 3
Precautions when dealing with control structures in Python 2.6
[python] [vscode] When you get angry with space-tab-mixed
Solve with Python [100 past questions that beginners and intermediates should solve] (053 --055 Dynamic programming: Others)
You should know if you use Python! 10 useful libraries
What are you using when testing with Python?
Directory structure when writing tests with Python 3 standard unittest
Python programming with Atom
Competitive programming diary python 20201220
Competitive programming diary python
Programming with Python Flask
I know? Data analysis using Python or things you want to use when you want with numpy
[Tips] Dealing with errors that occur when trying to install Python 3 series less than 3.5.3 with pyenv
Solution when you want to use cv_bridge with python3 (virtualenv)
Use a macro that runs when saving python with vscode
Programming with Python and Tkinter
[Python tutorial] Control structure tool
[Tips] Handle Athena with Python
Python Competitive Programming Site Summary
Error when playing with python
Network programming with Python Scapy
If you know Python, you can make a web application with Django
Let's create a Python directory structure that you won't regret later
What should I do with the Python directory structure after all?
Solve with Python [100 selections of past questions that beginners and intermediates should solve] (034-038 Dynamic programming: Knapsack DP basic)
Solve with Python [100 selections of past questions that beginners and intermediates should solve] (039 --045 Dynamic programming: Knapsack DP variant)