473,804 Members | 2,243 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
16 3563

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

--Scott David Daniels
sc***********@a cm.org


Sorry, it doesn't. It works with strings. It doesn't work with file,
it doesn't work with iterators I have created.

I have been using file objects as my test iterables for now - forgoing
any complications in my own iterables. such that my test bed has been:
f = open('word.txt' )
f2 = open('word2.txt ')
f3 = open('word3.txt ')

for combo in [testable function here]
print combo
Each file contains the letter a through g on, with each letter on a
line. At least I don't feel as bad anymore. My first attempts
generate the same output, and a couple of my earlier attempts work
quite nicely with lists, and similar things. But I can't find anthing
that works generically with any iterable, nor anything that works with
generators.

May 30 '06 #11
ak*********@gma il.com wrote:
Scott David Daniels wrote:
This works with "iterables" (and produces), rather than "iterators" ,
which is vital to the operation.

--Scott David Daniels
sc***********@a cm.org


Sorry, it doesn't. It works with strings. It doesn't work with file,
it doesn't work with iterators I have created.


Sorry, "re-iterables". A file re-iterable is:

class FileReIterable( object):
def __init__(self, file):
if isinstance(file , basestring):
self.file = open(file, 'rU')
else:
self.file = file
def __iter__(self):
self.file.seek( 0)
return iter(self.file)

This works if-and-only-if it is only in use once at a time.
If you have multiple simultaneous accesses, you need to do
something like:

class FileReIterable2 (object):
def __init__(self, file):
if isinstance(file , basestring):
self.file = open(file, 'rU')
else:
self.file = file
def __iter__(self):
self.file.seek( 0)
for line in self.file:
nextpos = self.file.tell( )
yield line
self.file.seek( nextpos)

--Scott David Daniels
sc***********@a cm.org
May 30 '06 #12

Scott David Daniels wrote:
Sorry, "re-iterables". A file re-iterable is:

class FileReIterable( object):
def __init__(self, file):
if isinstance(file , basestring):
self.file = open(file, 'rU')
else:
self.file = file
def __iter__(self):
self.file.seek( 0)
return iter(self.file)

This works if-and-only-if it is only in use once at a time.
If you have multiple simultaneous accesses, you need to do
something like:

class FileReIterable2 (object):
def __init__(self, file):
if isinstance(file , basestring):
self.file = open(file, 'rU')
else:
self.file = file
def __iter__(self):
self.file.seek( 0)
for line in self.file:
nextpos = self.file.tell( )
yield line
self.file.seek( nextpos)

--Scott David Daniels
sc***********@a cm.org


Since I was doing this as a self education excercise. When you say is
in use once and only once, you mean I can only use a single instance of
the class? I haven't even tested these yet, but I am very curious
about that statement. Why is it necessary to return a generator object
in the second example? If it's a real long explanation, feel free to
point me to some relvant texts. My practical problem was solved about
10 posts ago... but I am still trying to understand the behavior.

Thank you for you time.

AK

May 30 '06 #13
ak*********@gma il.com wrote:
Scott David Daniels wrote:
Sorry, "re-iterables". A file re-iterable is:

class FileReIterable( object): ...
def __iter__(self):
self.file.seek( 0)
return iter(self.file)

This works if-and-only-if it is only in use once at a time.
If you have multiple simultaneous accesses, you need to do
something like:

class FileReIterable2 (object): ...
def __iter__(self):
self.file.seek( 0)
for line in self.file:
nextpos = self.file.tell( )
yield line
self.file.seek( nextpos)


Since I was doing this as a self education excercise. When you say is
in use once and only once, you mean I can only use a single instance of
the class?

No. This works:

f1 = FileReIterable( "one.file")
f2 = FileReIterable( "another.fi le")
... free uses of ...

This does not "work":

gen = FileReIterable( "one.file")

for a in gen:
for b in gen:
print a, b

This does "work":

gen = FileReIterable2 ("one.file")

for a in gen:
for b in gen:
print a, b

That is, any instance of FileReIterable must not be used in a
context where it may be in the midst of iterating a file, gets
used to produce a result, and then must produce a result from
the original iteration.

If you think about what must happen to the file read pointer,
the reason for all of this should become clear.

--Scott David Daniels
sc***********@a cm.org
May 30 '06 #14

Scott David Daniels wrote:
ak*********@gma il.com wrote:
Scott David Daniels wrote:
Sorry, "re-iterables". A file re-iterable is:

class FileReIterable( object): ...
def __iter__(self):
self.file.seek( 0)
return iter(self.file)

This works if-and-only-if it is only in use once at a time.
If you have multiple simultaneous accesses, you need to do
something like:

class FileReIterable2 (object): ...
def __iter__(self):
self.file.seek( 0)
for line in self.file:
nextpos = self.file.tell( )
yield line
self.file.seek( nextpos)


