Questions about Python functions

Asked

Viewed 4,955 times

5

I am a beginner in the area of programming and I have doubts about the questions below. I will post the questions and my attempts (all are showing error in the broker). If anyone can help me already thank.

1 - Write the function Rectangle, printing the rectangles without padding, so that the characters that are not on the edge of the rectangle are spaces.

largura = int(input("Digite a largura: "))
altura = int(input("Digite a altura: "))
caractere = "#"


def retângulo(largura, altura, caractere):

    linha = caractere * largura

    for i in range(altura):
        print(linha)

retângulo(caractere, altura, largura)

2 - Write the function n_primos that takes an integer greater than or equal to 2 as a parameter and returns the number of primes that exist between 2 and n (including 2 and, where appropriate, n).

def èPrimo(x):
    fator = 2

    while x % fator !=0 and fator < x/2:
        fator = fator + 1
    if x % fator ==0:
        return False
    else:
        return True


def n_primos(n):

    lista_primos = []
    for i in range(2,n):
        if èPrimo(i):
            lista_primos.append(i);


    return len(lista_primos)

3 - Write a program that takes a sequence of integer numbers ending with 0 and prints all values in reverse order. (Show sequence vertically)

seq = []
num = 1


while True:
    num = int(input("Digite o número: "))
    if num == 0:
        break
    seq.append(num)
seq.reverse()
print(seq)
  • 1

    Okay, what are the mistakes for each?

  • She mentioned "broker" - it must be an automated broker, type "SPOJ": this type of program does not say which is the error - only says that "went wrong" same.

  • Hi Monica, welcome to SOPT. Your question is too wide. I suggest you open a question for each of your exercises (you can edit this and leave only one of them, and open new questions for the other two). Also, try to explore your difficulty: post the code as you did is great, but indicate and explain what is not working as expected.

  • Ah, and the first part of your question is duplicated this: http://answall.com/questions/178560/drawquadrado-na-tela-usando-bricks

  • 1

    Obg to all who have volunteered to help. I’m new aq at SOPT and I’m still getting used to how posts work. I saw the link that the friend posted, really is very similar to what I’m looking for. I believe I will be able to solve the problem there. Thanks.

  • @Monica - I restored the question to re0-include the doubts that Oce solved - after all, there was already an answer referencing them. When asking questions, as you identify errors, avoid editing the question itself - otherwise the answers become meaningless. (In this case it was something quite simple)

Show 1 more comment

4 answers

5


Your question is a little old, but come on.

Program 1

The first program has the following error:

def retângulo(largura, altura, caractere):
# ...
retângulo(caractere, altura, largura)

Note the parameters passed. They are in the wrong order! It should be retângulo(largura, altura, caractere).

The second problem is that you will paint a full rectangle, not just the edges. To fix this, the process is a little more complicated:

largura = int(input("Digite a largura: "))
print("")
altura = int(input("Digite a altura: "))
print("")
caractere = "#"

def retângulo(largura, altura, caractere):

    linha_cheia = caractere * largura
    if largura > 2:
        linha_vazia = caractere + (" " * (largura - 2)) + caractere
    else:
        linha_vazia = linha_cheia

    if altura >= 1:
        print(linha_cheia)
    for i in range(altura - 2):
        print(linha_vazia)
    if altura >= 2:
        print(linha_cheia)

retângulo(largura, altura, caractere)

The idea here is to compute linha_cheia which is the line with largura characters # and linha_vazia which is the line that has a largura - 2 spaces in the middle followed by a # and preceded by a #. Then I put a full line, altura - 2 empty lines and another full line.

Use the ifs to deal with special cases where the width could be too small for a line to have spaces in the middle or the height could be too small in case it could neither have one (or both) full lines at the beginning and at the end.

See here working on ideone.

Program 2

First of all, èPrimo should have been written as éPrimo. Or better yet, é_primo (see the Python naming conventions).

The second point is that in function n_primos, You don’t need to keep a list of cousins and then tell them how long the list is. Just go counting the elements that are cousins, without needing to store them.

