473,695 Members | 1,965 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 3548

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
3665
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
3395
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
2008
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
5632
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
1135
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
3435
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
7678
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
2000
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
6348
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
8652
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
9140
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...
1
8867
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
8841
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7688
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6511
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4599
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3025
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
1987
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.