why my Function isn't giving the required output

Question:

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?

Asked By: Hazem Majeek

||

Answers:

The code has five issues:

  1. 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.

  2. 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:

  3. In def gen2(n):, the input parameter n can be removed because it is not used inside the code. You can write def gen2():

  4. 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)

  5. 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()
Answered By: C-3PO
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.