坑真的很多,首先要处理全零reduce没有值typeerror的问题。
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
total=reduce(mul, nums)
ret =[]
if total == 0:
try:
total = reduce(mul, [x for x in nums if x != 0])
except TypeError:
#default value for all element is 0
total = 0
ret = [total if x==0 else 0 for x in nums]
else:
ret = [total// x for x in nums]
return ret
然后发现如果零大于1个,必然返回全零list,改造一下。
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# 0>1 return 0
if nums.count(0) > 1:
return [0 for x in nums]
#else
total=reduce(mul, nums)
ret =[]
if total == 0:
total = reduce(mul, [x for x in nums if x != 0])
ret = [total if x==0 else 0 for x in nums]
else:
ret = [total// x for x in nums]
return ret
错了两次,不过结果还不错
标签:Product,nums,Self,reduce,Except,ret,else,mul,total From: https://www.cnblogs.com/alfredsun/p/18288825