I am trying to create a generator for permutation purpose.I know there are other ways to do that in python.But this is for somthing else. But I am not able to yield the values .Can you help?

```
def perm(s,p=0,ii=0):
l=len(s)
s=list(s)
if(l==1):
print ''.join(s)
elif((l-p)==2):
yield ''.join(s)
yield ''.join([''.join(s[:-2]),s[-1],s[-2]])
#print ''.join(s)
#print ''.join([''.join(s[:-2]),s[-1],s[-2]])
else:
for i in range(p,l):
tmp=s[p]
s[p]=s[i]
s[i]=tmp
perm(s,p+1,ii)
```

Your line `perm(s,p+1,ii)`

doesn't do anything, really: it's just like typing

```
>>> perm("fred")
<generator object perm at 0xb72b9cd4>
```

If you yield from that call, though, i.e.

```
for subperm in perm(s, p+1, ii):
yield subperm
```

Then you'd get

```
>>> list(perm("abc"))
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
>>> list(perm("abcd"))
['abcd', 'abdc', 'acbd', 'acdb', 'adbc', 'adcb', 'bacd', 'badc', 'bcad', 'bcda', 'bdac', 'bdca', 'cabd', 'cadb', 'cbad', 'cbda', 'cdab', 'cdba', 'dabc', 'dacb', 'dbac', 'dbca', 'dcab', 'dcba']
>>> len(_)
24
>>> len(set(perm("abcd")))
24
```

which looks okay. I haven't tested the code beyond that.

BTW, you can swap `s[i]`

and `s[p]`

with `s[i], s[p] = s[p], s[i]`

; no need for a `tmp`

variable.

PS: right now you don't handle the one-character case.

In a generator, any time you want to return a value you have to `yield`

. It's like you had a recursive factorial function that looked like this:

```
>>> def fact(n, result=1):
if n==0: return result
fact(n-1, result*n)
```

And then you wonder why it doesn't return anything:

```
>>> fact(5)
>>>
```

The reason is that the function is called recursively, but the value is lost. You'll want to do:

```
>>> def fact(n, result=1):
if n==0: return result
return fact(n-1, result*n)
>>> fact(5)
120
```

Analogously, in the recursive part of your algorithm you do:

```
for i in range(p,l):
tmp=s[p]
s[p]=s[i]
s[i]=tmp
perm(s,p+1,ii)
```

This doesn't `yield`

anything, though, so none of the values from the `perm(s,p+1,ii)`

call will be returned (EDIT: actually, none of them will even be computed). You'll want to iterate through the results of the recursive call and return each one in turn:

```
for i in range(p,l):
tmp=s[p]
s[p]=s[i]
s[i]=tmp
for result in perm(s,p+1,ii):
yield result
```

Similar Questions

I am trying to build a simple tree like structure of objects and identify the depth level of each object. To do this i have created a recursive function but this function always returns the last resul

I'm running into a memory error in one of my recursive function. def allPaths(self, adjMat, start, stop, flag=[0], walks=[]): walks = walks + [start] if start == stop: return [walks] loc = 0 flag=flag

I want to do a function that will return the factorial of a number in bash Here's the current code that doesn't work, can anyone tell me what's wrong and how to correct it? I just started learning bas

Given a canvas, let's say 10x10, and given 3 rectangles/squares. Canvas = 10x10 Rectangle 1 = 2x2 Rectangle 2 = 3x3 Rectangle 3 = 2x4 I've created a recursive function that loops every position of eve

I have a recursive function like this: public static int h(int n) { if (n == 0) { return 0; } if (n == 1) { return 1; } else { //variable value is a fixed one. i = value % 2; return h(n - h(i) - 1) +

I have a list of items and would like to generate all possible subsets. Therefore I'm using a recursive function with the item number and a list of all selected items as parameters. The function is ca

I have a recursive function, and I'm trying to figure out it's complexity. denote P(n) - the runtime of the function (when given the parameter n). I know that : P(n)=n+(n-1)*P(n-1) [p(1)=1] How can I

i'm writing a program in python with call a recursive function. It is somewhat like: def myfunction(list): if (base-case): # code to execute else: return [myfunction(list[0]), myfunction(list[1])] Wh

I have the following recursive function: $cogs = array('hello', 'how', 'are', 'you'); $wheels = array(); foreach($cogs as $cog) { $wheels[] = array($cog); } function recursive($placement){ $counter =

This question already has an answer here: Python recursion with list returns None 1 answer I am not understanding how recursion works. The base case runs last, and yet the return value is None.

As a Clojure newbie, I'm bothered with this small problem: I would like to iterate through a sequence and execute a split, and then a str (concatenation) function over the sequence elements. Here is m

I'm trying to create a recursive function that adds all the digits in a number. Here's what I've come up with: def sumOfDigits(num): num=str(num) if len(num)==0: return 0 elif len(num)==1: return int(

I need to write a cumulative summation function in R but I've been hitting a brick wall. The function has the following structure: a*x1 a*x2 + a^2*x1 a*x3 + a^2*x2 + a^3*x1 a*x4 + a^2*x3 + a^3*x2 + a^

I'm using a recursive function to sort a list in Python, and I want to keep track of the number of sorts/merges as the function continues. However, when I declare/initialize the variable inside the fu

Possible Duplicate: The Python yield keyword explained Okay, I've probably phrased the question badly but this is the situation I have. I have this line of code in Python 2.7 which I'm trying to und

i have a SQL that using a recursive CTE to expand a self-referancing employees table builds a result set of defects aggregated by user and severity level. here is my CTE: ALTER FUNCTION [dbo].[fnGetE

I am new to python and trying to learn. I am trying to implement a simple recursive grep using python for processing and here is what I came to so far. p = subprocess.Popen('find . -name [ch]', shell

I'm trying to create a recursive function in coldfusion and am coming across some issues. Here is the logic I have: <cffunction name=getEvents access=private> <cfargument name=strtdate

There are a lot of good getattr()-like functions for parsing nested dictionary structures, such as: Finding a key recursively in a dictionary Suppose I have a python dictionary , many nests https://g

I was playing with the fibonacci sequence in Python (I know the implementation with yield, but wanted to implement it with recursion) and ended up with the following code snippet: def fib(start, leng)

I've problem returning value from recursive function. def ask_question(question) print question answer = STDIN.gets.chomp ask_question question if answer.empty? return answer end The first time the

I have an AppleScript script that runs a recursive function that counts instances of inserted plugins. After each plugin that is inserted the function checks the CPU and decides whether there's a CPU

I'm watching the sicp lectures, In video 1b, sussman calls algo 1 iterative. He says method 2 is recursive. From my understanding both are recursive algorithms. How can I best think of method 1? As an

I have a class model designed for a person class in python. where a person is a student and can have 0,1 or many advisors.A person can also have other attributes like name,school,year of graduation,cl

I have a question regarding converting a yield statement to a generator expression So I have this small yield method that gets a function and a starting number as its inputs, and basically calls the f

I don't understand recursive functions. I wrote this code to help me but i don't understand why it works the way it does. It prints backwards the steps from 0 to the number n/2 i input but don't know

Mathematica can solve recursive equations using RSolve. Is it possible to have a function defined by a recurrence, regardless whether the recurrence can or cannot be solved analytically?

I want to write a recursive function in joomla that get all the child level categories using a category id using joomla's jmodel's db object.Following is my code that I have written: function getChil

I havent done any classic ASP for a couple of years and now trying to get back into it from c# is prooving impossible! I've got a recursive function which very simply is supposed to query a database b

I have an exception class called Exception, and I'm invoking a recursive function which gets called approximately 200 times while looping through a map. RecursiveFunction() is part of a class that con

I'm using SQL Server 2008. I want to execute an ALTER on a recursive function. The alter adds parameters, it seems to choke on that. The function has no dependencies so I can safely do a DROP+CREATE,

I have a C++/Obj-C background and I am just discovering Python (been writing it for about an hour). I am writing a script to recursively read the contents of text files in a folder structure. The prob

I have written a function in python 2.7 that caluclates the digit sum of a given number: def dig_sum(n): s = 0 while n: s = s + n % 10 n = n/10 return s and now tries to rewrite it as a recursive fun

How can I call a function from inside the function, so it becomes recursive? Here is my code, I have added a comment where I would like to start the recursion: $('a.previous-photos, a.next-photos').cl

Should a Python generator raise an exception when there are no more elements to yield? Which one?

i have a piece of code like this class Program { static IEnumerable<string> GetSequences(string a) { yield return a; GetSequences(a + >); } static void Main(string[] args) { foreach (var n

I have the following task: Write a program that asks for a number and a power. Write a recursive function that takes the number to the power. For example, if the number is 2 and the power is 4, the

I'm starting to study the Scala programming language. I've some grasp of FP languages like Erlang and Haskell and I have a doubt about the meaning of the for/yield expression, like: for (arg <- arg

The following is a recursive function: (defn make-control-data [it alphabet] {:pre [(integer? it) (pos? it)]} (let [shuffled-alphabet-string (reduce str (shuffle alphabet))] (if (zero? it) shuffled-al

I am working on a program which works with a recursive function. My problem is when the work of the recursive function is complete, and control is transferred to next function, it returns back to recu

I am trying to design a function that essentially does as follows: String s = BLAH; store the following to an array: blah lah bah blh bla bl ba bh ah al So basically what I did there was subtract ea

This function must count the number of nodes in a binary tree. Tree contains more than 1000 nodes, and the number of recursive calls supposedly to be the same, but the value of the variable 'count' is

I am a Physics intern at TCD. My summer project is to write a Python code that searches, in a random packing, for ratthers i.e. particles that have a number of contacts with other particles at most

I have a simple html structure that I need to traverse. For some reason my recursive function returns 'undefined' on any nested nodes, but not for parent nodes. Unfortunately this needs to be native j

I basically want to have a function which is GET'ing a page and then returns a result based on that, this leads to the following problem: All GET methods are using a callback function, meaning that th

i use kohana framework and i am trying to code recursive function to create category tree. My Categories Table id int(11) NO PRI NULL auto_increment name varchar(50) NO NULL parent_id int(11) NO NULL

I have a function that yields 2 parts of a list: >>> x = [1,2,3,4,5,6] >>> def fold(ls): ... for i in range(0,2): ... yield x[:i] ... yield x[i:] ... I understand that it still retu

Hello fellow programmers. For some time now, recursive programming have been one of the things i understand the least. Because of that i decided, that i needed to use some time, understanding and prog

Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument I made this function: def test(num,v=[]): v.append(num) if num == 10: return v return test(num+1,v) When I use it, t

Excel's add-in named Analysis ToolPak provides Yield function for calculation of yield on security that pays periodic interest. Function works well and returns proper data. My understanding is fun