Reputation: 19
I'm trying to write a program that generates all two-character combinations of the alphabet from 'a' to 'z', and if the permutations include both 'x' and 'z', print them and break
import itertools
def gen2(n):
alplist = list(map(chr,list(range(ord('a'),ord('z')+1))))
for combi in itertools.product(alplist,*([alplist] * 2)):
return gen2(2)
if "x" and "z" in combi:
print(combi)
break
But I'm not getting an output what can be the problem?
Upvotes: 0
Views: 54
Reputation: 1213
The code has five issues:
return gen2(2)
inside the main for-loop
prevents the execution of the code. Also this freezes the code, since the recursive calls are nested indefinitely.
if "x" and "z" in combi:
does not work properly. Python will interpret this as only if "z" in combi:
because "x"
is always defined as a non-empty variable, and thus "x"
is evaluated as True
. You need to write if "x" in combi and "z" in combi:
In def gen2(n):
, the input parameter n
can be removed because it is not used inside the code. You can write def gen2():
The issue with the length of the string is caused by itertools.product(alplist,*([alplist] * 2))
. If you want 2 characters, you need to write itertools.product(alplist, repeat = 2)
. (credits to @John Coleman for the improved syntax)
list(map(chr,list(range(ord('a'),ord('z')+1))))
is the same as string.ascii_lowercase
. (credits to @John Coleman)
The corrected code is:
import itertools
import string
def gen2():
for combi in itertools.product(string.ascii_lowercase, repeat = 2):
if "x" in combi and "z" in combi:
print(combi)
break
gen2()
Upvotes: 1