Obtaining a powerset of a set in Java

Yes, it is O(2^n) indeed, since you need to generate, well, 2^n possible combinations. Here’s a working implementation, using generics and sets: public static <T> Set<Set<T>> powerSet(Set<T> originalSet) { Set<Set<T>> sets = new HashSet<Set<T>>(); if (originalSet.isEmpty()) { sets.add(new HashSet<T>()); return sets; } List<T> list = new ArrayList<T>(originalSet); T head = list.get(0); Set<T> rest = new … Read more

How to “perfectly” override a dict?

You can write an object that behaves like a dict quite easily with ABCs (Abstract Base Classes) from the collections.abc module. It even tells you if you missed a method, so below is the minimal version that shuts the ABC up. from collections.abc import MutableMapping class TransformedDict(MutableMapping): “””A dictionary that applies an arbitrary key-altering function … Read more

How to get all subsets of a set? (powerset)

The Python itertools page has exactly a powerset recipe for this: from itertools import chain, combinations def powerset(iterable): “powerset([1,2,3]) –> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)” s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) Output: >>> list(powerset(“abcd”)) [(), (‘a’,), (‘b’,), (‘c’,), (‘d’,), (‘a’, ‘b’), (‘a’, ‘c’), (‘a’, ‘d’), (‘b’, ‘c’), (‘b’, … Read more

Possible Locations for Sequence/Picture Parameter Set(s) for H.264 Stream

First off, it’s important to understand that there is no single standard H.264 elementary bitstream format. The specification document does contain an Annex, specifically Annex B, that describes one possible format, but it is not an actual requirement. The standard specifies how video is encoded into individual packets. How these packets are stored and transmitted … Read more

Does Python have an ordered set?

The answer is no, but you can use collections.OrderedDict from the Python standard library with just keys (and values as None) for the same purpose. Update: As of Python 3.7 (and CPython 3.6), standard dict is guaranteed to preserve order and is more performant than OrderedDict. (For backward compatibility and especially readability, however, you may … Read more