相互检查字符串(字谜) [英] Checking strings against each other (Anagrams)
问题描述
任务是编写一个程序,接受来自用户的两组单词,然后如果这两组单词是字谜(或者至少如果一个单词的所有字母都出现在另一个单词中)和一个如果不是,则为错误"声明.
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 asl
- you don't needrange
orlen
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
这篇关于相互检查字符串(字谜)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!