473,796 Members | 2,494 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

iterator? way of generating all possible combinations?

Ok, this is really irritating me. I'm sure there are different ways of
doing this - I'm interested in the algo, not the practical solution,
I'm more trying to play with iterators and recursion. I want to create
a program that generates every possible combination of a set of a n
dice, with s sides.

so I started with an iterator

class die(object):
def __init__(self,s ides):
self.sides = range(1,sides+1 )
def __iter__(self):
return self
def next(self):
self.sides = self.sides[1:] + [self.sides[0]]
return self.sides[-1]
now my thought was to create a recursive function to iterate through
all the dice combinations. Unfortunately.. . I'm coming up with a dead
end. I've tried working it out with different version of the die, ie
one that doesn't loop infinitely, but instead takes a starting
position. A vaiety of things, and yet I can't find a nice recursive
function that falls out of the die class.

Any ideas? or better terms to google? cuz I've tried.

Thanks

May 27 '06 #1
16 3561

ak*********@gma il.com wrote:
Ok, this is really irritating me. I'm sure there are different ways of
doing this - I'm interested in the algo, not the practical solution,
I'm more trying to play with iterators and recursion. I want to create
a program that generates every possible combination of a set of a n
dice, with s sides. . . . Any ideas? or better terms to google? cuz I've tried.


There are several interesting tidbits in the ASPN Cookbook:
http://aspn.activestate.com/ASPN/sea...ype=Subsection

http://tinyurl.com/frxqz

Raymond

May 27 '06 #2

<ak*********@gm ail.com> wrote in message
news:11******** **************@ i40g2000cwc.goo glegroups.com.. .
Ok, this is really irritating me. I'm sure there are different ways of
doing this - I'm interested in the algo, not the practical solution,
I'm more trying to play with iterators and recursion. I want to create
a program that generates every possible combination of a set of a n
dice, with s sides.


Are the dice identical or distinguishable (marked). In other words, with 2
dice, is 1,2 the same as 2,1 or different? Note that in most dice games,
such as craps, the dice are not distinguished, but probability calculations
must treast them as if they were to get the elementary events.

Terry Jan Reedy

May 27 '06 #3

Terry Reedy wrote:

Are the dice identical or distinguishable (marked). In other words, with 2
dice, is 1,2 the same as 2,1 or different? Note that in most dice games,
such as craps, the dice are not distinguished, but probability calculations
must treast them as if they were to get the elementary events.

they are distinct. This isn't necessarily about simulating a game. So
yes the dice are marked and I want to track those different
possibilties.

May 27 '06 #4
hmmm, just needed better search words, thanks :)

May 27 '06 #5

<ak*********@gm ail.com> wrote in message
news:11******** **************@ j73g2000cwa.goo glegroups.com.. .

Terry Reedy wrote:

Are the dice identical or distinguishable (marked). In other words,
with 2
dice, is 1,2 the same as 2,1 or different? Note that in most dice
games,
such as craps, the dice are not distinguished, but probability
calculations
must treast them as if they were to get the elementary events.

they are distinct. This isn't necessarily about simulating a game. So
yes the dice are marked and I want to track those different
possibilties.


Then your dice problem is equivalent to generating all n-digit base-d
numbers, which is also the n-fold cartesian product of a set with itself.
Sequential generation amounts to a 'plus-1' operation.

tjr

May 27 '06 #6


Well thanks for the mathematical restatement of my problem. I had
forgotten the proper terms. Searching on those terms generates some
interesting results.

However, none of the algo's I have checked will work with generated
sequences, or iterable classes, as posited in my first post.

While appropriate to the current domain, ie dice. What if you want
combinations of extrememely large lists, say 3 sets of 10 mil items.
In such a case, I really do want my sets to be generators rather than
lists or set objects.

This is what had me stumped before, and still has me stumped.

May 30 '06 #7
ak*********@gma il.com wrote:


Well thanks for the mathematical restatement of my problem. I had
forgotten the proper terms. Searching on those terms generates some
interesting results.

However, none of the algo's I have checked will work with generated
sequences, or iterable classes, as posited in my first post.

While appropriate to the current domain, ie dice. What if you want
combinations of extrememely large lists, say 3 sets of 10 mil items.
In such a case, I really do want my sets to be generators rather than
lists or set objects.

This is what had me stumped before, and still has me stumped.


def combinations(l, depth):
if depth == 1:
for element in l:
yield (element,)
else:
for element in l:
for rest in combinations(l, depth -1 ):
yield (element,) + rest

HTH,

