mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-28 18:26:54 +00:00
2.3 KiB
2.3 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 69bc6cb30c1d112a2e110a06 | Challenge 249: String Math | 29 | challenge-249 |
--description--
Given a string with numbers and other characters, perform math on the numbers based on the count of non-digit characters between the numbers.
- If the count of characters separating two numbers is even, use addition.
- If it's odd, use subtraction.
- Consecutive digits form a single number.
- Operations are applied left to right.
- Ignore leading and trailing characters that aren't digits.
For example, given "3ab10c8", return 5. Add 3 and 10 to get 13 because there's an even number of characters between them. Then subtract 8 from 13 because there's an odd number of characters between the result and 8.
--hints--
do_math("3ab10c8") should return 5.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(do_math("3ab10c8"), 5)`)
}})
do_math("6MINUS4") should return 2.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(do_math("6MINUS4"), 2)`)
}})
do_math("9plus3") should return 12.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(do_math("9plus3"), 12)`)
}})
do_math("5fkwo#10i#%.<>15P=@20!#B/25") should return 15.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(do_math("5fkwo#10i#%.<>15P=@20!#B/25"), 15)`)
}})
do_math("a.67,1$lk6ldf34@#LD@]2d32d2'2l3,@l3L#@2gh35s09if=df#$t9sm49t0df3$^%[vc;:0:4mt") should return 67.
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(do_math("a.67,1$lk6ldf34@#LD@]2d32d2'2l3,@l3L#@2gh35s09if=df#$t9sm49t0df3$^%[vc;:0:4mt"), 67)`)
}})
--seed--
--seed-contents--
def do_math(s):
return s
--solutions--
import re
def do_math(s):
tokens = re.findall(r'\d+|\D+', s)
result = None
pending_op = None
for token in tokens:
if re.match(r'^\d+$', token):
if result is None:
result = int(token)
elif pending_op == 'add':
result += int(token)
else:
result -= int(token)
else:
pending_op = 'add' if len(token) % 2 == 0 else 'subtract'
return result