Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Match two elements in a tuple, return the 3rd

I have a set of input conditions that I need to compare and produce a 3rd value based on the two inputs. a list of 3 element tuples seems like a reasonable choice for this. Where I could use some help is in building an compact method for processing it. I've laid out the structure I was thinking of using as follows:

input1 (string) compares to first element, input2 (string) compares to second element, if they match, return 3rd element

('1','a', string1)
('1','b', string2)
('1','c', string3)
('1','d', string3)
('2','a', invalid)
('2','b', invalid)
('2','c', string3)
('2','d', string3)
like image 528
downbySF Avatar asked Jan 13 '23 02:01

downbySF


1 Answers

Create a dict, dicts can have tuple as keys and store the third item as it's value.

Using a dict will provide an O(1) lookup for any pair of (input1,input2).

dic = {('1','a'): string1, ('1','b'):string2, ('1','c'): string3....}

if (input1,input2) in dic:
   return dic[input1,input2]
else:
   #do something else

Using a list of tuples in this case will be an O(N) approach, as for every input1,input2 you've to loop through the whole list of tuples(in worst case).

like image 166
Ashwini Chaudhary Avatar answered Jan 28 '23 01:01

Ashwini Chaudhary