Diez
May 30 '06 #8
ak*********@gma il.com wrote:
However, none of the algo's I have checked will work with generated
sequences, or iterable classes, as posited in my first post.

While appropriate to the current domain, ie dice. What if you want
combinations of extrememely large lists, say 3 sets of 10 mil items.
In such a case, I really do want my sets to be generators rather than
lists or set objects.

This is what had me stumped before, and still has me stumped.


class Counter(object) :
def __init__(self, digits, iterable=None):
self.digits = digits
self.iterable = iterable
def __iter__(self):
for digit in self.digits:
single = digit,
if self.iterable is None:
yield single
else:
for rest in self.iterable:
yield single + rest

for v in Counter('ab', Counter('cd', Counter('ef', Counter('gh'))) ):
print v

This works with "iterables" (and produces), rather than "iterators" ,
which is vital to the operation.

--Scott David Daniels
sc***********@a cm.org
May 30 '06 #9
This would only work for combinations of identical sets, and also does
not seem to work with generated sets, or iterators. Forgetting dice
for a moment. Say I have 3 very long files, and i want to generate the
combinations of lines in the files. This provides a well known
iterator for the example.

file1 = open('foo.txt')
file2 = open('bar.txt')
file3 = open('baz'.xt')

All examples I have seen and all attempts I have written generally do
something similar - which is they only iterates through the possible
combinations for the last element and do nothing for all other
elements.

I saw an interesting example that generates a nested function for the
given number of sets. While the example still didn't work with
generators as input, I think a little tweaking would make it work.

This should fulfill my requirements with a rather harsh limit of
python's max nesting depth (20?)

May 30 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

38
3694
by: Grant Edwards | last post by:
In an interview at http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273 Alan Kay said something I really liked, and I think it applies equally well to Python as well as the languages mentioned: I characterized one way of looking at languages in this way: a lot of them are either the agglutination of features or they're a crystallization of style. Languages such as APL, Lisp, and Smalltalk are what you might call style...
0
3399
by: sks_cpp | last post by:
I am trying to wrap the map iterator for keys and values. However, I seem to run into problems with the values for const_iterator - it works for all other combinations. Below I list my code and the compiler error. Please help if possible. Thanks in advance. // Compiler error ra:/home/ssangapu/personal/C++/STL/mapIter-738>g++ main.cc utlMapIterator.h: In method `class Object *& ValueIterator<_Rb_tree_iterator<pair<const int,Object...
2
2014
by: Lorenzo Castelli | last post by:
This is an old problem of mine. Basically I have an abstract base class which represents a generic iterator over a collection of elements, and various derived classes that implement the traversing on specific data structures. For each iterator I want to be able to specify the four possible const combinations, corresponding to the various void* for pointers, with the possibility to perform conversions from non-const to const just like...
8
5638
by: Mir Nazim | last post by:
Hello, I need to write scripts in which I need to generate all posible unique combinations of an integer list. Lists are a minimum 12 elements in size with very large number of possible combination(12!) I hacked a few lines of code and tried a few things from Python CookBook (http://aspn.activestate.com/ASPN/Cookbook/), but they are hell slow.
1
1139
by: mrajanikrishna | last post by:
Hi friends, I am generating combinations from a set with different sub sets. Here is my code. For this example, actually I need to get 56 combinations but I am getting 35 only. Can anybody suggest where I was wrong? <script language="javascript"> var st=Array("1","2","3","4","5","6"); var n=0;
6
3441
by: py_genetic | last post by:
Hi, I'm looking to generate x alphabetic strings in a list size x. This is exactly the same output that the unix command "split" generates as default file name output when splitting large files. Example: produce x original, but not random strings from english alphabet, all lowercase. The length of each string and possible combinations is
4
7692
by: RSH | last post by:
Okay my math skills aren't waht they used to be... With that being said what Im trying to do is create a matrix that given x number of columns, and y number of possible values i want to generate a two dimensional array of all possible combinations of values. A simple example: 2 - columns and 2 possible values would generate: 0 0
14
2011
by: bjorklund.emil | last post by:
Hello pythonistas. I'm a newbie to pretty much both programming and Python. I have a task that involves writing a test script for every possible combination of preference settings for a software I'm testing. I figured that this was something that a script could probably do pretty easily, given all the various possibilites. I started creating a dictionary of all the settings, where each key has a value that is a list of the possible...
13
6368
by: Yosifov Pavel | last post by:
Whats is the way to clone "independent" iterator? I can't use tee(), because I don't know how many "independent" iterators I need. copy and deepcopy doesn't work... --pavel
0
9683
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9529
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10457
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10231
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6792
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5443
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4119
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2927
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.