I checked the re module while solving the 51st question of Project Euler, so I will write the FizzBuzz code instead of the memorandum. In the following, I tried to (1) use regular expressions as much as possible, and (2) do not use the% operator even if I do not use regular expressions.
For multiples of 3, I couldn't think of a judgment using regular expressions. Therefore, in order to determine the multiple of 3, we used the fact that if the sum of each digit of the multiple of 3 is repeated, the final result will be either 3, 6 or 9. Specifically, it was decided to call recursively until the sum became one digit. When it becomes one digit, if the number is 3, 6 or 9, it returns true, otherwise it returns false.
def is_multiple_of_3(n):
if len(str(n)) == 1:
if str(n) in ['3', '6', '9']:
return True
else:
return False
else:
return is_multiple_of_3( reduce(lambda x,y:int(x)+int(y), str(n)))
Determining multiples of 5 is easy. This is because the first digit should be 0 or 5. It's easy, so I simply made it using re. As a caveat, re.compile (). Match () only hits at the word level (it determines if it matches from the beginning of the word, so use re.compile (). Search () It seems that you need to either precede the string you want to hit with? *.
def is_multiple_of_5(n):
#p = re.compile('(5|0)$')
p = re.compile('\d*(5|0)$')
if p.match(str(n)):
return True
else:
return False
When I googled "replace using regular expressions", the article about re.sub () was displayed at the top. If you want to use regular expressions for character replacement, you probably need to use re.sub.
If it is a multiple of 3 and a multiple of 5, it is a multiple of 15, so no special judgment was made. However, I tried to make full use of small tricks such as adding a space at the end of "Fizz" and replacing the space with "Buzz". If this works, FizzBuzz should look good.
import re
def is_multiple_of_3(n):
if len(str(n)) == 1:
if str(n) in ['3', '6', '9']:
return True
else:
return False
else:
return is_multiple_of_3( reduce(lambda x,y:int(x)+int(y), str(n)))
def is_multiple_of_5(n):
#p = re.compile('(5|0)$')
p = re.compile('\d*(5|0)$')
if p.match(str(n)):
return True
else:
return False
def main():
for n in range(1,101):
ret = str(n)
if is_multiple_of_3(n):
ret = re.sub('\d+', 'Fizz ', ret)
if is_multiple_of_5(n):
ret = re.sub('(\d+|\ )', 'Buzz', ret)
ret.strip(' ')
print ret
main()
Recommended Posts