Python重复单词检测代码报错求助:实现单词唯一性判定功能
Fixing Your Duplicate Word Detection Python Code
Let's work through fixing your code step by step—there are several syntax and logic issues causing the error you're seeing:
- The
isUnique()function doesn't accept any arguments, but you're passinguser_inputwhen calling it. You need to add a parameter to capture the input sentence. - You're using
sentence.split()butsentenceisn't defined anywhere—this should reference the function's input parameter instead. - In the for loop, you're iterating over
ibut checkingif word not in unique(typo:wordshould bei). - You're mixing up variable names:
count[i]is used butcountwas never initialized, while you meant to update theuniquedictionary. - Python uses capitalized boolean values (
True/False), not lowercasetrue/false. - Your function doesn't return anything—so when you assign
uniques = isUnique(user_input), it will always beNone. - The logic for detecting duplicates is reversed: you want to flag duplicates, not mark uniqueness in a dictionary.
Here's a simplified, corrected version of your code that meets your requirements:
def is_unique(sentence): words = sentence.split() # Sets automatically remove duplicates—compare lengths to check for repeats if len(words) != len(set(words)): return "not unique" else: return "unique" def main(): user_input = input("Enter words separated by space: ") result = is_unique(user_input) print(result) main()
Quick Explanation:
- Renamed
isUniquetois_uniqueto follow Python's standard snake_case naming convention (optional but recommended for readability). - Added a
sentenceparameter to the function so it can receive the user's input. - Used a set to efficiently check for duplicates: since sets can't hold duplicate values, if the length of the word list doesn't match the set length, duplicates exist.
- Fixed the typo in the input prompt ("sperated" → "separated").
- Added clear return statements that directly output your required strings.
If you want to stick with a dictionary-based approach to understand the iteration logic better, here's a corrected version using that method:
def is_unique(sentence): words = sentence.split() seen_words = {} for word in words: if word in seen_words: # Return immediately when a duplicate is found (more efficient) return "not unique" seen_words[word] = True # If we finish the loop without finding duplicates return "unique" def main(): user_input = input("Enter words separated by space: ") result = is_unique(user_input) print(result) main()
This version tracks words we've already seen in a dictionary, and exits early as soon as a duplicate is detected—saving unnecessary iterations if a repeat shows up early in the sentence.
内容的提问来源于stack exchange,提问作者filedelete
相关产品推荐
相关产品推荐

