Amazing order in python combinational methods

I know set()python has no order since it is implemented as a hash table. However, I was a little surprised to resolve the issue of order using set.intersection().

So, I am assigned two lists with order, for example, indicating a certain rating or sequence of occurrence. I have to find an element that is common to both lists, and has the highest order (first) in the two lists. For instance,

List1 = ['j','s','l','p','t']
List2 = ['b','d','q','s','y','j']

must infer 's', since he is the second best in List1and occurs first in List2.

If you convert each of the lists into sets and take an intersection Set1.intersection(Set2), you will get a set set(['s', 'j']). In my case, I could convert this to a list and spit out the first element, and that was approximately O (n1 + n2).

I was happy to solve this interview question (all tests passed), but I am surprised how I can solve such a problem using python set.

Does anyone know how this works? What is the possible case that this can lead to breakage?

EDIT: looks like this is a case of luck, so if you have a good solution for this problem, it will also be appreciated

+4
source share
2 answers

O(n1+n2). . ( , ), , .

List1 = ['j','s','l','p','t']
List2 = ['b','d','q','s','y','j']

# unreachable max value to initialize the slots
maxlen = max(len(List1),len(List2))+1000

# create empty slot_array (initialized to values higher than last letter pos
# for both lists (the value is greater than any "valid" position)
# first pos (index 0) is for letter "a", last pos is for letter "z"

slot_array = [[maxlen,maxlen] for x in range(ord('a'),ord('z')+1)]

# scan both lists, and update the position if lower than the one in slot_array
for list_index,the_list in enumerate((List1,List2)):
    print(list_index)
    for letter_index,letter in enumerate(the_list):
        slot = slot_array[ord(letter)-ord('a')]
        if slot[list_index]>letter_index:
            slot[list_index] = letter_index

# now compute minimum of sum of both minimum positions for each letter
min_value = maxlen*2

for i,(a,b) in enumerate(slot_array):
    sab = a+b
    if sab < min_value:
        min_value = sab
        min_index = i

# result is the letter with the minimal sum
print(chr(min_index+ord('a')))
+1

:

Set2 = set(List2)
[x for x in List1 if x in Set2]

List1, List2.

next ( , ), .

0

Source: https://habr.com/ru/post/1659790/


All Articles