Strony

niedziela, 21 lutego 2021

 Problem:list of elements, one is unique, others always in pairs, find unique



 

def unique(arr):
""" find unique element in array
1. only one is unique
2. all the others are in pairs
>>> unique([1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1])
6
A XOR A = 0
0 XOR A = A
"""
x = 0
for i in arr:
x ^= i
return x
view raw unique hosted with ❤ by GitHub

 Handy itertools:


  • powerset
    import itertols as it
    def powerset(iterable):
    """
    powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
    """
    s = list(iterable)
    return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1))
    view raw powerset hosted with ❤ by GitHub
  • all sublist from list
    def sublists(iterable):
    """ generate all of the sublist from *iterable*.
    >>> [s for s in sublists('hi')]
    [('h',), ('i',), ('h', 'i')]
    >>> list(sublists([0, 1, 2]))
    [(0,), (1,), (2,), (0, 1), (1, 2), (0, 1, 2)]
    """
    # The length-1 sublist
    seq = []
    for item in iter(iterable):
    seq.append(item)
    yield (item,)
    seq = tuple(seq)
    item_count = len(seq)
    # And the rest
    for n in range(2, item_count + 1):
    for i in range(item_count - n + 1):
    yield seq[i : i + n]
    view raw sublists hosted with ❤ by GitHub