+ 1

Code Coach - It's a sign (Python)

Hello! I found out how to reverse the string but I don't know how to output "trash" if the while loop runs without output...is there a way for that? inp=input() words=inp.split() for i in words: x=len(i) back="" while x >= 0: back+=i[x-1] x-=1 if i == back: print("Open") else: continue

28th Jun 2023, 7:17 AM
Áron SzƱcs
Áron SzƱcs - avatar
7 Answers
+ 8
You can add a counter, if the counter remains zero by the end, then execute the print "trash" statement.
28th Jun 2023, 7:34 AM
Ausgrindtube
Ausgrindtube - avatar
+ 8
Your code has a problem right at the beginning, you are not accepting 4 inputs to test, only one. You will need a loop to generate 4 words, and store them in a list. Prove that first, then build a bit of code to test each word.
28th Jun 2023, 8:36 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 7
Áron SzƱcs , to check if a word is a palindrome (reading the same forward and backward) we can reverse the word and compare it to the not reversed word: ... if word == word[::-1]: # word is palindrome ... [::-1] is a slice that reverses strings and some other container types.
28th Jun 2023, 2:02 PM
Lothar
Lothar - avatar
+ 6
Áron SzƱcs You are getting closer. 👍 Your code now prints "Open" every time it sees a palindrome, which means that if you have more than one palindrome in a box, then your output will not meet task requirements
28th Jun 2023, 9:12 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
I tried it and solves 3 out of the 5 test cases... What can be the problem with the other 2? inp=input() words=inp.split() count=0 for i in words: x=len(i) back="" while x >= 0: back+=i[x-1] x-=1 if i == back: print("Open") count+=1 else: continue if count == 0: print("Trash")
28th Jun 2023, 7:41 AM
Áron SzƱcs
Áron SzƱcs - avatar
+ 2
Yeah right I forgot the input is always 4 different words... This code works in 4/5 test cases, what could be the trouble with it? word1=input() word2=input() word3=input() word4=input() inp=[word1,word2,word3,word4] count=0 for i in inp: x=len(i) back="" while x >= 0: back+=i[x-1] x-=1 if i == back: print("Open") count+=1 else: continue if count == 0: print("Trash")
28th Jun 2023, 8:53 AM
Áron SzƱcs
Áron SzƱcs - avatar
+ 2
I managed to solve it with the counter... Thanks to both of y'all! :)
28th Jun 2023, 9:33 AM
Áron SzƱcs
Áron SzƱcs - avatar