――Since I use Ruby at work, I mainly solved competitive programming with Ruby, but at the next workplace, I will practice Python little by little every day because I will use Python, and I will leave it in Qiita as a memorandum. The subject is Let Code. --I'm not familiar with Python, so feel free to comment.
Easy 1108.Defanging an IP Address --Summary: Replace. With [.]
"1.1.1.1"
"1[.]1[.]1[.]1"
--Replace: ** replace **
class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".","[.]")
771.Jewels and Stones --Summary: Count how many letters J are in S
J = "aA", S = "aAAbbbb"
3
--Answer 1: Use strings like arrays
--Arrange strings: ** list **
--Character count: ** count **class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
cnt = 0
chars = list(J)
for e in chars:
cnt += S.count(e)
return cnt
--Answer 2: Use strings like arrays
--I didn't know that strings can be treated like arrays as they are
--for x in string:
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
cnt = 0
for e in J:
cnt += S.count(e)
return cnt
--Answer 3: Use anonymous function
――I think Python's lambda is a map in Ruby.
--The shape is special and processing for arrays (map (lambda variable: processing for variables, arguments))
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
return sum(map(lambda x:S.count(x),J))
1281.Subtract the Product and Sum of Digits of an Integer --Summary: Number of all digits multiplied by --- Number of all digits added
n = 234
15
--Answer 1: Calculate as an array with lambda
--Create a number array with the lambda you just remembered. With Ruby, you can immediately imagine with map and to_i
--String => Integer: ** int **
--Integer => string: ** str **class Solution:
def subtractProductAndSum(self, n: int) -> int:
ary = list(map(lambda x: int(x), list(str(n))))
n = 1
m = 0
for i in ary:
n *= i
for j in ary:
m += j
ans = n - m
return ans
--Answer 2: Calculate as a string array (Sophisticated form of Answer 1) --Use **; ** for multiple tasks --Use **: ** in block units?
class Solution:
def subtractProductAndSum(self, n: int) -> int:
a, b = 0, 1
for i in str(n): a += int(i); b *= int(i)
return b - a
1221.Split a String in Balanced Strings
--Summary: How many pairs of R and L can be created under the condition that R and L must have the same number of characters?
s = "RLRRLLRLRL"
4
--Answer 1: Count the number of pairs by setting 1 if R appears and -1 if L appears.
class Solution:
def balancedStringSplit(self, s: str) -> int:
r = 0
output = 0
for e in s:
if e == 'R':
r += 1
if e == 'L':
r -= 1
if r == 0:
output += 1
return output
Recommended Posts