I want to individually print(and then write to a file) items of a list that are in another list. If there are no matching items then I want 'NONE' to be printed. I have a time limit on my program, so I would like a quick and easy solution to this, preferable under 0.1 seconds.
I have a list called joinedComb, and I want to individually print all items in joinedComb that are in another list called dictionary I have tried
for i in joinedCombs:
if i in dictionary:
endResult.append(i)
fout.write(i+'\n')
if endResult == []:
fout.write('NONE\n')
I would like it to print something like this:
GREG
GEKA
GENO
or
NONE
endResult = [i for i in joinedCombs if i in dictionary]
fout = '\n'.join(endResult) if any(endResult) else 'NONE'
If you prefer, it is possible to do it without loops. You can use logical conjuction of two sets but don't expect execution time shortening.
endResult = set(joinedCombs).intersection(set(dictionary.keys()))
Thank You for this answer. However, the grader still says that the program runs for too long (1.393 seconds). Do you have any faster methods, without loops, perhaps?
@MathWiz Please, provide information on the size of
joinedCombs
anddictionary
as well as some example values. Does values of joinedCombs repeat?joinedCombs is 3^12 terms long(its huge) and dictionary is 5000 terms long. no repeated terms in either one
please check this site where I have posted a more specific question: stackoverflow.com/questions/56874022/…
@MathWiz 3^12 list size isn't very big and I'm quite surprised that your execution time is that long. I created example list and sample dictionary with given sizes and the execution time was below 0.05 second. Please, check solution from edited answer. Maybe it will help you in any manner.