Alphabetical Grid using python3

Viewed 543

how to write a function grid that returns an alphabetical grid of size NxN, where a = 0, b = 1, c = 2.... in python

example :

a b c d
b c d e
c d e f
d e f g

here I try to create a script using 3 for loops but it's going to print all the alphabets

def grid(N):
    for i in range(N):
        for j in range(N):
            for k in range(ord('a'),ord('z')+1):
                print(chr(k))
    pass
3 Answers

Not the most elegant, but gets the job done.

import string

def grid(N):
    i = 0
    for x in range(N):
        for y in string.ascii_lowercase[i:N+i]:
            print(y, end=" ")
        i += 1
        print()

grid(4)

Output

a b c d
b c d e
c d e f
d e f g

You have specified for k in range(ord('a'),ord('z')+1) which prints out the entire series from 'a' to 'z'. What you probably need is a reference list comprehension to pick your letters from, for example

[chr(x) for x in range(ord('a'),ord('z')+1)]

Try this:

letters = [chr(x) for x in range(ord('a'),ord('z')+1)]

def grid(N):
    for i in range(N):
        for j in range(i, N+i):
            print(letters[j], end=' ')
            if j==N+i-1:
                print('')   #to move to next line

grid(4)

Output

a b c d 
b c d e 
c d e f 
d e f g 

Do you need to add a check for N<=13 ?

Extending from @MichHeng's suggestion, and using list comprehension:

letters = [chr(x) for x in range(ord('a'),ord('z')+1)]

def grid(N):
    for i in range(N):
        print(' '.join([letters[i] for i in range(i,N+i)]))

grid(4)

output is

a b c d
b c d e
c d e f
d e f g
Related