我在注意公式时注意到我的函数有些奇怪的行为。这是没有函数的原始方程:
>>> (.39 * 4.0) + (11.8 * 1.5) - 15.59
3.6700000000000017 # the answer im looking for
我用返回相同数字的函数替换了其中一些数字。
def average_words(astring):
word_count = len(re.findall(r'\w+', astring))
period_count = len(re.findall(r'\.+', astring))
period_count = period_count or 1
return word_count/period_count
>> average_words(astring)
4.0
def average_syllables(astring):
words = re.findall(r'\w+', astring)
vowels_count = []
for word in words:
vowels = len(re.findall(r'[aeiou]+', word))
vowels_count.append(vowels)
return sum(vowels_count)/len(vowels_count)
>>>average_syllables(astring)
1.5
但是现在当我用函数替换数字时,它会给我一些奇数回报
>>> (.39 * average_words(astring)) + (11.8 * average_words(astring)) - 15.59
33.17
为什么会这样?
编辑:
完整代码:
import re
def average_words(astring):
word_count = len(re.findall(r'\w+', astring))
period_count = len(re.findall(r'\.+', astring))
period_count = period_count or 1
return word_count/period_count
def average_syllables(astring):
words = re.findall(r'\w+', astring)
vowels_count = []
for word in words:
vowels = len(re.findall(r'[aeiou]+', word))
vowels_count.append(vowels)
return sum(vowels_count)/len(vowels_count)
def flesch_kincaid(s):
""" Takes a string and returns grade level rounded off to two decimal points."""
return (.39 * average_words(s)) + (11.8 * average_syllables(s)) - 15.59
print flesch_kincaid("The turtle is leaving.")
答案 0 :(得分:2)
在REPL会话中,您正在执行(11.8 * average_words(astring))
,而不是(11.8 * average_syllables(astring))
。但是在完整的代码中它是正确的。