Hello I was given a problem where I had to take a list of lists and find individual bands within those lists and see if they all have a common favorite band. If so I am supposed to output true. I need to follow this method of programming where I modularize my code, but I cannot seem to get it. Here is my code so far. Thank you for all help that you can give.
favoriteBandLists = [["Metallica","Linkin Park","Alice In Chains","Nirvana", "Soundgarden"],
["Pink Floyd","Alice In Chains","Soundgarden","Metallica","Linkin Park"],
["Audioslave","Offspring","The Beatles", "Soundgarden"]]
def commonFavoriteBand(favoriteBandLists):
thereExists= False
for i in (favoriteBandLists[2]):
if(commonFavoriteBandA(favoriteBandLists)):
thereExists = True
return (thereExists)
def commonFavoriteBandA(favoriteBandLists):
foundCounterExampleYet = False
for band in favoriteBandLists[2]:
if not(band == favoriteBandLists[0:1]):
foundCounterExampleYet = True
return not foundCounterExampleYet
print(commonFavoriteBand(favoriteBandLists))
If you really want to write something that shows that you're modularizing your code, first make a function that returns the common element in two lists:
def commonBand(L1, L2):
answer = []
for band in L1:
if band in L2:
answer.append(band)
return answer
Now, call that function many times, repeatedly:
def main(listOfLists):
i = 1
answer = listOfLists[0]
while i<len(listOfLists):
answer = commonBand(answer, listOfLists[i])
if not answer:
break
i += 1
return answer
Output:
In [193]: main(favoriteBandLists)
Out[193]: ['Soundgarden']
Note: this seemed like a homework question to me, so my code is conducive to that. I would otherwise have gone with the set intersection method that has been discussed in other responses here