Как сравнить два индекса массива (не значения этих индексов)? - PullRequest
0 голосов
/ 02 апреля 2019

Мне нужно сделать программу, которая определяет, является ли слово анаграммой или нет. Ну, вот мой код. Строки, отмеченные ## 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)

1 Ответ

0 голосов
/ 02 апреля 2019
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
...