我正在学习python并尝试了anagram generator练习,然后决定尝试不同的方法来生成anagrams,然后决定生成sub anagrams。我遇到的问题是需要比较列表,然后需要从list_1中删除list_2以说明它是否是一个子字谜,但这不会发生,当我运行它时,第一个字母被删除,然后一个字母,两个词都是一样的。我的代码如下:
def sub_anagram(word_1, word_2):
#letters need to be sorted into alphabetical order
list_1 = [c for c in word_1] #turns the string into a list
#list_1.sort() #sorts the list alphabetically
print(list_1)
list_2 = [c for c in word_2] #turns the string into a list
#list_2.sort() #sorts the list alphabetically
print(list_2)
#then the lists get compared
#loop to check if any letters from list_2 are in list_1
for list_2 in list_1:
#removes the letters in list_1 that are in
list_1.remove(list_2) list_2
print(list_2)
print(list_1)
list_1[len(list_1)-1] #checks the length of the list
if list_2 == list_1:
print("It is a sub-anagram")#return true if it is a sub-anagram
else:
print("It is not a sub-anagram") #return false if not
print("Sub-Anagram Antics")
#user inputs two words
#user input word 1
word_1 = input("Enter a word: ")
#user input word 2
word_2 = input("Enter a word: ")
#call function
sub_anagram(word_1, word_2)
答案 0 :(得分:0)
这里有一些格式错误的python代码:
for list_2 in list_1: ## <<< == nothing indented under the for loop, meaning that the for loop is not actually looping
#removes the letters in list_1 that are in
list_1.remove(list_2) list_2 ### <<< Here you have a dangling expression, the second instance of "list_2"
为了让你的代码更具可读性,我认为你的for循环应该看起来像
for ch in list_1:
list2.remove(ch)
我们的想法是,当它不是列表时,你不应该将你的循环变量“list_2”标记出来......它是列表中的一个元素。
答案 1 :(得分:0)
这就是你要找的东西:
def sub_anagram(word_1, word_2):
#letters need to be sorted into alphabetical order
list_1 = list(word_1) #turns the string into a list
#list_1.sort() #sorts the list alphabetically
print(list_1)
list_2 = list(word_2) #turns the string into a list
#list_2.sort() #sorts the list alphabetically
print(list_2)
#then the lists get compared
#loop to check if any letters from list_2 are in list_1
try:
for letter in list_2:
list_1.remove(letter)
print('It is a sub-anagram')
except ValueError:
print('It is not a sub-anagram')
#user inputs two words
#user input word 1
word_1 = input("Enter a word: ")
#user input word 2
word_2 = input("Enter a word: ")
#call function
sub_anagram(word_1, word_2)
另外,正如其他人所指出的,你应该小心你的变量名。您的代码在不同的时间为名称list_2分配了不同的值。列表中的项目与列表本身不同。