![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Expert Programmer
|
Recursion: yield vs. return
I have been learning Python for a while now. I was browsing old posts in this forum and stumbled across this thread in which Arevos posted the following code:
def permutations(x):
if len(x) <= 1:
yield x
else:
for i in range(len(x)):
for p in permutations(x[:i] + x[i + 1:]):
yield [x[i]] + pAlso, I understand the gist of how this function works, but it is more complicated than most recursive functions I have studied. Could someone please explain how this particular function works, especially the last two lines? Thanks. |
|
|
|
|
|
#2 |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4
![]() |
The yield keyword turns a function into a generator. This allows a function to return more than once, and is typically used in for loops. For example:
def count_to_four():
yield 1
yield 2
yield 3
yield 4
for number in count_to_four():
print number1 2 3 4 As for the last two lines, it might make more sense if you understand that: x[:i] + x[i + 1:] permutations(x[:i] + x[i + 1:]) yield [x[i]] + p |
|
|
|
|
|
#3 |
|
Expert Programmer
|
Thanks, Arevos. I understand it now.
|
|
|
|
|
|
#4 |
|
Professional Programmer
Join Date: Feb 2005
Posts: 434
Rep Power: 4
![]() |
Neat generator example there, Arevos!
__________________
I looked it up on the Intergnats! |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|