如何仅当单词末尾为元音时返回1?否则返回0(MapReduce Mapper问题)
问题:实现单词首尾元音判断的MapReduce Mapper逻辑
这是此前相关问题的后续:需要实现仅当单词最后一个字母是元音时返回1,否则返回0的功能,但当前代码存在逻辑错误,导致输出不符合预期。
现有代码
import sys import re pattern = re.compile("^[a-z]+$") # 匹配纯字母单词 starting_vowels = re.compile("(^[aeiouAEIOU])") # 匹配开头元音 ending_vowels = re.compile("[aeiouAEIOU]$") # 匹配结尾元音 starting_vowel_match = 0 ending_vowel_match = 0 for line in sys.stdin: line = line.strip() # 去除首尾空白字符 words = line.lower().split() # 将行拆分为单词并转为小写 for word in words: starting_vowel_match = 1 if starting_vowels.match(word[0]) else 0 # 三元运算符,word[0]是单词首字母 ending_vowel_match = 1 if ending_vowels.match(word[-1]) else 0 for letter in word: if pattern.match(letter): print("%s 1" % letter, starting_vowel_match, ending_vowel_match) starting_vowel_match = 0 ending_vowel_match = 0
当前错误输出
当输入文本为its a beautiful life时,得到以下错误输出:
i 1 1 0 t 1 0 0 s 1 0 0 a 1 1 1 b 1 0 0 e 1 0 0 a 1 0 0 u 1 0 0 t 1 0 0 i 1 0 0 f 1 0 0 u 1 0 0 l 1 0 0 l 1 0 1 i 1 0 0 f 1 0 0 e 1 0 0
期望输出
仅单词的最后一个字母对应的第四列显示1,正确输出应为:
i 1 1 0 t 1 0 0 s 1 0 0 a 1 1 1 b 1 0 0 e 1 0 0 a 1 0 0 u 1 0 0 t 1 0 0 i 1 0 0 f 1 0 0 u 1 0 0 l 1 0 0 l 1 0 0 i 1 0 0 f 1 0 0 e 1 0 1
问题原因与修复方案
问题根源
遍历单词的每个字母时,第一次循环就把starting_vowel_match和ending_vowel_match重置为0,后续字母循环时变量已被清空。以life为例,最后一个字母e循环时,ending_vowel_match已经是0,反而前面的字母因变量未被重置,错误拿到了结尾元音标记。
修复后的代码
import sys import re pattern = re.compile("^[a-z]+$") # 匹配纯字母单词 vowels = {'a', 'e', 'i', 'o', 'u'} # 用集合判断元音更高效 for line in sys.stdin: line = line.strip() words = line.lower().split() for word in words: # 提前计算当前单词的首尾元音状态 is_start_vowel = 1 if word[0] in vowels else 0 is_end_vowel = 1 if word[-1] in vowels else 0 # 遍历每个字母,根据位置决定输出对应标记 for idx, letter in enumerate(word): if pattern.match(letter): # 仅首字母输出首元音标记,其余为0 current_start = is_start_vowel if idx == 0 else 0 # 仅尾字母输出尾元音标记,其余为0 current_end = is_end_vowel if idx == len(word)-1 else 0 print(f"{letter} 1 {current_start} {current_end}")
修复说明
- 用**集合
vowels**替代正则判断元音,逻辑更直观且效率更高; - 提前计算单词的首尾元音状态,避免重复判断;
- 遍历字母时通过
enumerate获取索引,仅在对应位置(首/尾字母)输出1,其余位置输出0; - 移除不必要的全局变量重置逻辑,避免变量污染。
内容的提问来源于stack exchange,提问作者Zaku
相关产品推荐
相关产品推荐

