'Python Grok learning and decoding a messsage
Grok learning was being very picky today. So I was working on this question:
People pass messages to other people in a certain code: They read the words in reverse order They only pay attention to the words in the message that start with an uppercase letter.
So a code like this: "BaSe fOO ThE AttAcK" would be decripted into "attack the base", this is because 1. Reading in the reverse order (AttAck ThE fOO BaSe) and 2. Only pay attention to the words that start with an uppercase letter (AttAck ThE BaSe). Then use .lower() to turn in all into lower case.
This is the code I used:
code = input('code: ')
code = code.split()
decoded = ''
last_index = len(code) - 1
for i in range(last_index, -1, -1):
while code[i][0] == code[i][0].upper():
decoded = decoded + code[i] + ' '
break
print(f'says: {decoded.lower().rstrip()}')
Everything seemed to work (Grok told me I passed 5 / 6 criterias) but when I type in only punctuation e.g. "!!!", my code (above) returns "!!!" but Grok requires the code to return a blank space.
Thank you very much. (I was working on an assignment and I couldn't find answers anywhere.)
Solution 1:[1]
Your construct
while ...:
...
break
makes no sense. You have to use if instead:
if ...:
...
About the main problem: You're not checking, if the first letter of a word is a character of the alphabet. That's why ! is accepted as a legal character. The classic solution for pattern matching is using regular expressions:
import regex as re
code = "BaSe fOO ThE AttAcK !!!"
code = code.split()
decoded = ''
last_index = len(code) - 1
for i in range(last_index, -1, -1):
if re.match("[A-Z]", code[i][0]):
decoded = decoded + code[i] + ' '
print(f'says: {decoded.lower()}')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Florian Metzger-Noel |
