Home > Back-end >  How to write a simple python program that prints letters in ascending order?
How to write a simple python program that prints letters in ascending order?

Time:11-22

For example I would like to have:

a

. . .

z

aa

ab

. . .

az

bz

. . .

zz

aaa

and so on.

CodePudding user response:

Maybe try something like the following:

range(97,123) simply creates a range of numbers from 97 to 122, which converted to ASCII equates to a...z (done using chr())

So all our FUnction does, is it recieves a base string (starts with empty), prints out the base range of charachters and calls its self with base every charachter as the new base and depth decremented by 1

def printcharachters(base, depth):
    if depth > 0:
        for a in range(97, 123):
            print(base   chr(a))

        for a in range(97, 123):
            printcharachters(base   chr(a), depth - 1)



printcharachters("", 2)

Replace the depth with your desired depth (for 2 the last string would be zz for 4 it would be zzzz).

CodePudding user response:

Using more of standard library:

import itertools
import string


for i in range(1, 3): # Print items of length 1 and 2
    for prod in itertools.product(*(string.ascii_lowercase for _ in range(i))):
        print(''.join(prod))

What you describe is a sorted output of n-th powers of set {'a'...'z'} in terms of cartesian products in string format (cartesian power n of a set X is, from a simple point of view, a set of all possible tuples (x_1, ..., x_n) where all x_i are contained in X). itertools.product implements exactly cartesian product and outputs in order of presence, so just loop over them. string.ascii_lowercase is a simple string containing all letters a..z in natural order. This is fast (uses C implementation of itertools).

  • Related