user14384591
user14384591

Reputation:

calculate avg from an input that is a string

I have a string that looks like the following

s = """nate : 9.5 ,8 ,5 ,8.7
moe : 7 ,6.8 , - ,1
sam : 6 ,4 , ,7.6
cat : 8 ,8.6 ,6 ,2"""

for the dash (- ) it should just be removed completely for ex: 6.8, - , 1 should become 6.8,1 for the blank parts, it should have 0 instead for ex 4, , 7.6 should become 4, 0 , 7.6 after that is all done I want to calculate the average of each person and display it as a dictionary

this what I have come up with and I couldn't manage to go any further

def avg(s):
    s = s.replace(" - ,", ""). replace(", ,", ", 0 ,")
    s= s.strip().splitlines()
    students={}
    for i in s: 
        s = i.strip().split(":")         
        students[s[0]]= s[1].strip().split(",") 

Upvotes: 0

Views: 84

Answers (2)

Barmar
Barmar

Reputation: 781068

Loop through the scores, skipping -, replacing empty strings with 0, and converting the rest to floats. Then calculate the average by dividing by the length, and store that in the students dictionary.

It's easier to replace individual list elements than replacing in the original lines, since your spacing is inconsistent.

def avg(s):
    s= s.strip().splitlines()
    students={}
    for i in s: 
        s = i.split(":")
        student = s[0].strip()
        scores = [x.strip() for x in s[1].split(",")]
        scores = [float(score) if score else 0 for score in scores if score != "-"]
        students[student] = sum(scores) / len(scores) if scores else 0

Upvotes: 2

John Gordon
John Gordon

Reputation: 33335

# split s into lines and iterate over each line
for line in s.splitlines():

    # init num_scores and total to zero for this student
    num_scores = 0
    total = 0.0

    # get the name and the scores
    name, scores = line.split(" : ")

    # split scores on commas and iterate over each score
    for score in scores.split(","):
        # remove whitespace
        score = score.strip()

        # if we have something and it's not a dash
        if score and score != "-":
            num_scores += 1
            total += float(score)

    # print this student's name and average
    print(f"{name}: average score {total/num_scores}")

Upvotes: 0

Related Questions