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? ? ?
Don’t remove in the loop
If you just want to count different types of values
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.