list comprehension - Name error disappears on print in python -
i trying write code in python generate permutations of input string.
inp = raw_input() out = [inp[0]] in range(1,len(inp)): #print [range(len(j)+1) j in out] out = [j[:k]+inp[i]+j[k:] k in range(len(j)+1) j in out] print out
for input 'abc', outputs
traceback (most recent call last): file "perm.py", line 6, in
out = [j[:k]+inp[i]+j[k:] k in range(len(j)+1) j in out]
nameerror: name 'j' not defined
shell returned 1
if uncomment line 5, , code looks like
inp = raw_input() out = [inp[0]] in range(1,len(inp)): print [range(len(j)+1) j in out] out = [j[:k]+inp[i]+j[k:] k in range(len(j)+1) j in out] print out
for input 'abc', outputs
[[0, 1]]
[[0, 1, 2], [0, 1, 2]]
['cba', 'cab', 'bca', 'acb', 'bac','abc']
what sorcery this?
you have list comprehension loops front; need list them in nesting order left right, for j in out
needs come first
out = [j[:k]+inp[i]+j[k:] j in out k in range(len(j)+1)]
the print
statement list comprehension defined j
name version loop over; in python 2, list comprehension not have own scope for
loop target accessible after loop completes regular for
loop. has changed in python 3, list comprehensions own scope, dict , set comprehensions , generator expressions.
if helps, write out list comprehensions regular loops first; code did this:
tmp = [] j in out: tmp.append(range(len(j)+1)) print tmp out = [] k in range(len(j)+1): j in out: out.append(j[:k]+inp[i]+j[k:])
where range(len(j)+1)
expression only works because have used j
for
loop target in preceding expression building tmp
print
.
you may treating coding exercise, standard library includes function produces permutations: itertools.permutations()
:
from itertools import permutations inp = raw_input() print list(permutations(inp))
demo:
>>> itertools import permutations >>> list(permutations('abc')) [('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]
Comments
Post a Comment