1

I am currently working through this book: Introduction to Computation and Programming Using Python.

The question I am currently working on is:

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 figured out how to this for integers:

s = raw_input('Enter any positive integers: ')

total = 0

for c in s:

    c = int(c)

    total += c

print total

I tried several methods including try and except method, but I can figure out how to solve the

Valuerror:invalid literal for int() with base 10: '.'

I appreciate any help. Thank you.

Update: I want to thank every one for their help. It is good to know that there are people who are willing to help the small joe.

3
  • Well, have you tried changing int to float? Commented Jan 7, 2014 at 23:39
  • Yes, I have but because there are multiple floats separated by commas, it can't convert it. Commented Jan 7, 2014 at 23:54
  • Next time remember to post accurate information - the error you present doesn't match the situation you're describing (the error is not about the comma you speak of now, but because of trying parse a float with int()) Commented Jan 7, 2014 at 23:56

3 Answers 3

2
sum(map(float,raw_input("Enter any positive integers: ").split(',')))

This is sort of a quick and dirty one-liner as a quick hack. Here it is unrolled a little:

input_string = raw_input("Enter any positive integers: ")
#input_string is now whatever the user inputs

list_of_floats_as_strings = input_string.split(",")
#this splits the input up across commas and puts a list in
#list_of_floats_as_strings. They're still strings here, not floats yet,
#but we'll fix that in a moment

running_total = 0 #gotta start somewhere

for value in list_of_floats_as_strings:
    number = float(value) #turn it into a float
    running_total+=number #and add it to your running total

#after your for loop finishes, running_total will be the sum you're looking for

As for what EXACTLY the quick dirty one-liner does:

sum( #tells Python to add up everything inside the brackets
    map( #tells Python to run the designated function on everything in the
         #iterable (e.g. list or etc) that follows
        float, #is the float() function we used in the unrolled version
        raw_input("Enter any positive integers: ") #is your input
            .split(',') #splits your input into a list for use in map
        )
    )

Please never write code the way I just did. Keep those dirty one-liners as dirty one-liners, and explain them afterwards. I thought that format may be better for a one-shot explanation, but DEFINITELY it is far worse for documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Well, at least it's short :)
Longer now -- figured I'd type the hack then explain the code :P
1

Here is a solution using a for loop.

# Save the string (e.g. '12.5,67.4,78.5')
number_string = raw_input("Enter any positive floats: ")

# Initialize a variable to hold the sum of the numbers
tot = 0

# Iterate over all numbers in the string. The string is splitted 
# at each comma, thus resulting in a list like `['12.5', '67.4', '78.5']`
for num in number_string.split(','):
    # But every element in the list is a string, so you need to 
    # convert them to floats, and add each of them to the total sum
    tot += float(num)

# Print the total sum
print tot

As others have pointed out, you can do this easier and by writing less code, but this may be a bit easier to understand. When you understand this, you may understand how the other solutions work.

2 Comments

Thanks a lot. I wanted to ask I understand it correctly: are the parameters inside the split method are excluded? I appreciate your help, this is exactly what I was looking for.
@user3171116 If you want to read more about such methods, type help(str) in your Python interpreter, and all the string methods will be shown. You can also read about it in the online docs
1

Use split and float, e.g.

s = raw_input('Enter any floats: ')
print s

items = s.split(",")
print "items:",items

floats = map(float, items)
print "floats:",floats

total = sum(floats)
print "total:",total

The output would be

Enter any floats: 12.3,45.6,78.9
12.3,45.6,78.9
items: ['12.3', '45.6', '78.9']
floats: [12.3, 45.6, 78.9]
total: 136.8

Comments

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.