[Tutor] recursion
Peter Otten
__peter__ at web.de
Fri Feb 5 04:39:19 EST 2016
Ben Finney wrote:
> Alan Gauld <alan.gauld at btinternet.com> writes:
>
>> On 05/02/16 02:03, noopy via Tutor wrote:
>>
>> > def permutations(items):
>> > n = len(items)
>> > if n==0: yield []
>> > else:
>>
>> I assume this bit is clear enough?
>
> I think it would be clearer without the needless opaque name ‘n’.
> Better::
>
> def permutations(items):
> if not items:
> # ‘items’ is empty (or is not a container).
> yield []
> else:
> for i in range(len(items)):
> …
>
> Binding a name that is used exactly once should be done only if the name
> clarifies the purpose. An opaque name like ‘n’ is not helpful.
While you're at it you can also throw out the range(len(...)) construct:
>>> def p(items):
... if items:
... for i, item in enumerate(items):
... for cc in p(items[:i] + items[i+1:]):
... yield [item] + cc
... else:
... yield []
...
>>> list(p("xyz"))
[['x', 'y', 'z'], ['x', 'z', 'y'], ['y', 'x', 'z'], ['y', 'z', 'x'], ['z',
'x', 'y'], ['z', 'y', 'x']]
More information about the Tutor
mailing list