[PYTHON] Private memos used for list operations and competitive programming

If you notice it, you can add or update the article here. http://qiita.com/clarinet758/items/5135a8075001a3b6782b is in ruins.

Strings in reverse order

a='abcdef'
a[::-1]
'fedcba'

Scheduled for lists, sets, maps, etc.

list

Make a lot of empty lists l=[[] for x in xrange(n)]

Turn vertically and horizontally. e.g. Original character string 8 vertical 8 8 horizontal abcdefgh ijklmlop qrstuvwx yzABCDEF GHIJKLMN OPQRSTUV WXYZ1234 567890!?

tateyoko.py


#In this case a,b is 8 for both
(a,b)=map(int, raw_input().split())
x=[sys.stdin.readline().strip() for x in range(a)]
print x
#['abcdefgh', 'ijklmlop', 'qrstuvwx', 'yzABCDEF', 'GHIJKLMN', 'OPQRSTUV', 'WXYZ1234', '567890!?']

chikan=[[] for i in range(8)]
#X in the original list[0]Read from
for a in range(8):
#Initialize the list of temporary storage
    tate=[]
#Lick the bth element in column a
    for b in range(8):
        tate.append(x[b][a])
#Combine the different characters one by one and put them in the list for official storage
    tate1=''.join(tate)
    chikan[a]=tate1
print chikan
#['aiqyGOW5', 'bjrzHPX6', 'cksAIQY7', 'dltBJRZ8', 'emuCKS19', 'flvDLT20', 'gowEMU3!', 'hpxFNV4?']

Back and forth between strings and lists

List operation


#For strings
orig = "hello"
li   = list(orig)   #String=>list
text = "".join(li)  #list=>String
print li    # ['h', 'e', 'l', 'l', 'o']
print text  # hello


#For an array of numbers
nums = [1,2,3,4,5]
text = "".join(map(str, nums))  #list=>String
li   = list(map(int, text))     #String=>list
print li    # [1, 2, 3, 4, 5]
print text  # 12345

#It seems that it is faster to use the inclusion notation for the list from the character string
#Reflect the comments you received and check how to use them
text='12345'
li = [int(i) for i in text]
#[1, 2, 3, 4, 5]

Sorting the list

sort.py


#Sort in ascending order()Is used.
>>> m = [1, 18, 2, 117, 205]
>>> m.sort()
# x = m.sort()Even if you write, leave the original list,
#x cannot be a sorted list.
>>> m
[1, 2, 18, 117, 205]


#In the case of descending order, sort once()Then reverse()Is used.
>>> n = [1, 18, 2, 117, 205]
>>> n.reverse()
>>> n
[205, 117, 2, 18, 1]
# reverse()Just do it to reverse the original list.
#So sort in ascending order and then reverse.
>>> n.sort()
>>> n.reverse()
>>> n
[205, 117, 18, 2, 1]

List y=Be careful when handling with x


>>> x=[1,6,3,8,4]
>>> y=x
>>> y
[1, 6, 3, 8, 4]
>>> x
[1, 6, 3, 8, 4]
>>> y.sort()
>>> y
[1, 3, 4, 6, 8]
>>> x
[1, 3, 4, 6, 8]
>>> y[1]=y[1]+1
>>> y
[1, 4, 4, 6, 8]
>>> x
[1, 4, 4, 6, 8]

>>> x=[1,2,3,4,5]
>>> y=x[:]
>>> x
[1, 2, 3, 4, 5]
>>> y
[1, 2, 3, 4, 5]
>>> y[1]+=3
>>> y
[1, 5, 3, 4, 5]
>>> x
[1, 2, 3, 4, 5]

The original list is not left for sort () and reverse (). .. If you need the original list

Sort part 2


