The following works but I’m wondering if there is a better more Pythonic way. I’m checking if there is any list in crosses[0] that has all different numbers than any list in crosses[1] then check crosses[0] vs crosses[2], then check crosses[1] vs crosses[2], and so on. The list might be much longer I just used a short one for example.
The lists that do not share any of the same numbers are:
crosses[0][0] and crosses[2][1],
crosses[0][1] and crosses[1][0],
crosses[0][1] and crosses[2][1]
crosses = [[[1,2,3,4], [2,3,4]], [[1,6,7,8], [2,6,7,8]], [[1,2], [6,7]]]
result = 0
for i in range(len(crosses)):
for j in range(len(crosses[i])):
for k in range(i + 1, len(crosses)):
for l in range(len(crosses[k])):
match = False
for num in crosses[i][j]:
if num in crosses[k][l]:
match = True
if not match:
area = len(crosses[i][j]) * len(crosses[k][l])
if area > result:
result = area
print(result) # 12
So, basically create a set from the two lists being compared and if the length of the set is less than the total length of the two original lists added together then there is overlapping numbers in the lists. Is that what you’re thinking? That did cross my mind and I wondered about time complexity. I’ve studied time complexity and get the “gist” of it but I have to admit not fully grasped it.
That’s one way. I was thinking more about getting intersection of two sets (two lists) and checking if the resulting set is empty (meaning there’s no matching elements in both lists) or not.
Regarding the time complexity - is there a specific concern? If not I’d just stick with what is more clear for you. Step with making sets might add some overhead, but checking if two sets have matching elements should be much faster than iterating manually over the contents of the lists. Generally due to how sets work, checking if element is in set is as fast as it gets. The more elements are in the initial set (list), the more advantage will have set.
Thanks for the reply, I’ll look more into sets and intersection and see if I can shorten it up a bit.
This code was part of a solution I had for a hackerrank challenge, my solution passed the test in the time limit but it got me thinking if the lists were nested deeper I would need to add more loops and if the data is really large would my code be the most efficient?
Please let me know how I can improve my code, or maybe a different way of solving it. There are a few lines that could be expanded into multiple lines for better readability, but it’s still pretty clean. Enjoy!
Here is my solution to the Time-Calculator Exercise: