Reputation:
I am new comer to python. I started to read a book published by MIT's professor about python. I got an exercise from this book. I tried to solve this but i could not.
Problem: Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123' . Write a program that prints the sum of the numbers in s. i have to find out the sum of 1.23,2.4, and 3.123
So far i made some codes to solve this problem and my codes are follwoing:
s = '1.23,2.4,3.123'
total = 0
for i in s:
print i
if i == ',':
Please,someone help me how can go further?
Upvotes: 2
Views: 974
Reputation: 107287
All you need is first splitting your string with ,
then you'll have a list of string digits :
>>> s.split(',')
['1.23', '2.4', '3.123']
Then you need to convert this strings to float
object till you can calculate those sum
, for that aim you have 2 choice :
First is using map
function :
>>> sum(map(float, s.split(',')))
6.753
Second way is using a generator expression within sum
function :
>>> sum(float(i) for i in s.split(','))
6.753
Upvotes: 4
Reputation: 28983
It's much less Pythonic, and more effort, to walk through the string and build up the numbers as you go, but it's probably more in keeping with the spirit of a beginner working things out, and more of a continuation of your original code:
s = '1.23,2.4,3.123'
total = 0
number_holder_string = ''
for character in s:
if character == ',': # found the end of a number
number_holder_value = float(number_holder_string)
total = total + number_holder_value
number_holder_string = ''
else:
number_holder_string = number_holder_string + character
print total
That way, number_holder_string goes:
''
'1'
'1.'
'1.2'
'1.23'
found a comma -> convert 1.23 from string to value and add it.
''
'2'
'2.'
etc.
Upvotes: 0
Reputation: 8380
It is much simpler to use str.split()
, like in
s = '1.23,2.4,3.123'
total = 0
for i in s.split(','):
total += float(i)
Upvotes: 0