s = 'zhangkaiguozhangxuanzhuangbaosui'
d={}
# for i ,c in enumerate(s):
# d[c] = d.get(c,[])+[i]
#
# print(d)
#第二种方法 ,效果更好
for i,c in enumerate(s):
d.setdefault(c,[]).append(i)
print(d)
创建一个向量类
import math
_EPSTION=0.0000001
class Vector:
def __init__(self,lst:list):
self._values = list(lst)
@classmethod
def zero(cls,dim):
return cls([0]*dim)
def norm(self):
return math.sqrt(sum(e**2 for e in self))
def normalize(self):
# return Vector([e/self.norm() for e in self]) 这样self.norm()重复计算
# return 1/self.norm()*Vector(self._values)
if self.norm()<_EPSTION:
raise ZeroDivisionError("除数不能为零")
return Vector(self._values)/self.norm()
def dot(self,another):
'''向量点乘,返回结果为标量'''
assert len(self) == len(another), \
"Error in adding.length of vectors must be same"
return sum(a*b for a,b in zip(self,another))
def __repr__(self):
return f"Vector:({self._values})"
def __str__(self):
return "({})".format(",".join(str(e) for e in self._values))
def __getitem__(self, index):
return self._values[index]
def __add__(self, other):
assert len(self)==len(other),\
"Error in adding.length of vectors must be same"
# return Vector([a+b for a,b in zip(self._values,other._values)])
return Vector([a+b for a,b in zip(self,other)]) #返回一个新的向量类
def __sub__(self, other):
assert len(self) == len(other), \
"Error in adding.length of vectors must be same"
return Vector([a-b for a,b in zip(self,other)])
def __pos__(self):
return 1*self
def __neg__(self):
return -1*self
def __mul__(self,k):
return Vector([k*e for e in self])
def __rmul__(self, k):
return self*k
def __truediv__(self, k):
return (1/k)*self
def __iter__(self):
return self._values.__iter__()
def __len__(self):
'''返回向量长度'''
return len(self._values)
if __name__ == '__main__':
v=Vector([0,0])
v2=Vector([3,4])
print(v.norm())
print(v2.norm())
try:
print(v.normalize().norm())
except ZeroDivisionError as e:
print(e)