Since I was doing this as a self education excercise. When you say is
in use once and only once, you mean I can only use a single instance of
the class?

No. This works:

f1 = FileReIterable( "one.file")
f2 = FileReIterable( "another.fi le")
... free uses of ...

This does not "work":

gen = FileReIterable( "one.file")

for a in gen:
for b in gen:
print a, b

This does "work":

gen = FileReIterable2 ("one.file")

for a in gen:
for b in gen:
print a, b

That is, any instance of FileReIterable must not be used in a
context where it may be in the midst of iterating a file, gets
used to produce a result, and then must produce a result from
the original iteration.

If you think about what must happen to the file read pointer,
the reason for all of this should become clear.

--Scott David Daniels
sc***********@a cm.org


Thanks for the explanation, the issue of the file pointer was pretty
clear - it's why I created multiple files. I just misunderstood what
you meant by use only one. What I did miss at first was the fact that
the file object is not re-iterable. Just plain dumb oversite.

Of course in the end I'm actually more concerned with writing my own
iterators or generators. I was to busy thinking my errors were in the
recursion to look at the iterable/reiterable issue. This is a working
version of the die class I started this thread with.

class die(object):
def __init__(self,s ides):
self.sides=side s

self.next = 1
def next(self):
if self.next <= self.sides:
current = self.next
self.next +=1
return current
else:
self.next=1
raise StopIteration
def __iter__(self):
return self

May 31 '06 #15
In article <44********@nnt p0.pdx.net>,
Scott David Daniels <sc***********@ acm.org> wrote:

This works if-and-only-if it is only in use once at a time.
If you have multiple simultaneous accesses, you need to do
something like:

class FileReIterable2 (object):
def __init__(self, file):
if isinstance(file , basestring):
self.file = open(file, 'rU')
else:
self.file = file
def __iter__(self):
self.file.seek( 0)
for line in self.file:
nextpos = self.file.tell( )
yield line
self.file.seek( nextpos)


Hmm - I tried this with 'one.file' being just the lower case letters,
one per line:

class FileReIterable2 (object):
def __init__(self, file):
if isinstance(file , basestring):
self.file = open(file, 'rU')
else:
self.file = file
def __iter__(self):
self.file.seek( 0)
for line in self.file:
nextpos = self.file.tell( )
yield line
self.file.seek( nextpos)
gen = FileReIterable2 ("one.file")

for a in gen:
for b in gen:
print " ", a.strip(), b.strip()
gen = FileReIterable2 ("one.file")
for a in gen:
for b in gen:
print a.strip(), b.strip()

which didn't produce lines 'a a', 'a b', etc. It produced the single
line 'a a', then stopped. A judicious proint or two showed that after
the first execution of 'for line in self.file:', the file pointer was
at EOF, not at 2, as one would expect.

Rewriting the __iter__ method to not internally iterate over the file
object, as follows, works - it now generates
a a
....
a z
b a
....
z z
class FileReIterable2 (object):
def __init__(self, file):
self.file = open(file, 'rU')

def __iter__(self):
self.file.seek( 0)
while True:
line = self.file.readl ine()
if line == '': raise StopIteration
nextpos = self.file.tell( )
yield line
self.file.seek( nextpos)

--
Jim Segrave (je*@jes-2.demon.nl)

May 31 '06 #16
Jim Segrave wrote:
In article <44********@nnt p0.pdx.net>,
Scott David Daniels <sc***********@ acm.org> wrote:
class FileReIterable2 (object):
...
def __iter__(self):
self.file.seek( 0)
for line in self.file:
nextpos = self.file.tell( )
yield line
self.file.seek( nextpos)
Hmm - I tried this with 'one.file' being ... letters, one per line:

gen = FileReIterable2 ("one.file")
for a in gen:
for b in gen:
print a.strip(), b.strip()

which didn't produce lines 'a a', 'a b', etc. It produced the single
line 'a a', then stopped....

Oops. This works in Python 2.5 (and later) because the file.tell and
file.seek code are aware of the file iteration buffering. Since I am
trying to test all of my stuff on 2.5, that is what I am using by
default.
Rewriting the __iter__ method to not internally iterate over the file
object, as follows, works ....

class FileReIterable2 (object):
...
def __iter__(self):
self.file.seek( 0)
while True:
line = self.file.readl ine()
if line == '': raise StopIteration
nextpos = self.file.tell( )
yield line
self.file.seek( nextpos)


This fix does in fact provide working behavior for Pythons before 2.5.

--Scott David Daniels
sc***********@a cm.org
May 31 '06 #17

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

Similar topics

38
3698
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
3401
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
2016
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
5639
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
1140
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
3444
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
7693
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
2013
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
6371
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
9715
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
9595
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
9175
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
7642
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
5535
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...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4313
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
2
3835
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
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.