fork download
  1. # Python 3
  2.  
  3. # Given a 2D matrix of M x N size, find all elements present in every row.
  4. testcase = [
  5. [7, 1, 3, 5, 3, 6],
  6. [2, 3, 6, 1, 1, 6],
  7. [6, 1, 7, 2, 2, 4],
  8. [6, 6, 7, 1, 3, 3],
  9. [5, 5, 6, 1, 5, 4],
  10. [3, 5, 6, 2, 7, 1],
  11. [4, 1, 4, 3, 6, 4],
  12. [4, 6, 1, 7, 4, 3]]
  13. # We always need to check elements, so we will use this list to store them.
  14. checked = []
  15. # We will use the elements in the first row one by one to check the other rows.
  16. for elmt in testcase[0]:
  17. # If this elmt is a duplicate, we skip it.
  18. if elmt in checked:
  19. continue
  20. # If it isn't a duplicate, then add it to the list of checked elmts
  21. else:
  22. checked.append(elmt)
  23. # Reset the counter used to confirm the presence of our elmt.
  24. count = 1
  25. # For each row,
  26. for row in testcase[1:]:
  27. # Count up if our element is present
  28. if elmt in row:
  29. count += 1
  30. # If a row is missing an elmt, we should break to save a little time.
  31. else:
  32. break
  33. # If our count is the same number as the amount of rows, then that number
  34. # must be present in all rows.
  35. if count == len(testcase):
  36. try:
  37. answer.append(elmt)
  38. # If we had no answers before, make a new list to begin keeping them
  39. except NameError:
  40. answer = [elmt]
  41. # Print our answer(s)
  42. try:
  43. print(answer)
  44. # If there is no answer to print, our answer is None.
  45. except NameError:
  46. print(None)
Success #stdin #stdout 0.03s 9312KB
stdin
Standard input is empty
stdout
[1, 6]