The third point is that in the function é_primo, you don’t need to follow with the while until x / 2, just go to the square root of the x. A simple and easy way to know if you have reached the square root without having to invoke a function that calculates the square root is to use as a condition fator * fator <= x.

The fourth point is that you can put the if who has the return False within the while, and so you do not need to repeat the condition of % so much on the while how much in the if.

The fifth point is that in its function n_primo, you have to use n + 1 in his range instead of n. This is because the second parameter of the range would be the first value that is outside the range, not the last value that is inside it.

So here’s what your code looks like:

def é_primo(x):
    fator = 2
    while fator * fator <= x:
        if x % fator == 0:
            return False
        fator = fator + 1
    return True

def n_primos(n):
    contagem_primos = 0
    for i in range(2, n + 1):
        if é_primo(i):
            contagem_primos = contagem_primos + 1
    return contagem_primos

# Teste
for t in range(0, 100):
    print("p(" + str(t) + ") = " + str(n_primos(t)))

See here working on ideone. Obviously, the given test is not part of the program, it’s just to make sure it works.

Program 3

In this program here, the only thing missing is printing vertically. That’s easy, just iterate the sequence with a for and give a print in each element. Follow the code:

seq = []
num = 1

while True:
    num = int(input("Digite o número: "))
    if num == 0:
        break
    seq.append(num)
seq.reverse()
print("")
for i in seq:
    print(i)

See here working on ideone.

Concluding remarks

Some brokers don’t like to see strings like "Digite a largura: ", "Digite a altura: " and "Digite o número: " on output. If this is your case, just read from enter without telling the user using only input() and remove the lines you have only print("") programmes 1 and 3.

1

So that the square is fully filled by "#"

largura = int(input("Digite a largura: "))
print("")
altura = int(input("Digite a altura: "))
print("")
caractere = "#"

def retângulo(caractere, largura, altura ):

    linha_cheia = caractere * largura
    if largura > 2:
        linha_vazia = caractere + ("#" * (largura - 2)) + caractere
    else:
        linha_vazia = linha_cheia

    if altura >= 1:
        print(linha_cheia)
    for i in range(altura - 2):
        print(linha_vazia)
    if altura >= 2:
        print(linha_cheia)

retângulo(caractere, largura, altura)

0

Program 1: you fill the full rectangle filled, not with the inside of the blank rectangle

Program 2: Your check function does not test "n" number - will go wrong when n is prime.

Program 3: The statement asks to print "vertically" - I understand this as a number on each line - alone (no commas or other symbols)- you are printing the Python list - the list representation is in a single line and includes square brackets and commas.

  • Hello, the last two I managed to resolve, my doubt now is on the issue of the rectangle. My code shows all filled and what the exercise asks is to show only the edges and white spaces inside.

  • That - with the "if" command, and a bit of basic operations you should be able

  • Another thing- If the answer serves to fix parts of your problem - don’t erase the problems of the question - this platform files the questions and answers one without the other makes no sense.

  • Ah ok. I didn’t know, I tried to delete the last two to make the post more specific.

  • @Monica - tried to build its function that generates rectangle using the "if" command to try to make only the edges printed? The problem is simple, but around here we don’t like to give ready-made answers that will prevent people from learning. If you still have questions, create a new question with your attempts for the correct rectangle function.

0

On the rectangle, I did it this way:

largura = int(input('digite a largura: '))
altura = int(input('digite a altura: '))
l = 1 
a = 1 #Primeira linha
while a <= altura: #Primeira linha
   print('#' * largura, end = '') #Linha completa
   print() #Nova linha
   a = a + 1 #Sai da primeira linha
   while a > 1 and a < altura: #Começa linha vazada
      print('#' + ' ' * (largura - 2) + '#') #Linha vazada até a penúltima linha
      a = a + 1 #Passa pra nova linha. Quando chegar à última linha, sai do while interno e volta ao while externo imprimindo uma linha cheia.

This is the complete code that prints the hollow rectangle. To print only the full rectangle, remove the internal while.

  • If you remove the end = '' of the first print you won’t need to call her again with print() to break the line.

  • Well observed, Anderson. Obg.

Browser other questions tagged

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