你如何制作一个程序来检测数组中的一个单词是否是异义词?这会将其输出为True和False吗


def hetemoro(s):
hash = [0] * 26
x = 0
repeat = 0
register = 0
result = []
new_list = []
while(repeat <= 2):
activity = ''.join(c for c in s[x] if c.isalpha()) #Necessary in order to allow 's' to exclude all numbers
new_list.append(activity.lower())
repeat += 1
x += 1
x = 0
repeat = 0
while(repeat <= 2):
ignore = 0
a = new_list[x]
n = len(a)-1
for i in range(n):
if hash[ord(a[i]) - ord('a')] == 0:
hash[ord(a[i]) - ord('a')] = 1
else:
value = (s[x], False)
result.append(value)
register += 1 
if (register == 3):
print(result)
ignore = 1
x += 1  
repeat += 1
if (ignore == 0):
value = (s[x], True)
result.append(value)
register += 1
if (register == 3):
print(result)
x += 1   
repeat += 1
return result

我是不是错过了什么?因为输出只是

hetemero(['great', 'dgss', 'may'])
hetemero(['a25a', 'agd', 'ss25'])
[('great', True), ('dgss', False), ('may', False)]
[('a25a', True), ('agd', False), ('ss25', True)]

这是错误的,因为"可能"肯定是真的,我认为代码在过程中有一些错误,我需要一些帮助来理解我需要添加和删除什么,这样它才能顺利地进行

这就是你想要的函数吗:

def func(words):
return [(word, len(set(word)) == len(word)) for word in words]

使用集合的原因是因为它们不能包含重复的值,所以如果单词中有一个字母重复,它将被删除,因此集合的长度将比单词短

非常感谢大家的贡献,我在大家的帮助下找到了解决方案。即建议添加的人

if len(set(word)) == len(word):
lst.append((words[x], True))
else:
lst.append((words[x], False))
repeat += 1

是的,现在的输出是正确的。

使用Set是可以的,但它不会给您带来懒惰的评估,因为扫描整个单词是为了检测重复的字母。我会使用字典来跟踪解析的每个字母,如果遇到的下一个字母已经存储,则立即返回False。我将采用这种实现方式:

def is_heterogram(word):
d = {}
for letter in word:
if letter in d.keys():
return False
d[letter] = None
return True
def hetemero(words):
return [(word, is_heterogram(word)) for word in words]
print(hetemero(['great', 'dgss', 'may']))
print(hetemero(['a25a', 'agd', 'ss25']))

最新更新