Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Using regex and too many if solution in Creative category for Reveal the Number by H0r4c3
import re
def reveal_num(line: str) -> int | float | None:
signs = re.findall('[+-]', line)
digits = re.findall('\d', line)
dots = re.findall('\.', line)
signs_digits_dots = re.findall('[+]|[-]|\d|[.]', line)
if digits == []:
return None
if signs_digits_dots[0].isdigit() or signs_digits_dots[0] == '.':
signs = ''
if not signs and not dots:
if digits[0] == 0:
digits.pop(0)
return int(''.join(digits))
signs_digits_dots = re.findall('[+]|[-]|\d|[.]', line)
digits_positions = [(pos, dig) for pos, dig in enumerate(signs_digits_dots) if dig.isdigit()]
idx_first_digit = digits_positions[0][0]
signs = [sign for sign in signs_digits_dots[:idx_first_digit] if sign in ['+', '-']]
if signs:
sign = signs[-1]
else:
sign = ''
if sign == '+':
sign = ''
if '.' in signs_digits_dots:
idx_first_dot = signs_digits_dots.index('.')
first_digits = [dig for dig in signs_digits_dots[:idx_first_dot] if dig.isdigit()]
last_digits = [dig for dig in signs_digits_dots[idx_first_dot+1:] if dig.isdigit()]
result = sign + ''.join(first_digits) + '.' + ''.join(last_digits)
else:
result = sign + ''.join(digits)
return eval(result)
print("Example:")
print(reveal_num("+A%+-1-0..."))
# These "asserts" are used for self-checking
assert reveal_num("F0(t}") == 0
assert reveal_num("Utc&g") == None
assert reveal_num("-aB%|_-+2ADS.12+3.ADS1.2") == 2.12312
assert reveal_num("-aB%|_+-2ADS.12+3.ADS1.2") == -2.12312
assert reveal_num("zVâ„–1}3;o.vEf``C.WqTY0") == 13.0
assert reveal_num("!3B'j=(}89JQ6aWvN*%5@uy.r)B
Feb. 23, 2023