python - 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.
解决方案
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.
推荐阅读
- c++ - 用于 Visual Studio 代码的 Arduino 多文件代码
- powershell - 将带有撇号的文件名的批处理文件传递给powershell命令
- angular - Angular 10 Formly + 材质垂直多选框
- laravel - 附加多态关系?
- javascript - jQuery / Javascript总和按预期计算
- javascript - 调用堆栈超出快速排序功能
- r - 通过使用 dplyr 添加前缀重命名除 id 列之外的所有列
- python - 在 Python 这样的编程语言和 Tensorflow 这样的平台中,“API”是什么意思?
- flutter - Flutter: chopper_generator >=3.0.4 与 moor_generator ^4.1.0 不兼容,如何解决?
- python - 写入同一视频后,视频的 NumPy 数组从原始数组发生变化