Hello guys I’m trying to write a program that generate 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?
>Solution :
The code has four issues:
-
return gen2(2)inside the mainfor-loopprevents 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 onlyif "z" in combi:because"x"is always defined as a non-empty variable, and thus"x"is evaluated asTrue. You need to writeif "x" in combi and "z" in combi: -
In
def gen2(n):, the input parameterncan be removed because it is not used inside the code. You can writedef 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 writeitertools.product(alplist, repeat = 2). (credits to @John Coleman for the improved syntax)
The corrected code is:
import itertools
def gen2():
alplist = list(map(chr,list(range(ord('a'),ord('z')+1))))
for combi in itertools.product(alplist, repeat = 2):
if "x" in combi and "z" in combi:
print(combi)
break
gen2()