Hi, I am trying to find all lists of length x with elements a, b, and c.
To this end, I have created the class below, but it is not quite working and
I am having trouble figuring out what to change. Does anyone have any
insight?
class c:
def __init__(self):
self.traits = 4 # number of list elements
self.types = 3 # elements can be 0, 1, or 2
def a(self):
l = []
for i in range(self.trai ts):
l.append(self.b (str(i)))
return l
def b(self, s):
if len(s) == self.types:
return s
for i in range(self.trai ts):
return self.b(s + str(i))
i = c()
lst = i.a()
Thanks in advance,
d 20 3167
"drs" <dr*@removetosendmailecpsoftware.com > wrote in message
news:Gp******** ***********@twi ster.nyroc.rr.c om...
I didn't state what I am doing quite so clearly (or correctly), so I'll try
again. I am looking for a list of all unique strings of length x whose
elements are from the set a, b, and c.
So, for example, in this case it would be
aaa, aab, aac, aba, abb, abc, aca, acb, acc, ... cca, ccb, ccc
but I need for the length and the number of elements to be variable.
I understand this will get out of hand very quickly for large numbers, but I
only need it for small length/numbers.
Thanks,
d
drs <drs <at> removetosendmailecpsoftware.com > writes: Hi, I am trying to find all lists of length x with elements a, b, and c.
I'm not sure exactly what you're looking for here. It would help if you gave an
example of some input and the output you want to produce.
Seems you might be looking for the permutations of a list. If so, check the
ASPN Cookbook: http://aspn.activestate.com/ASPN/Coo.../Recipe/190465
If this is not what you're looking for, please give us a little more info on the
problem.
Steve
drs <drs <at> removetosendmailecpsoftware.com > writes: I am looking for a list of all unique strings of length x whose elements are from the set a, b, and c.
So, for example, in this case it would be
aaa, aab, aac, aba, abb, abc, aca, acb, acc, ... cca, ccb, ccc
but I need for the length and the number of elements to be variable.
Much clearer, thanks. Is this what you're looking for: def f(chars, n):
.... for char in chars:
.... if n == 1:
.... yield char
.... else:
.... for string in f(chars, n1):
.... yield char + string
.... list(f('abc', 1))
['a', 'b', 'c'] list(f('abc', 2))
['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] list(f('abc', 3))
['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa', 'bab',
'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba',
'cbb', 'cbc', 'cca', 'ccb', 'ccc']
Steve
drs <drs <at> removetosendmailecpsoftware.com > writes: I am looking for a list of all unique strings of length x whose elements are from the set a, b, and c.
Does anyone know what this operation is called? It's not permutations or
combinations as I understand them since permutations and combinations do not
allow repetition. I assume there was already a solution for this somewhere, but
I didn't know what term to google for.
Thanks,
Steve
Steven Bethard <st************ @gmail.com> wrote: drs <drs <at> removetosendmailecpsoftware.com > writes: I am looking for a list of all unique strings of length x whose elements are from the set a, b, and c.
Does anyone know what this operation is called? It's not permutations or combinations as I understand them since permutations and combinations do not allow repetition. I assume there was already a solution for this somewhere, but I didn't know what term to google for.
There's been a recent thread where the OP called them 'permutations',
somebody commented they're 'variations'. In that thread you'll find a
bazillion solutions, recursive and non, with or without itertools, &c.
Alex
In article <ma************ *************** ***********@pyt hon.org>,
Steven Bethard <st************ @gmail.com> wrote: drs <drs <at> removetosendmailecpsoftware.com > writes: I am looking for a list of all unique strings of length x whose elements are from the set a, b, and c.
Does anyone know what this operation is called? It's not permutations or combinations as I understand them since permutations and combinations do not allow repetition. I assume there was already a solution for this somewhere, but I didn't know what term to google for.
The task you're describing is generation of all strings over a given
alphabet. Fortunately, there is a fairly simple technique for doing
this  here is a Python generator to do it:
def lexgen(alph, maxlen = None):
"""Generate all the possible strings over the given alphabet in
lexicographic order. Stop after generating the strings of maxlen,
if provided; otherwise, generate forever."""
ixs = []
while maxlen is None or len(ixs) <= maxlen:
while True:
yield str.join('', [ alph[ixs[x]] for x in
xrange(len(ixs)  1, 1, 1) ])
for pos in xrange(len(ixs) ):
ixs[pos] = (ixs[pos] + 1) % len(alph)
if ixs[pos] <> 0:
break
if sum(ixs) == 0:
break
ixs += [0]
Cheers,
M

Michael J. Fromberger  Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/  Dartmouth College, Hanover, NH, USA
Michael J. Fromberger <Mi************ ******@Clothing .Dartmouth.EDU>
wrote:
... I am looking for a list of all unique strings of length x whose elements are from the set a, b, and c.
... The task you're describing is generation of all strings over a given alphabet. Fortunately, there is a fairly simple technique for doing this  here is a Python generator to do it:
def lexgen(alph, maxlen = None): """Generate all the possible strings over the given alphabet in lexicographic order. Stop after generating the strings of maxlen, if provided; otherwise, generate forever."""
ixs = []
while maxlen is None or len(ixs) <= maxlen: while True: yield str.join('', [ alph[ixs[x]] for x in xrange(len(ixs)  1, 1, 1) ])
for pos in xrange(len(ixs) ): ixs[pos] = (ixs[pos] + 1) % len(alph) if ixs[pos] <> 0: break
if sum(ixs) == 0: break
ixs += [0]
Nice, and different from what was offered in the other recent thread
(and from what the OP asked for) since you generate all strings of
length up to maxlen, while the request was for just those of length
exactly x. Still, this can easily be restricted, and maybe a few
Pythonic tweaks with it...:
def lexgen_n(alph, x):
ixs = [0] * x
while True:
yield ''.join([alph[i] for i in ixs[::1]])
for pos in xrange(x):
ixs[pos] += 1
if ixs[pos] < len(alph):
break
ixs[pos] = 0
else:
break
the 'else: break' at the end executes if the for terminates normally
(this makes it needless to test sum(ixs), or max(ixs), again).
In 2.4 one can do a bit better for the yield, with
yield ''.join(alph[i] for i in reversed(ixs))
[generator expression vs list comprehension, and reversed builtin vs
reversal by slicing]. Of course, instead of reversing in the yield, one
can reverse in the for  so in 2.4 one might have (variant...):
yield ''.join(alph[i] for i in ixs)
for pos in reversed(xrange (x)):
...
or, after a 'from itertools import imap':
yield ''.join(imap(al ph.__getitem__, ixs))
It's important to remember that Python does no constantexpression
hoisting; there may be important efficiencies in hoisting constants
oneself (that len(alph) in the inner loop, for example). E.g, sticking
to 2.4 (what one should use if one cares for speed anyway), another
variant:
def lexgen_n(alph, x):
# hoistings for speed
from itertools import imap
getalph = alph.__getitem_ _
lenalph_m1 = len(alph)  1
# and now, to work
ixs = [0] * x
while True:
yield ''.join(imap(ge talph, reversed(ixs)))
for pos, ix in enumerate(ixs):
if ix == lenalph_m1:
ixs[pos] = 0
else:
ixs[pos] = ix + 1
break
else:
break
Alex
Steven Bethard <st************ @gmail.com> wrote: Does anyone know what this operation is called? It's not permutations or combinations as I understand them since permutations and combinations do not allow repetition. I assume there was already a solution for this somewhere, but I didn't know what term to google for.
 al*****@yahoo.c om (Alex Martelli) wrote: There's been a recent thread where the OP called them 'permutations', somebody commented they're 'variations'. In that thread you'll find a bazillion solutions, recursive and non, with or without itertools, &c.

(1) "Variation" is the same as "permutatio n". It's matter of
semantics. Some people use the notation V(n, k), some people use the
notation P(n, k). For people that use the term "variation" , the term
"permutatio n" is reserved for the special case V(n, n). Neither name
is right for the original question.
(2) I too googled for the name of the operation of the original
poster. One name I found is "string" (see http://mathworld.wolfram.com/BallPicking.html). However, this name may
not be universally recognized.
(3) The functional version would be:
strings = lambda Xs, k: reduce(lambda r, i: [p + x for p in r for x
in Xs], range(k), [''])
print strings('abc', 2)
Hung Jung
Hung Jung Lu wrote: ... The functional version would be:
strings = lambda Xs, k: reduce(lambda r, i: [p + x for p in r for x in Xs], range(k), [''])
Wow! Grand prize for elegance. :) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics 
by: Jakle 
last post by:
Hi all. Need alittle help here. This is an example from "How to Think Like a
Computer Scientist: Learning with Python, Chapter 5". It's an open source
ebook, so if you feel like it you can find it here:
http://www.ibiblio.org/obp/thinkCSpy/
The example uses factorials to explain more complex recursion.
"Explanation From the Book Begins Here"++++++++++++++++++
>def factorial(n):

by: MetalOne 
last post by:
I am trying to write a generator function that yields the index position
of each set bit in a mask.
e.g.
for x in bitIndexGenerator(0x16): #10110
print x
> 1 2 4
This is what I have, but it does not work.
Changing yield to print, shows that the recursion works correctly.

by: Dan 
last post by:
I've encountered some strange behavior in a recursive procedure I'm
writing for a bill of materials. First let me ask directly if what I
think is happening is even possible:
It seems like the procedure is not following the recursion in serial
order, but in parallel. In other words, after one instance of the
procedure calls itself, it continues executing lines below the
recursion before the recursion is done. Is that possible? I...

by: Chris Thomasson 
last post by:
Here is a "simple" method for using the preprocessor to generate code via.
recursion... What do you think of my experimental recursion implementation?
Can you compile it?
Any comments are welcome...
;)
http://appcore.home.comcast.net/appcore/src/ppmetarecurse.c

