我會怎么做:“如果這個函式列印“字謎”然后列印別的東西”。我也想以某種方式只是想看看它是否會列印它但不讓它列印它。
這些是檔案,我正在處理 findAnagrams 并且無法更改 comparewords。
比較詞.py
def word_compare(x, y='steal'):
if isinstance(x, str) and isinstance(y, str) == True:
sorted_x = sorted(x)
sorted_y = sorted(y)
if sorted_x == sorted_y:
print('Anagram')
else:
mytuple = (x, y)
print(mytuple)
else:
print("Those aren't strings!")
findtheanagram.py
from WordCompare import word_compare
def findanagram(words):
for i in words:
for j in words:
if word_compare(i,j) == "Anagrams":
print(word[i] ":" j)
words = ['tar', 'rat', 'face', 'cafe', 'hello']
findanagram(words)
我該怎么做“如果函式列印 x 然后做 x 并且不讓它列印任何東西”?
uj5u.com熱心網友回復:
解決問題的一種方法,使用字典保存排序的單詞并將相同的排序單詞保存在串列中,在串列字謎中制作元素
def findanagram(words):
dic = {}
for word in words:
if not isinstance(word, str):
continue
sorted_word = ''.join(sorted(word))
if sorted_word not in dic:
dic[sorted_word] = []
dic[sorted_word].append(word)
return [anagrams for anagrams in dic.values() if len(anagrams)>1]
words = [1,'tar', 'rat', 'face', 'cafe', 'hello']
result = findanagram(words)
print(result)
輸出
[['tar', 'rat'], ['face', 'cafe']]
改進你的代碼
而不是使用 print,您的函式需要回傳 True 和 False,說明給定的兩個單詞分別是否是字謎。
所以你在 compareword.py 中的代碼應該像
def word_compare(word1, word2):
if not isinstance(word1, str) or not isinstance(word2, str):
return False # you can use log here to give reason
sorted_word1 = ''.join(sorted(word1))
sorted_word2 = ''.join(sorted(word2))
if sorted_word1==sorted_word2:
return True
else:
return False
# you can just use
# return sorted_word1 == sorted_word2
在檔案中findtheanagram.py你可以做
def findtheanagram(words):
result = []
for i, v in enumerate(words):
for j in range(i 1, len(words)): # considering minimum 2 elements
word1 = v
word2 = words[j]
if word_compare(word1, word2):
result.append((word1, word2))
return result
uj5u.com熱心網友回復:
您還想回傳一個值而不僅僅是列印,以便可以在函式之外訪問這些值:
def word_compare(x, y):
if isinstance(x, str) and isinstance(y, str) == True:
sorted_x = sorted(x)
sorted_y = sorted(y)
if sorted_x == sorted_y:
return 'Anagram'
print('Anagram')
else:
mytuple = (x, y)
return mytuple
print(mytuple)
else:
print("Those aren't strings!")
看到你不知道回傳值,我建議你先學習 python 的基礎知識。
編輯:沒關系看到你現在已經編輯了你的問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/504398.html
標籤:Python python-3.x 列表 功能
