0

I finally make this works, but I dont like that my solution is like "someone else checking how many list exist" and writing the code.

It find common item in all list.

I tried to use recursion, but I coldn't make it works

def comunes (*lista):
  word = ""
  for i in lista:
    word = "set({})".format(i) + " &" + word
  word = word.split(" ")
  word.pop()
  wordF = ""
  for i in word:
    wordF += str(i)
  if len(eval(wordF)) == 0:
    return None
  else:
    return eval (wordF)
Daniel
  • 53
  • 5

1 Answers1

0
def comunes(*lista):
    commons = set(lista[0])
    for i in lista[1:]:
        commons &= set(i)
    return commons

This function creates a set commons with all the elements of the first list and then for each next list i it'll replace commons with the intersection (& operator) of commons with the set of i. The intersection of two sets is the set with only the elements that are both in the first and the second set. This'll ensure that commons has only elements that are in all the lists you passed to comunes.

isaactfa
  • 5,461
  • 1
  • 10
  • 24
  • 2
    As a rule of thumb, if you're using `eval` or `exec` you should rethink your approach. It's almost never a good idea to use them for 'everyday' problems. – isaactfa Apr 30 '19 at 16:09