Apply Discount to Prices
Real-world version: Marking Down the Priced WordsThe statement here is our own: the same inputs, outputs and technique.
A notice reads sentence, a run of words separated by single spaces with no space at either end.
A word is a price when it begins with '$' and every character after that is a digit, and there is at least one such digit. Any other word is left alone, including a bare "$" and anything with a non-digit after the '$'.
Every price is reduced by discount percent. Write the reduced amount with exactly two digits after a decimal point, keeping the leading '$'. Taking a whole number of percent off a whole amount always lands on an exact number of hundredths, so two digits is always enough and nothing has to be rounded.
Return the notice after every price has been marked down.
Examples
Example 1
- Input
- sentence = "there are $1 $2 and 5$ items", discount = 50
- Output
- "there are $0.50 $1.00 and 5$ items"
The words "$1" and "$2" are prices and halve to "$0.50" and "$1.00". The word "5$" does not begin with the marker, so it is left alone.
Example 2
- Input
- sentence = "$3", discount = 33
- Output
- "$2.01"
Taking 33 percent off 3 leaves 2.01, which written to two digits is "$2.01".
Example 3
- Input
- sentence = "$", discount = 25
- Output
- "$"
The word is the marker with no digits after it, so it is not a price and is left unchanged.
Constraints
- 1 <= sentence.length <= 10^5
- sentence consists of lowercase English letters, digits, spaces and '$' only
- sentence has no leading or trailing space, and words are separated by single spaces
- Every price holds at most 10 digits and no leading zero
- 0 <= discount <= 100
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def mark_down_prices(sentence: str, discount: int) -> str:public String markDownPrices(String sentence, int discount)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 12 test cases: 12 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's