forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apply-discount-to-prices.py
42 lines (38 loc) · 1.29 KB
/
apply-discount-to-prices.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Time: O(n)
# Space: O(1)
# string
class Solution(object):
def discountPrices(self, sentence, discount):
"""
:type sentence: str
:type discount: int
:rtype: str
"""
result = []
i = 0
while i < len(sentence):
j = sentence.find(' ', i)
if j == -1: j = len(sentence)
if sentence[i] == '$' and j-(i+1) > 0 and all(sentence[k].isdigit() for k in xrange(i+1, j)):
cnt = reduce(lambda x, y: x*10+int(y), (sentence[k] for k in xrange(i+1, j)), 0)
result.append("${:d}.{:02d}".format(*divmod(cnt*(100-discount), 100)))
else:
for k in xrange(i, j):
result.append(sentence[k])
if j != len(sentence):
result.append(' ')
i = j+1
return "".join(result)
# Time: O(n)
# Space: O(n)
# string
class Solution2(object):
def discountPrices(self, sentence, discount):
"""
:type sentence: str
:type discount: int
:rtype: str
"""
def format(discount, x):
return "${:d}.{:02d}".format(*divmod(int(x[1:])*(100-discount), 100)) if x[0] == '$' and x[1:].isdigit() else x
return " ".join(format(discount, x) for x in sentence.split())