This converts from character representation of integers to their decimal value:
def chrtodec(str):
dec = 0
base = ord('0')
for chr in str:
dec = dec * 10 + ord(chr) - base
return dec
For example: "123" -> 123
This converts from character representation of integers to their decimal value:
For example: "123" -> 123 |
||||
|
You shouldn't use You should also add comments and a docstring. Docstrings are basically comments that are programmatically accessible so that other users can understand how to use your function.
I think you have another big problem though, which is invalid input handling. Take a look at these:
Clearly there are problems here when you have characters other than numbers, so I think what you should do is raise a
You could also just use Also you could add support for negative numbers by checking at the start if the first character is
This evaluates the expression
Then just return with a ternary that checks
|
|||||||||
|
Your code lacks modularization, This problem can be decomposed in:
The second function is an excellent place for a generator expression:
Finally:
|
|||||||||||||||||||||
|
You don't support negative numbers. But that's actually pretty easy to add, all you need to do is:
That also has the handy ability to support arbitrary base conversions too! |
|||||||||||||||||||||
|
Please improve your naming! I've come to love the "straight-to-the-point" Python syntax a lot, and I embrace the delicious syntactic sugar of the language; but I keep seeing really bad naming of things among Python programmers. Maybe try this?
|
|||||||||||||
|