Suppose I have a string containing the following:
'*as**4fgdfgd*vv**6fdfd5***5'
String contains numbers, letters, and a special symbol such as an asterisk.
- I need to find the sum of numbers
(4,6) (5,5)separated byasterisk. - The
number of asterisksbetween two numbers must beequal to 3. - Return
Trueifsumofevery pairisequal to 10.
Examples:
*as**4fgdfgd*vv**6fdfd5***5returnsTrue.ssss*0***10jkj* **0***10returnsTrue.5***5***5returnsTruebecause there 3 asterisks between the numbers and sum equals 10.8**2returnsFalse
My Code So far:
my_str = "*as**4fgdfgd*vv**6fdfd5***5"
my_digits = [int(x) for x in my_str if x.isnumeric()]
print(sum(my_digits))
CodePudding user response:
You can use a regex to find pairs of numbers that are separated by 3 asterisks, then convert the found numbers to int and add them, returning true if all pairs add to 10. Note that because you want overlapping matches, we need to use a lookahead as described in this question.
def all_tens(my_str):
pairs = re.findall(r'(?=(?<!\d)(\d )(?:[^*\d]*\*){3}[^*\d]*(\d ))', my_str)
return len(pairs) > 0 and all(sum(map(int, pair)) == 10 for pair in pairs)
strs = [
'*as**4fgdfgd*vv**6fdfd5***5', 'ssss*0***10jkj* **0***10', '5***5***5', '8**2', '5***5***4'
]
for s in strs:
print(f'{s} : {all_tens(s)}')
Output:
*as**4fgdfgd*vv**6fdfd5***5 : True
ssss*0***10jkj* **0***10 : True
5***5***5 : True
8**2 : False
5***5***4 : False
Regex explanation:
(?=(?<!\d)(\d )(?:[^*\d]*\*){3}[^*\d]*(\d )(?!\d))
(?=a lookahead (we use this to allow overlapping matches)(?<!\d)the preceding character must not be a digit(\d )some digits, captured in group 1(?:[^*\d]*\*){3}3 sets of an asterisk, which may be preceded by some number of characters which are neither asterisks or digits[^*\d]*some number of characters which are not asterisk or digits(\d )some digits, captured in group 2
