If we considered this input in Python:
s="""David Smith 17,15,14,19 Melina Jackson 15,16,17,19,20 Charli Decker 14,15,18 """
I want to have this output:
{"David_Smith":16.25," Melina_Jackson":21.75,"Charli Decker":15.75}
CodePudding user response:
What you can do is :
- split the string every space. It will create a list with 3 elements per person : first name, last name and marks (I guess),
- iterate over the list. First we concatenate the first name and last name into
Mark_Twain. Then we calculate the mean. Then we add this pair into a dictionnary
def calc_mean(numbers: list[int]) -> float:
"""calculate a mean"""
return sum(numbers) / len(numbers)
def extract_mean_from_string(s: str) -> dict:
arr = s.strip().split(" ")
means = {}
i = 0
while i < len(arr):
name = arr[i] "_" arr[i 1]
string_numbers = arr[i 2]
numbers = list(map(int, string_numbers.strip().split(",")))
means[name] = calc_mean(numbers)
i = 3
return means
# If we considered this input in Python:
s = """David Smith 17,15,14,19 Melina Jackson 15,16,17,19,20 Charli Decker 14,15,18 """
# I want to have this output:
expected = {"David_Smith": 16.25, " Melina_Jackson": 21.75, "Charli Decker": 15.75}
print(expected)
print(extract_mean_from_string(s))
{'David_Smith': 16.25, ' Melina_Jackson': 21.75, 'Charli Decker': 15.75}
{'David_Smith': 16.25, 'Melina_Jackson': 17.4, 'Charli_Decker': 15.666666666666666}
Those are the correct values.
CodePudding user response:
I am providing this answer that you want to get the average of those numbers.
Average of 17,15,14,19 equal to 16.25
There can be shorter ways, my code looks like this :
string ="""David Smith 17,15,14,19 Melina Jackson 15,16,17,19,20 Charli Decker 14,15,18"""
mydict = {}
total = 0
numbers,fname,fullname = [],[],[]
data = string.split(' ')
for i in data :
c = data.index(i)
c = 1
if c%3 == 0 :
numbers.append(i)
elif i.isalpha() :
fname.append(i)
for item1, item2 in zip(fname[::2], fname[1::2]):
fullname.append(str(item1) ' ' str(item2))
for z in range(len(numbers)) :
allno = numbers[z].split(',')
for no in allno :
total = int(no)
avg = "{:.2f}".format((total/len(allno)))
mydict[fullname[z]] = avg
total = 0
print(mydict)
Output :
{'David Smith': '16.25', 'Melina Jackson': '17.40', 'Charli Decker': '15.67'}