#Let x be the original list and y be the sort destination
>>> x=[3,55,6,3,71,8,1]
>>> y=sorted(x)
>>> y
[1, 3, 3, 6, 8, 55, 71]
>>> y=reversed(x)
>>> y
<listreverseiterator object at 0x109144c10>
>>> y=x[::-1]
>>> y
[1, 8, 71, 3, 6, 55, 3]
>>> y=reversed(x)
>>> y[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'listreverseiterator' object is not subscriptable
>>> for i in y:
...   print i
... 
1
8
71
3
6
55
3

It seems that you need to be careful because reversed () is a mysterious behavior.

What are the elements in the list of c?

Count the number and set the maximum / minimum


#1 in c,2,3,Count the number of 4(p)Count by
#Append to the empty list l.
#max(l),min(l)For maximum and minimum values
l,p=[],1
c=[1, 2, 3, 4, 1, 2, 3]
for i in xrange(4):
    l.append(int(c.count(p)))
    p+=1
print max(l),min(l)

#It seems that the inclusion notation is good for the element count, so reprint it
c = [1, 2, 3, 4, 1, 2, 3]
l = [c.count(i) for i in xrange(4)]
print max(l), min(l)

Dictionaries for elements in the list


i=['A','A','C','C','A','B']
h={"A":4,"B":3,"C":2,"D":1,"F":0}
for x in enumerate(i): f+=h[x[1]]

↑ A neat code that I don't understand why I passed. It still counts the scores assigned to ABC in the list of i.

Difference between list elements? take

List diff


a=['a','b','c','d',1,2,'3','4']
b=['c','d','1',2,3]
#List of people to leave-List of candidates to be erased, list of enrolled people-List of migrants=Like the latest enrollee
#The order of the list is broken.
l=set(a)-set(b)
l
set(['a', 1, '3', 'b', '4'])
sabun=list(l)
sabun
['a', 1, '3', 'b', '4']

List join


a=[1,2,3]
b=['4','5','6']
c=a+b
#It seems that there is no problem even if str type and int type are mixed

List duplicate operation

For deduplication, the set type is faster than the list type, and logical expressions can be used, which is convenient. Let's use the set type.

set type

A set object is a collection of unordered hashable objects. Common uses include testing membership, removing duplicates from sequences, and calculating mathematical operations such as AND, OR, complement, and symmetric differences. It seems.

Operation of set that I tried or seems to use


{raw_input()}
123
#set(['123'])

{int(raw_input())}
345
#set([345])

#Separated by spaces
set(raw_input().split())
#I can, but

set(int, raw_input().split())
set(input().split())
#Is no good

Various overlapping elements from the two lists


#When using set
a=[1,2,3,1,2,3]
b=[1,4,5]

set(x)&set(y)
#set([1])
#a,It seems that only the elements that are duplicated in b are extracted
#The duplication in a and b seems to disappear

set(x)|set(y)
#set([1, 2, 3, 4, 5])
#The duplication in a and b disappears, and all the elements become one

set(x)^set(y)
#set([2, 3, 4, 5])
#The duplication in a and b seems to disappear
#It was only in a, it was only in b, but it joins

#The number of elements is len(set(x)&set(y))Etc. can be taken using len.

#Duplicates in the set disappear when it is made into a set type.
#It seems that the existence of duplicate elements in the set is erased. set(raw_input())
23432
# set(['3', '2', '4'])
set(raw_input())
asdfgfdsa
# set(['a', 's', 'd', 'g', 'f'])
#Notation that was possible
#set(raw_input().split())All contents are str, separated by spaces

#When using group by
#next time

If set cannot be used


#Is it possible to create a string in the lower column using the characters in the upper column one by one? When
Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

s=list(raw_input())+[' ']*200
try: 
  map(s.remove,raw_input())
  print 'YES'
except:
  print 'NO'

Erase elements in the list

・ Specify the position and order of the list risuto=['a','b','c'] del risuto[i] The i-th of risuto disappears

・ Specify by element risuto=['haru','natsu','aki',huyu'] risuto.remove('huyu') This will make huyu disappear

・ Erase the end risuto=['haru','natsu','aki',huyu'] risuto.pop() This will remove the trailing huyu

List comprehension for statement tt = [ x+y for x in "abxy" for y in "abxy" ]

Count a specific string

count.py


>>> x = 'aaaabbaaabaaa'
>>> x
'aaaabbaaabaaa'
>>> x.count('aa')
4
# 1,The second character is'aa'2 if counted as,3rd character'aa'Is
#It seems that it is not counted.

>>> x.count('a')
10

Count the number of matches

count.py


>>> import re

>>> x = 'aaaabbaaabaaaba'
>>> i = 0
# +Counts one or more consecutive characters immediately before.
>>> for m in re.finditer('a+', x):
...    i += 1
... 
>>> i
4

>>> re.findall('a+', x)
['aaaa', 'aaa', 'aaa', 'a']
#Matching points are extracted in list format
# len(re.findall('a+', x))To get the number of elements in the list
#It seems to be synonymous with getting the number of matches.

# re.re than findall.finditer seems to save memory.
>>> i = 0
>>> for m in re.finditer('a+', x):
...    i += 1
... 
>>> i
4

Reference site http://lightson.dip.jp/zope/ZWiki 2013/11/14 I should have known the syntax highlighting, so it was a complete omission. .. .. Thank you for your editing request.

Recommended Posts

Private memos used for list operations and competitive programming
[Summary of books and online courses used for programming and data science learning]
[Competitive programming] [Python3] Required knowledge, for myself
Get all standard inputs used in paiza and competitive programming with int (python)
List of frequently used built-in functions and methods
[Python / Chrome] Basic settings and operations for scraping
Program to search all permutations (for competitive programming)
[For beginners] How to study programming Private memo
[Python] Building an environment for competitive programming with Atom (input () can be used!) [Mac]