Draw triangle with repetition structure in Python

Asked

Viewed 456 times

2

I need to draw a triangle of the shape:

....1
...12
..123
.1234
12345

I should use repeating structures. From what I understood as a hint, I should use two concatenated structures. I’m a beginner and I’ve tried several times but it’s not coming off.

An example of what I tried:

n = int(input())

def triângulo2(n):
  
  s = ''
  i = n
  c = 1
  while i>=1:
    s = s + str('.')
    print(s)
    i = i-1
triângulo2(n)

2 answers

4


An alternative is to make a loop from 1 to n, increasing the number (adding the new digit at the end) and printing using the formatting options:

def triangulo(n):
    x = 0
    for i in range(1, n + 1):
        x = i + (x * 10)
        print(f'{x:.>{n}}')

triangulo(5)

At each iteration I multiply the number by 10 and add the new digit (thus, 1 becomes 12, which then becomes 123, etc).

To print I use .>{n}, that says to print the number on the right (>), occupying n positions and filling the missing spaces with the point.


Of course you can also make concatenating strings:

def triangulo(n):
    x = '1'
    pontos = '.' * (n - 1)
    for i in range(1, n + 1):
        print(f'{pontos}{x}')
        x += str(i + 1) # adiciona um dígito
        pontos = pontos[:-1] # remove um ponto 

triangulo(5)

But I find it unnecessary to keep creating so many strings (each iteration creates a new string for the "number" and another for the points), when some simple accounts and the use of formatting options already solve.

  • Very good! Thank you!!

0

Hello,
At first it may seem a little complex, but just use 2 Python list methods to help you.
What you need to do is create a list by filling it with the dots '.'
The 2 methods that will help you are . pop() that removes a specific position from a list (the last if nothing is passed) and . append() that will add an element to the end of the list. Understanding these 2 methods, you will easily be able to solve the problem.

lista = [1, 2, 3, 4, 5]

lista.pop(0)
# A lista agora eh: [2, 3, 4, 5]

lista.append(6)
# A lista agora eh: [2, 3, 4, 5, 6]

Another tip is to use the.pop(0) list in while! as a stop condition.

  • I didn’t know the pop, very good!

Browser other questions tagged

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