Alphabetic Triangle - Python

Asked

Viewed 163 times

-3

I have an exercise where, the enunciating informs the following:

The Latin alphabet is composed of letters, beginning with 'A' and ending with 'Z'. There are twenty-six different characters, if we disregard accents and differences between upper and lower case letters.

Harry, a very studious boy, realized that it is even possible to draw using letters. In one of the drawings, Harry writes in the first line of a sheet the first character of the alphabet, in the second line he writes twice the second character, in the third line writes three times the third character and so on. Harry realized that with this he can form an alphabetic triangle, similar to the one seen in Figure 1.

As Harry needs to study to perform a programming test (which for him is also a form of magic!), asked you to help him automate the designs of "alphabetic triangles", creating a program that receives as input an integer N (1 <= N <= 26) and drawing a triangle with exact N lines, following the same strategy described in the text.

ENTREE

An integer N (1 <= N <= 26).

EXIT

An alphabetic triangle with exact N lines and with the same construction strategy mentioned in the text. Note that the letters are always uppercase.

EXEMPLOS

What I’ve done so far as code was:

n = int(input())
x = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
x1 = []
for i in range(1, n+1):
    x1 = x.copy()
    print(f'{x1}')

However I cannot extract from the list and print the amount that is informed.

1 answer

0


Look, you only need the quantity variable, the alphabet list and a for to scroll through the list and display the letter at the same time. It looks like this:

vezes = int(input("Vezes: "))


alfabeto = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']


for i in range(vezes):
    print(alfabeto[i]*(i+1))

That way, typing it 4, for example, the result would be:

>>To BB CCC DDDD

Explaining the code, it works so -> defined the number of times, you already know the place of each letter in the alphabet, then alphabet[0] = 'A', alphabet[1] = 'B', and so on. So, you just need to access the letter and print it on the screen. In Python, you can multiply a variable string, then on for of the code when it’s in the letter 'A' (alphabet[0]), i = 0, you want 'A' to appear 1 time, then multiply by 1 (i+1), to 'B' (alphabet[1]), i = 1, multiply by 2 (i+1), and go.

That’s it... xD

  • Thank you very much! I always have doubts when referring to the list in python.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.