简体   繁体   中英

cs50 pset6 readability getting wrong grade and negative index

Can anyone spot the issue? I get a negative for my index everytime so it always prints "Before Grade 1". I tried doing some regex but I still don't know how to implement it really

import re
from cs50 import get_string

words = 1
letters = 0
sentences = 0


st = get_string("Text: ")
t = len(st)
regex = r'\w+'
output = re.findall(regex,st)

for i in range(t):
    if st.isalpha():
        letters += 1
    if st.isspace():
        words += 1
    if st[i] == '.' or st[i] == '!' or st[i] == '?':
        sentences += 1

L = (letters / words * 100)
S = (sentences / words * 100)
index = 0.0588 * L - 0.296 * S - 15.8
roundedIndex = round(index)

if roundedIndex < 1:
    print("Before Grade 1")
if roundedIndex >= 16:
    print("Grade 16+")
else:
    print(roundedIndex)

Inside your loop, you're checking if the whole string is alphabetical or a space, not whether the letter corresponding to the index i is. You probably want st[i].isalpha() and st[i].isspace() .

Or, you could loop over the characters directly, rather than over indexes:

for char in st:
    if char.isalpha():
        ...
    if char.isspace():
        ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM