1

This function will take a string as input. The string has the following properties:

  • Includes characters 0-9
  • May include period to denote cents. (If not included assume 0 cents.)
  • May include $ sign.
  • May include commas as digit separators.

Your function will convert the string into a floating point number. You may not use any built in commands like int or float. You must solve this problem by analyzing the characters in the string of text.

If the input is invalid, return -1 as the function's result.

If I input the following:

100.00
200
98.78
$1,009.78
Goat
exit

This is what the output looks like:

Determine Price with Tax.
Enter 'exit' at any time to quit.
Enter Amount ($X,XXX.XX):
Amount: 100.0
Tax: 6.0
Price w/ Tax: 106.0
Enter Amount ($X,XXX.XX):
Amount: 200
Tax: 12.0
Price w/ Tax: 212.0
Enter Amount ($X,XXX.XX):
Amount: 98.78
Tax: 5.93
Price w/ Tax: 104.71
Enter Amount ($X,XXX.XX):
Amount: 1009.78
Tax: 60.59
Price w/ Tax: 1070.37
Enter Amount ($X,XXX.XX):
Amount: -1
Tax: -0.06
Price w/ Tax: -1.06
Enter Amount ($X,XXX.XX):

My code is:

def price_to_int(text):
    res = 0
    valid = "$,.1234567890"
    for l in text:
        if l in valid:
            res = float(text)
        else:
            return -1
    return res

#---------You may not make any changes below this line-----------   
print("Determine Price with Tax.")
print("Enter 'exit' at any time to quit.")
word = input("Enter Amount ($X,XXX.XX):\n")
while word.lower() != "exit":
    d = price_to_int(word)
    tax = 0.06
    print("Amount:",round(d,2))
    print("Tax:",round(d*tax,2))
    print("Price w/ Tax:",round(d+d*tax,2))
    word = input("Enter Amount ($X,XXX.XX):\n")

The only thing wrong is the function definition. My code works up until I input '$1009.78'. I am specifically asked to only rewrite the function definition and not change anything else.

0

1 Answer 1

3

Your current solution does not seem right to me. You are iterating over your string character-by-character, coercing each argument. You'd want to convert the entire string at once (otherwise, how are you going to get your float?).

Would you like a solution that does exception handling using try ... except?

def price_to_int(text):
    clean_text = text.lstrip('$').replace(',', '')
    try:
        return int(clean_text)
    except:
        try:
            return float(clean_text)
        except ValueError:
            return -1

This solution cleans your string and attempts to cast to float. If the conversion is not possible, an error is raised and handled, and -1 returned.

Details

  • str.lstrip removes the leading $ character
  • str.replace removes commas (when the second argument is the empty string)
  • try ... except ValueError: ... will attempt to run code inside the try block while waiting to catch a ValueError exception. If the exception is raised, the code inside the except block is executed (otherwise no).
Sign up to request clarification or add additional context in comments.

6 Comments

This will accept 100.5,0 which might be allowed, OP doesn't specify restrictions on comma use.
@RyanHaining Hmm, you have a point, but tricky inputs like that will require regex which I am assuming is beyond the scope of an entry level python course... however I will stay tuned for OP's verdict, if they ever decide to get, back that is
I was thinking more like parts = text.split('.'); dollars = parts[0] and then use what you have on dollars and stick parts[1] back onto the end if it exists
@RyanHaining I'll still have to worry about inputs like 10,,00.00 and stuff like that, there's a lot of scope to trip up the interpreter here... where do ya stop?
commas would only be allowed in every 4th place going right to left, and can't be the first non-digit (,000 is wrong) so you could scan in that way. irl a regex right? but this seems like the kind of thing I'd expect in a freshman programming assignment
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.