You are not printing string

Asked

Viewed 71 times

-3

Good morning, someone can help me?

It is intended to develop the function invert_pal(st) it takes as parameter a string st and returns as a result the same string in which each word was inverted.
For example, invert_pal(“Eu gosto de programar”) should return the string “uE otsog ed ramargorp”.
In the resolution of this exercise you must use a stack (can consider the existence of the stack class not needing to develop it).

Lf= []
st= (input ("Introduza a palavra: "))
L= list (st)
class Stack:
    def __init__(self):
        self.items = []
        
    def isEmpty(self):
        return self.items == []
    
    def push(self, item):
        self.items.append(item)
        
    def pop(self):
        return self.items.pop()
    
    def top(self):
        return self.items[len(self.items)-1]
    
    def size(self):
        return len(self.items)

def invert_pal ():
    inverter= Stack ()
    for i in L:
        inverter.push(i)
    while not inverter.isEmpty():
        y= inverter.pop()
        Lf.append(y)
    print (str(Lf))
                
a= invert_pal()
print (a) 
  • On the last lines, you display the variable a, which is the return of invert_pal, but the function has no return. This doesn’t seem right.

3 answers

1

From what I understand, you want to implement a script that is able to receive a Frase and return this phrase with the letters of each word reversed, that is, receive "I like programming" and return "ue otsog ed ramargorp".

One of the most efficient ways to solve this problem is by using lists. For this we can use the following code:

def invert_pal(fra):
    return [i[::-1] for i in fra]


frase = input('Digite a frase desejada: ').split()

print(*invert_pal(frase))

Note that when we run this script we receive the following message: Digite a frase desejada: . At this point we must enter the full sentence and press Enter. Then this phrase will be stored in a list, the same being passed as parameter to the function invert_pal(fra). Once there, this list will be reassembled, in which every word of it will be reversed.

NOTE: The reversal of words is executed through the list comprehension in the following code:

[i[::-1] for i in fra]

What this code is doing? This code is going through each of the elements on the list fra and reversing their letters, i.e., reassembling each of the words with their reversed letters.

Finally, the return of the function will be displayed. Return this formed by the unpacking of the list formed by the words reversed.

Testing the code:

When executing the code, we type...

Eu gosto de programar

... and press Enter. Then we will receive as a result:

uE otsog ed ramargorp
  • Very good your code but I believe that the split() could be embedded in the invert_pal function()

1

Every time you solve a problem first thing you should do is decode the proposed message for the purpose of finding out what is being required. In this process do not be afraid to highlight the text in search of information you consider relevant.

The function development invert_pal(st) that receives as parameter a string st and return as result the same string in which every word got the letters reversed.
For example, invert_pal(“Eu gosto de programar”) should return the string “uE otsog ed ramargorp”.
In resolving this exercise you must must use a stack (can consider the existence of the stack class not needing to develop it).

Then we can identify the following requirements:

  • The goal is function development invert_pal().
  • invert_pal() should receive as a parameter a string st.
  • The return of invert_pal(st) must be the string st inverted.
  • The inversion should be done by means of a stack(stack).
  • irrelevance in the implementation of the stack.

Knowing the requirements it is possible to conclude that the focus should be the construction of the function invert_pal() which must receive a string st and must operate by means of a battery this parameter string st so that the result of such an operation must be string st reversed and that this is the return of invert_pal(st).

#Define a função invert_pal dotada de um parâmetro st, evitando o uso de variáveis globais.
def invert_pal(st):
    pilha = Stack()                     #Cria-se uma pilha que receberá os caracteres de st.
    resultado = []                      #Cria-se uma lista que receberá os caracteres desempilhados da pilha.
    #Para cada caractere da entrada st...
    for c in st:
        pilha.push(c)                   #...empilhe dado caractere.
    #Enquanto a pilha não estiver vazia...
    while not pilha.isEmpty:
        resultado.append(pilha.pop())   #...desempilhe os caracteres da pilha em resultado
    #Junte todos os caracteres do resultado em uma string e a retorne.
    return "".join(resultado)           

Joining the function invert_pal(st) in a testable example:

#Como o exercício não determinou uma implementação específica para a pilha decidi
# a implementar não como uma fachada para um objeto List mas como uma derivação dessa classe 
# evitando assim a reimplementação desnecessária de métodos, ex: pop(). 
class Stack(list):
    @property
    def isEmpty(self):              #Retorna True se a pilha estiver vazia.
        return self.size == 0
    
    @property
    def top(self):                  #Não foi utilizada na resolução. Retorna o topo da pila sem remover.
        return self[-1]
        
    @property
    def size(self):                 #Devolve o tamanho da pilha.
        return len(self)
    
    def push(self, item):           #Empilha um item.
        self.append(item)

def invert_pal(st):
    pilha = Stack()
    resultado = []
    for c in st:
        pilha.push(c)
    while not pilha.isEmpty:
        resultado.append(pilha.pop())
    return "".join(resultado)
                
a = invert_pal(input("Introduza a palavra: "))
print(a) 

Resulting:

Introduza a palavra: Eu gosto de programar
ramargorp ed otsog uE

0

1-The invert_pal function must return the string the other way using Return, but: In the last lines, you display the variable a, which is invert_pal return, but the function has no return

Code:

Lf= []
st= (input ("Introduza a palavra: "))
L= list (st)
class Stack:
    def __init__(self):
        self.items = []
        
    def isEmpty(self):
        return self.items == []
    
    def push(self, item):
        self.items.append(item)
        
    def pop(self):
        return self.items.pop()
    
    def top(self):
        return self.items[len(self.items)-1]
    
    def size(self):
        return len(self.items)

def invert_pal ():
    inverter= Stack ()
    for i in L:
        inverter.push(i)
    while not inverter.isEmpty():
        y= inverter.pop()
        Lf.append(y)
    print (str(Lf))
    return str(Lf)
                
a= invert_pal()
print (a) 

Browser other questions tagged

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