我需要编写一个定义单词是否为字谜的程序。好吧,这是我的代码。用## here
标记的行反映了主要问题。我需要定义第一个和第二个word1
循环的word2
和for
的索引,然后进行比较。如果这些索引相似,则程序会遗漏单词(因为它在迭代时会出现两次)。我知道,代码尚未完成
text_sample = 'text goes here'
c = 0
i = 0
isanagramma = 0
n = len(text_sample)
while c < len(text_sample):
for word1 in text_sample:
for word2 in range(1,n):
s1 = sorted(word1)
s2 = sorted(text_sample[word2])
index1 = text_sample.index(word1) ## here
index2 = text_sample.index(text_sample[word2]) ## here
if index1 == index2: ## here
continue ## here
if s1 == s2:
isanagrama+=1
i+=1
c+=1
print(isanagramma)
答案 0 :(得分:0)
text_sample = 'text goes here ttex'
s = text_sample.split(" ")
isanagramma = 0
for i in range (0,len(s)-1):
for x in range(i+1,len(s)):
if sorted(s[i]) == sorted(s[x]):
print ("is anagram :{} and {}".format(s[i],s[x]))
isanagramma += isanagramma
else:
print ("not anagram :{} and {}".format(s[i],s[x]))
print (isanagramma)
输出:
not anagram :text and goes
not anagram :text and here
is anagram :text and ttex
not anagram :goes and here
not anagram :goes and ttex
not anagram :here and ttex
1