Reputation: 521
Here are some tests:
Input: "zero nine five two"
Output: "four"
Input: "four six two three"
Ouput: "three"
Here is my code, which works until the last step where I need to inverse lookup key by value, which I dont know how to do. Any 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 = []
for 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
Upvotes: 1
Views: 114
Reputation: 8077
Why not just utilize a list of words to represent the numbers where the index represents their respective value?
def average_string(s):
num_list = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
str_split = s.split()
int_sum = sum(map(num_list.index, str_split))
return num_list[int_sum / len(str_split)]
The map goes over each element in str_split
and translates it into the numeric version by calling num_list.index()
using each element as a parameter.
Finally using the same num_list
, use the average value as the index to get the string version back.
Upvotes: 1
Reputation: 71451
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 nine five two"
new_dict = {b:a for a, b in num_dic.items()}
average = sum(num_dic[i] for i in s.split())/float(len(s.split()))
final_average = new_dict[average]
Output:
four
Upvotes: 1
Reputation: 162
As far as I know there isn't a way to lookup in a dict by value. Instead you can loop over the dict to find the correct value like this:
for text, number in num_dic.iteritems():
if number == int_avg:
print text
Here is another question where you can find this: Get key by value in dictionary
You can use num_dic.items()
in Python 3
Upvotes: 0
Reputation: 582
Here is how you inverse a dictionary. This is a duplicated question though:
inv_dic = {v: k for k, v in num_dic.items()}
Upvotes: 0