I thought it would be an easy win because it was problem A, but I couldn't come up with a vivid answer. (I don't want to take time, so I ended up submitting a code that doesn't have the sense of writing 8 different cases in solid, I'm sorry ...)
When I was looking at the submissions of the top performers for hints, I saw many vivid answers using itertools, but for me who recently started to touch Python, group by was a slapstick. I understand this time, so I will write down the contents.
There is a continuous $ 3 $ day weather record for AtCoder town. The weather record is represented by the string $ S $ of length $ 3 $, and the weather on the $ i (1 \ leq i \ leq 3) $ day is sunny when the $ i $ character is'S','R' It was raining at that time. Find the maximum number of consecutive days when the weather is rainy.
Constraint
The request is very simple, but if you simply judge by the number of'R', it will be NG with the pattern of'RSR'.
If you write it without any extensibility, it will be as follows. It's a push.
Shoboi answer
s = input()
if s == 'RRR':
res = 3
elif s =='SRR':
res = 2
elif s =='RSR':
res = 1
elif s =='RRS':
res = 2
elif s =='RSS':
res = 1
elif s =='SRS':
res = 1
elif s =='SSR':
res = 1
else:
res = 0
print(res)
Probably this is the expected code.
Ordinary answer
s = input()
if 'RRR' in s:
res = 3
elif 'RR' in s:
res = 2
elif 'R' in s:
res = 1
else:
res = 0
print(res)
morio__ had submitted the following code. .. For the yellow coder, it's completely reveal because it's the fastest AC in Python in 36 seconds.
#15907417
from itertools import groupby
res = 0
s = input()
for k, v in groupby(s):
if k == 'R':
res = max(res, len(list(v)))
print(res)
It's very versatile and beautiful. You can always get the longest contiguous number in a given string just by rewriting the part of the specified key. I feel that the code should be there.
This is the official document of groupby. itertools.groupby(iterable, key=None)
It seems that you can group by any column for multidimensional input, but this time I will look at it with a one-dimensional array. It seems to behave like this.
#Import groupby from itertools (itertools had many other useful tools)
from itertools import groupby
#One-dimensional array to group by
mylist = [0,0,0,1,1,2,2,2,1,1,1]
#groupby is iterable and returns key and group
for key, group in groupby(mylist):
#Cast each element of group to a list and output
print(key, list(group))
#output
# 0 [0, 0, 0]
# 1 [1, 1]
# 2 [2, 2, 2]
# 1 [1, 1, 1]
The group
obtained by groupby
is just an iterable'object', so it seems that you have to cast it to a list when handling it.
By the way, when I output the type of group
astype (group)
, it was<class'itertools._grouper'>
.
For the group whose key is'R', it means that the number of elements of the group is acquired by len (list (v))
and the maximum one is output.
It was very vivid and I learned a lot. I will do my best too.
Recommended Posts