by: Josiah Manson 
last post by:
In the following program I am trying to learn how to use functional
programming aspects of python, but the following program will crash,
claiming that the recursion depth is too great. I am attempting to make
a list of polynomial functions such that poly(3) = 1, poly(3) =
3, poly(3) = 9, etc. Could someone point me in the right direction?
Thanks.
def make_polys(n):
"""Make a list of polynomial functions up to order n.
"""
 
by: mdeni 
last post by:
I am sorry if this was allready asked or discussed, please redirect me.
I have to make the program of postorder traversal of the binary search tree NOT using recursion. I have found many solutinos using recursion but I can't figure 1 without recursion. Can you help me and tell me the code? Please.
With recursion:
void postorder(struct node *bt)
{
if(bt!=NULL)
{
postorder(bt>left);
postorder(bt>right);

by: NOO Recursion 
last post by:
Hi everyone! I am trying to write a program that will search a 12x12 for a
thing called a "blob". A blob in the grid is made up of asterisks. A blob
contains at least one asterisk. If an asterisk is in a blob, an asterisk
that is contiguous to it is in the same blob. If a blob has more than two
asterisks, then each asterisk in the blob is contiguous to at least one
other asterisk in the blob. For example this 12x12 grid has 6 blobs. ...

by: Mumia W. 
last post by:
Hello all.
I have a C++ program that can count the YOYOs that are in a grid of
Y's and O's. For example, this
Y O Y O O Y
O Y O Y O O
Y O Y Y O Y
O Y O O Y O
O Y Y O Y O

by: nishit.gupta 
last post by:
Can somebody please help me for algorithm for postorder bst traversal
without recursion.
It should use stack. i am not able to implement it.
thnx

by: Jeff Bigham 
last post by:
So, it appears that Javascript has a recursion limit of about 1000
levels on FF, maybe less/more on other browsers.
Should such deep recursion then generally be avoided in Javascript?
Surprisingly, deep recursion actually isn't that slow for what I'm
doing. Programming this task recursively is so much more
straightforward to me, but currently I'm forced to use an ugly hack to
avoid going over the 1000 level limit. Of course, it could...

by: Oralloy 
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bitfields 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...
 
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...

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,...

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, ZWave, WiFi, 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...

by: agi2029 
last post by:
Let's talk about the concept of autonomous AI software engineers and nocode 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...

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...

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();...
 
by: muto222 
last post by:
How can i add a mobile payment intergratation into php mysql website.

by: bsmnconsultancy 
last post by:
In today's digital era, a welldesigned 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...
 