简体   繁体   中英

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. I've tried multiple test cases but my count function always returns 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' .

It should instead be:

check.count(True)

You could also simply use this:

sum(check)

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