python - How to find the first common number from a dictionary of lists -


i have dictionary of lists. each list contains many numbers. lists can have different lengths. looking find first common number in lists. the answer has function.

for example in case:

d = { 'case1' : [18, 17, 497, 298, 57, 82, 1], 'case2': [128, 184, 497,298,57, 1, 82], 'case3':[104,2828,3881, 497, 1, 38], 'case4': [392, 497, 573, 1]} 

the expected output is: 497. don't want catch 1. looking 497.

all have :

def find_first_common_number(dictionary_of_lists):     list_name in dictionary_of_lists:    #list name e.g. 'case1'         num1 in dictionary_of_lists[list_name]:             #this going have find first common              # number lists in dictionary             # order number appears in each list not matter 

i appreciate on this. looked through list methods, couldn't new python. if explain/comment method great.

can try way:

#!/usr/bin/python  d = { 'case1' : [18, 17, 497, 298, 57, 82],       'case2': [128, 184, 497,298,57,82],       'case3':[104,2828,3881, 497, 38],       'case4': [392, 497, 573]       }  k = d.values() # sort bring shortest list in front  # loop base on shortest list.(optimization) k.sort(key = lambda s: len(s))  def find_first_common_number(k):     # lets loop base on shortest list.     # k[0] first list      y in k[0]:        if all([y in x x in k[1:]]):            return y     return false print find_first_common_number(k) 

output: 497


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -