简体   繁体   English

Python Grok 学习和解码消息

[英]Python Grok learning and decoding a messsage

Grok learning was being very picky today.今天的 Grok 学习非常挑剔。 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).所以像这样的代码:“Base fOO The AttAcK”会被描述为“attack the base”,这是因为 1. 以相反的顺序读取 (AttAck ThE fOO Base) 和 2. 只注意开头的单词一个大写字母 (AttAck The Base)。 Then use .lower() to turn in all into lower case.然后使用.lower()将全部转为小写。

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 eg ",.!", my code (above) returns "!!!"一切似乎都正常(Grok 告诉我我通过了 5 / 6 个标准)但是当我只输入标点符号时,例如“,.!”,我的代码(上面)返回“!!!” but Grok requires the code to return a blank space.但是 Grok 要求代码返回一个空格。

Thank you very much.非常感谢你。 (I was working on an assignment and I couldn't find answers anywhere.) (我正在做一项作业,但在任何地方都找不到答案。)

Your construct你的构造

while ...:
    ...
    break

makes no sense.没有意义。 You have to use if instead:您必须改用if

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()}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM