简体   繁体   English

计算列表中的字符串出现

[英]Counting string occurrences in list

I'm trying to work on a simple python problem hosted on hackerrankteam but I'm having difficulty with the count function for lists in Python. 我正在尝试解决由hackerrankteam托管的简单python问题,但是我在使用Python中列表的count函数时遇到了困难。 I've tried multiple test cases but my count function always returns 0. 我尝试了多个测试用例,但我的count函数始终返回0。

  • Objective: count the number of occurrences that consecutive squares equals the number of days. 目标:计算连续平方等于天数的出现次数。

Is this an issue with the type of list? 这是列表类型的问题吗? Is there an easier way for me count the values in one line instead of having to check the valued pairs and then count the sums? 对我而言,是否有一种更简单的方法来对一行中的值进行计数,而不必先检查已对值对然后对总和进行计数?

import sys

def solve(size, squares, day, month):
    check = [sum(squares[nums:nums+month]) == day for nums in range(0,len(squares))]
    print (check)   #Test list output
    count = check.count('True')
    return count

#Test Cases 1
# size = 6
# squares = [1,1,1,1,1,1]
# day, month = (3,2)
#Output 0

#Test Cases 2
# size = 1
# squares = [4]
# day, month = (4,1)
#Output 1

#Test Cases 3
size = 5
squares = [1,2,1,3,2] 
day, month = [3,2]
#Output 2

#Custom User Input:
# size = int(input().strip())
# squares = list(map(int, input().strip().split(' ')))
# day, month = input().strip().split(' ')
# day, month = [int(day), int(month)]
result = solve(size, squares, day, month)
print(result)
check.count('True')

This code is counting the number of occurrences of the string 'True' . 此代码计算字符串 'True'的出现次数。

It should instead be: 相反,它应该是:

check.count(True)

You could also simply use this: 您也可以简单地使用以下代码:

sum(check)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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