首页 > 解决方案 > varibale "count" won't be incremented even though if statement ,to increment it, matches the condition

问题描述

I am trying to make it so that it chooses the max value in a list that contains all the count variables...you'll see what I mean below.

import string

def solve(s):
    assigned_alphabet = {string.ascii_lowercase[num] : num + 1 for num in range(26)}
    non_vowels = "".join([char if char not in "aeiou" else " " for char in s]).split()
    count_list = []
    for item in non_vowels:
        count = 0
        if len(item) > 1:
            for char in item:
                count += assigned_alphabet[char]
            count_list.append(count)
        elif len(item) == 1:
            count += assigned_alphabet[item]
    return max(count_list)

It passed the following tests:

Test.assert_equals(solve("chruschtschov"),80)
Test.assert_equals(solve("khrushchev"),38)
Test.assert_equals(solve("strength"),57)
Test.assert_equals(solve("catchphrase"),73)
Test.assert_equals(solve("twelfthstreet"),103)
Test.assert_equals(solve("mischtschenkoana"),80)

but for some reason failed this one:

Test.assert_equals(solve("zodiac"),26)

It might be a stupid error, my eyes are tired and I just can't find how I can fix this.

标签: pythonpython-3.x

解决方案


I don't know what you're program is trying to do, but I see the error.

This line:

non_vowels = "".join([char if char not in "aeiou" else " " for char in s]).split()

Splits input strings into a list of strings containing non vowels in between the vowels.

''.join([char if char not in "aeiou" else " " for char in 'mischtschenkoana']).split()

--> ['m', 'schtsch', 'nk', 'n']

The problem with zodiac is that none of the values in this list has length greater than one.

['z', 'd', 'c']

The if clause in your code for the case of len = 1 doesn't update the thing you return.

elif len(item) == 1:
    count += assigned_alphabet[item]
return max(count_list)

You update only count, not count_list. So you are returning an empty list.


推荐阅读