In the following code, kind_num is used to count the integers with several different values in the integer list.
class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
loc = len(candies)
mol = loc % 2
if not (2 <= loc <= 10000) or mol != 0:
return 'wrong length of array'
for num in candies:
if not (-10000 <= num <= 10000):
return 'wrong element in array'
kind_num = 0
sis_num = loc / 2
for candy in candies:
kind_num += 1
while True:
try:
candies.remove(candy)
print candies
except ValueError:
break
if kind_num > sis_num:
return sis_num
elif kind_num < sis_num:
return kind_num
else:
return sis_num
s = Solution()
print s.distributeCandies([1,1,2,2,3,3])
But the second for loop exited early before completing the values in the candies. Why is this? ? ?
曾经蜡笔没有小新2017-06-22 11:54:27
Don’t remove in the loop
If you just want to count different types of values
#统计出现次数
lst = [1,1,2,2,3,3,4,4,5,6]
print len(set(lst))
#统计每种各出现几次
from collections import Counter
print dict(Counter(lst))
天蓬老师2017-06-22 11:54:27
candies.remove(candy) is executed for the first time Ok, candy is removed; due to while (True), this candy will be removed infinitely in the same For loop, but this candy has been removed the first time. So break.
phpcn_u15822017-06-22 11:54:27
from collections import defaultdict
d = defaultdict(int)
for item in your_list:
d[item] += 1
print d