Python is a simple algorithmic task in lists (a standard question for an interview)

There are 2 input lists L and M, for example:

L =  ['a',     'ab',  'bba']
M = ['baa', 'aa',  'bb']

How to get 2 non-empty output lists U and V such that: ''.join(U) == ''.join(V)) is True and each element of U lies in L, and each element of V is in M?

For example, one of the possible solutions for the two lists above is:

U=['bba', 'ab', 'bba', 'a']
V=['bb', 'aa', 'bb', 'baa']

because

 'bbaabbbaa' == 'bbaabbbaa' is True

and every element of ['bba', 'ab', 'bba', 'a'] is in ['a', 'ab', 'bba']

and every element of ['bb', 'aa', 'bb', 'baa'] is in ['baa', 'aa', 'bb']

1) Create an algorithm that finds at least one solution (U and V).

2) Is it possible to solve it in O (n), where n = len (L + M)?

: WQ

+3
source share
3 answers

- ( ) ? " " ( - ) ...?

, , U V [] O (1) ; -).

: , , , - :

import itertools as it
import collections

L = ['a', 'ab', 'bba']
M = ['baa', 'aa', 'bb']

def cmbs(L=L, M=M):
  Ucans = collections.defaultdict(list)
  Vcans = collections.defaultdict(list)
  sides = (L, Vcans, Ucans), (M, Ucans, Vcans)
  for i in it.count(1):
    for k, (G, Ocans, Tcans) in enumerate(sides):
      for u in it.product(G, repeat=i):
        j = ''.join(u)
        if j in Ocans:
          for samp in Ocans[j]:
            result = samp, u
            yield result[1-k], result[k]
        Tcans[j].append(u)

if __name__ == '__main__':
  for x, y in it.islice(cmbs(), 10):
    print x, y, ''.join(x), ''.join(y)

('a', 'a') ('aa',) aa aa
('bba', 'a') ('bb', 'aa') bbaa bbaa
('a', 'a', 'a', 'a') ('aa', 'aa') aaaa aaaa
('a', 'a', 'bba', 'a') ('aa', 'bb', 'aa') aabbaa aabbaa
('a', 'ab', 'a', 'a') ('aa', 'baa') aabaa aabaa
('a', 'ab', 'bba', 'a') ('aa', 'bb', 'baa') aabbbaa aabbbaa
('bba', 'a', 'a', 'a') ('bb', 'aa', 'aa') bbaaaa bbaaaa
('bba', 'ab', 'a', 'a') ('bb', 'aa', 'baa') bbaabaa bbaabaa
('bba', 'ab', 'bba', 'a') ('bb', 'aa', 'bb', 'baa') bbaabbbaa bbaabbbaa
('bba', 'a', 'bba', 'a') ('bb', 'aa', 'bb', 'aa') bbaabbaa bbaabbaa

, O (N) - N ?! -)

2: ( ) dicts , , , > 1 (a , , ); , L ['a', 'aa'] , s > 1 a - , , M, .

+9

! , .

from itertools import product 
m = 5   # top limit of elements in output lists
sumsets = lambda s1, s2: s1 | s2

for u in reduce(sumsets, [set(product(L, repeat=i)) for i in  range(1, m+1)]):
    for v in reduce(sumsets, [set(product(M, repeat=i)) for i in  range(1, m+1)]):
            if ''.join(u) == ''.join(v):
                print u, v  

: U, V

('a', 'a', 'a', 'a') ('aa', 'aa')
('a', 'a') ('aa',)
('a', 'a', 'bba', 'a') ('aa', 'bb', 'aa')
('bba', 'a', 'a', 'a') ('bb', 'aa', 'aa')
('bba', 'a') ('bb', 'aa')
('bba', 'ab', 'a', 'a') ('bb', 'aa', 'baa')
('a', 'ab', 'a', 'a') ('aa', 'baa')
('a', 'ab', 'bba', 'a') ('aa', 'bb', 'baa')
('bba', 'ab', 'bba', 'a') ('bb', 'aa', 'bb', 'baa')
('bba', 'a', 'bba', 'a') ('bb', 'aa', 'bb', 'aa')
+4

" " , , .

+1
source

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


All Articles