Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why my Function isn't giving the required output

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The code has four 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)

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading