You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中检测两个单词是否相邻?自定义函数异常求助

Troubleshooting Your Adjacent Word Detection Function

Hey Jake, let's dig into why your function is returning None and always outputting "They are far"—this is a super common issue with Python functions, usually tied to missing return statements or flawed logic flow. Let's break it down and fix it together!

First, Let's Identify the Likely Culprits

The two main reasons you're seeing None and the wrong message are:

  • Your function isn't explicitly returning a value for all code paths. Python functions return None by default if they reach the end without a return statement.
  • You're using print() instead of return (or mixing the two), so even though you see a message printed, the function itself doesn't pass that value back when called.

Example of the Problematic Code

Chances are your function looks something like this (I've recreated a common incorrect version):

def check_adjacent(s, word1, word2):
    words = s.split()
    for i in range(len(words)-1):
        if (words[i] == word1 and words[i+1] == word2) or (words[i] == word2 and words[i+1] == word1):
            print("They are adjacent")
    print("They are far")

When you call this function:

  • If it finds adjacent words, it prints "They are adjacent" but then continues to the end and prints "They are far" anyway.
  • The function never uses return, so calling it gives you None as the result.

Fixed Version of the Function

Here's how to adjust it to work correctly:

def check_adjacent(s, word1, word2):
    # Split the string into words (note: this splits on whitespace only—we'll cover punctuation later)
    words = s.split()
    
    # Loop through each pair of consecutive words
    for i in range(len(words) - 1):
        current_word = words[i]
        next_word = words[i+1]
        # Check if the pair matches either order
        if (current_word == word1 and next_word == word2) or (current_word == word2 and next_word == word1):
            return "They are adjacent"
    
    # If we finish the loop without finding a match, return this
    return "They are far"

Key Fixes Explained

  • Explicit return statements: The function returns immediately when it finds adjacent words, so it doesn't keep running and print the wrong message. If no match is found, it returns "They are far" at the end.
  • No stray print() calls: The function returns the result instead of printing it, so when you call it, you get the actual string value instead of None.

Testing the Fixed Function

Now when you test it, you'll get the correct results:

# Test case 1: Words are adjacent
result1 = check_adjacent("The quick brown fox jumps", "quick", "brown")
print(result1)  # Output: "They are adjacent"

# Test case 2: Words are not adjacent
result2 = check_adjacent("The quick brown fox jumps", "quick", "fox")
print(result2)  # Output: "They are far"

Bonus: Handling Punctuation

If your strings have punctuation (like "hello, world"), split() won't separate "hello," from "world". To fix this, use regex to extract actual words:

import re

def check_adjacent(s, word1, word2):
    # Extract only words (ignores punctuation)
    words = re.findall(r'\b\w+\b', s)
    
    for i in range(len(words) - 1):
        current_word = words[i]
        next_word = words[i+1]
        if (current_word == word1 and next_word == word2) or (current_word == word2 and next_word == word1):
            return "They are adjacent"
    
    return "They are far"

This will correctly handle strings like "Hello, world! How are you?" when checking "Hello" and "world".

Final Checks

Double-check your code for:

  • Missing return statements in any branch of logic
  • Accidental use of print() instead of return
  • Edge cases like empty strings, single-word strings, or words with punctuation

内容的提问来源于stack exchange,提问作者Jake 1986

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:38:25