-4

I want no add all the numbers in my string

info="10-20,30,40-50,60,70-80"

    print(sum([int(a) for a in info.split(",")[::2].split("-")])+sum([int(b) for b in info.split(",")[1::2]]))
Amit
  • 327
  • 2
  • 11

2 Answers2

0

I am not a Python person, so there is definitely a better way to do this, but here is a step-by-step way to get to your desired result. Hopefully, the comments are explanatory. I also commented out several print() statements that you can re-add if you want to see what transformations happen at each step:

x="10-20,30,40-50,60,70-80"

# Do a first split
xList = x.split(',')
#print(xList)

# Get the non-ranges into their own list
listOfSingles = []
xListSingleNumsOnly = list(filter(lambda x: '-' not in x, xList))
for a in xListSingleNumsOnly:
    listOfSingles.append(int(a))

# Get the sum of the non-ranges
listOfSinglesSum = sum(listOfSingles)
#print(listOfSinglesSum)

# Get the ranges into their own list
xListRangesOnly = list(filter(lambda x: '-' in x, xList))
#print(xListRangesOnly)

# Turn the ranges that are currently strings into ints and populate them
# Start with an empty list to hold results of transformations
listOfRanges = []

# Split on the dash
for i in xListRangesOnly:
    iSplit = i.split('-')
    # For each (pseudo-)range, populate it
    listedInts = []
    for x in iSplit:
        listedInts.append(int(x))
    ranged = list(range(listedInts[0],listedInts[1]+1))
    # Add up these ranges
    rangeSum = sum(ranged)
    listOfRanges.append(rangeSum)

# Sum the ranges you just populated
listOfRangesSum = sum(listOfRanges)
#print(listOfRangesSum)

final = listOfSinglesSum + listOfRangesSum
print(final)
reallymemorable
  • 882
  • 1
  • 11
  • 28
-1

Import regular expression library and using findall method, set a search pattern in order to get integers from string.

import re
    sum([int(i) for i in re.findall(pattern="\d[,]?[-]?\d",string=info)])
Amit
  • 327
  • 2
  • 11
  • Hello! While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Brian61354270 Jul 19 '20 at 17:11