相互检查字符串(字谜)

编程入门 行业动态 更新时间:2024-10-11 13:30:54
本文介绍了相互检查字符串(字谜)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

任务是编写一个程序,接受来自用户的两组单词,然后如果这两组单词是字谜(或者至少如果一个单词的所有字母都出现在另一个单词中)和一个如果不是,则为错误"声明.

The assignment is to write a program that accepts two groups of words from the user and then prints a "True" statement if the two are anagrams (or at least if all the letters of one are present in the other) and a "False" statement if not.

作为一个整体编程的新手,我不知道如何超越仅仅索引一个字符串并将一个字符串的所有部分相互比较.我强调我是初学者;我已经阅读了许多其他带有 Python 和 Anagram 标签的帖子,它们都在我的头顶之上,并且引用了我没有学过的东西.所以越简单越好.到目前为止,这是我的非工作代码:

Being very new to programming as a whole, I don't know how to move beyond just indexing a string and comparing all of the pieces of one to another. I stress that I am a beginner; I've read many of the other posts tagged with Python and Anagram, and they are uniformly above my head and reference things I have not been taught. So the simpler the better. Here is my non-working code so far:

s1 = input("Please enter a word:") s2 = input("Please enter another word:") for i in range(0, len(s1), 1): if i in range (0, len(s2), 1): print("The letters in your first word are present in your second word.")

推荐答案

您需要多考虑一下您的条件逻辑.循环在正确的轨道上,但是如果 s1 中有一个不在 s2 中的字母,您应该 break 退出这个循环并打印False"语句.考虑使用像 all_s1_in_s2 = True 这样的变量,然后在发现不匹配的字母时将其设置为 false.

You need to think through your conditional logic a bit more. The loop is on the right track, but if there is a letter in s1 that is NOT in s2, you should break out of this loop and print the "False" statement. Consider using a variable like all_s1_in_s2 = True and then setting that to false if you find a letter that doesn't match.

其他一些提示:

  • for l in s1 将循环遍历字符串 s1,让您按 l 顺序访问每个字母 - 您不需要 range 或 len

  • for l in s1 will loop through string s1 giving you access to each letter in sequence as l - you don't need range or len at all

if .. in 语句可以帮助测试字符串中是否存在一个字母,例如if letter in mystring: 是一个有效的语句,这对你有很大帮助,同样不需要 range 或 len

The if .. in statement can help test whether a letter exists in a string, e.g. if letter in mystring: is a valid statement and this could help you a lot, again not needing range or len

您应该尽可能避免在变量名称中使用数字 - 最好是 word_one 和 word_two,例如

You should avoid using numbers in variable names where possible - better would be word_one and word_two, as an example

更多推荐

相互检查字符串(字谜)

本文发布于:2023-11-12 13:32:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581642.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字谜   字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!