2

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
Toto
  • 89,455
  • 62
  • 89
  • 125
Parth
  • 64
  • 1
  • 5

3 Answers3

1

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
Drizzit12
  • 169
  • 2
  • 19
1

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 ?

MiH
  • 354
  • 4
  • 11
  • This doesn't give the right answer. Each line needs to start with the next letter in the alphabet, not always with a – Drizzit12 May 26 '21 at 02:49
  • hi @Drizzit12, apologies, misread the question, i've updated my codes, cheers! – MiH May 26 '21 at 02:57
1

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
blackraven
  • 5,284
  • 7
  • 19
  • 45