[Tutor] computation problem
Zhenya Sakal
genichka at gmail.com
Sun Nov 28 17:59:24 EST 2021
Hello!
You are looking into creating a powerset. There are many solutions to this
problem but I think the one through bit notation is the shortest.
def powerSet(items):
N = len(items)
# enumerate the 2 ** N possible combinations
for i in range(2 ** N):
combo = []
for j in range(N):
#test bit j-th of integer i -> that is turning base 10 into
binary for i
if (i >> j) % 2 == 1:
combo.append(items[j])
yield combo
On Sun, Nov 28, 2021 at 4:49 PM Mark Lawrence <breamoreboy at gmail.com> wrote:
> On 28/11/2021 19:14, marcus.luetolf at bluewin.ch wrote:
> > Hello Experts
> >
> >
> >
> > I'd like to write a python code to find all possible combinations of a
> list
> > of n items.
> >
> > If, for example, a list L consists of 4 items, n = 4, L = ['abcd'], the
> > code should print out 24 different combinations from ['abcd'] to
> ...['dcba']
> >
> > I tried several solutions posted on stackoverflow using itertools but
> none
> > gave the sought for combinations.
> >
> > I'm aware the complexity of a a code using for loops might be
> exponential .
> >
> > Could anybody tell me a text or tutorial how to approach tist task by
> python
> > ?
> >
>
> You have a list which contains one item, a string 'abcd'. If you only
> want the string used the following works.
>
> python3.9
> Python 3.9.7 (default, Sep 10 2021, 14:59:43)
> [GCC 11.2.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from itertools import permutations
>
> >>> l='abcd'
> >>> for a in permutations(l):print(a)
> ...
> ('a', 'b', 'c', 'd')
> ('a', 'b', 'd', 'c')
> ('a', 'c', 'b', 'd')
> ('a', 'c', 'd', 'b')
> ('a', 'd', 'b', 'c')
> ('a', 'd', 'c', 'b')
> ('b', 'a', 'c', 'd')
> ('b', 'a', 'd', 'c')
> ('b', 'c', 'a', 'd')
> ('b', 'c', 'd', 'a')
> ('b', 'd', 'a', 'c')
> ('b', 'd', 'c', 'a')
> ('c', 'a', 'b', 'd')
> ('c', 'a', 'd', 'b')
> ('c', 'b', 'a', 'd')
> ('c', 'b', 'd', 'a')
> ('c', 'd', 'a', 'b')
> ('c', 'd', 'b', 'a')
> ('d', 'a', 'b', 'c')
> ('d', 'a', 'c', 'b')
> ('d', 'b', 'a', 'c')
> ('d', 'b', 'c', 'a')
> ('d', 'c', 'a', 'b')
> ('d', 'c', 'b', 'a')
> >>>
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
>
> Mark Lawrence
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
--
Ievgeniia Sakal, PhD
she/her/hers,
Yale University,
Department of History
More information about the Tutor
mailing list