python - string number average returned in string format -
here tests:
input: "zero 9 5 two"
output: "four"
input: "four 6 2 three"
ouput: "three"
here code, works until last step need inverse lookup key value, dont know how do. advice?
def average_string(s): num_dic = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9} str_split = s.split() int_values = [] key, val in num_dic.items(): if key in str_split: int_values.append(val) int_avg = int(sum(int_values) / len(int_values)) return int_avg
you can try this:
num_dic = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9} s = "zero 9 5 two" new_dict = {b:a a, b in num_dic.items()} average = sum(num_dic[i] in s.split())/float(len(s.split())) final_average = new_dict[average]
output:
four
Comments
Post a Comment