#杨辉三角的第m行第k元素 n=8 k=1 a=1 b=1 for x in range(n-1,n-k,-1): a=ax for y in range(k-1,0,-1): b=y print(a//b)

n=6 k=3 a=1 b=1 for x in range(n-1,n-k,-1): a*=x b*=(x-n+k) print(a//b)

#给定一个3*3矩阵,求其转置矩阵 l=[[1,2,3],[4,5,6],[7,8,9]] for i in range (3): for j in range (i,3): l[i][j],l[j][i]=l[j][i],l[i][j] print(l)

l=[[1,2,3],[4,5,6],[7,8,9]] for i in range (3): for j in range (i,3): tmp=l[i][j] l[i][j]=l[j][i] l[j][i]=tmp for x in range(3): print(l[x])

#打印2*3转置矩阵 l=[[1,2,3],[4,5,6]] l.append([a,a,a]*1) for i in range (3): for j in range (i,3): tmp=l[i][j] l[i][j]=l[j][i] l[j][i]=tmp for x in range(3): print(l[x][:2])

其实可以不用补这列的可以直接开辟一个新表用第一种的方法就可以实现 l=[[1,2,3],[4,5,6]] tm=[[0 for j in range (len(l))]for i in range(len(l[0]))] for i in range(len(tm)): for j in range (len(tm[0])): tm[i][j]=l[j][i] print (tm)

在tm那里的赋值是用到了后面的知识,是可以理解的、

#随机产生10个数字 #要求:每个数字取值范围【1,20】 #统计重复的数字有几个,分别是什么, #统计不重复的数字有几个分别是什么 #举例:11,7,5,11,6,7,4,其中2个数字7和11重复了,三个数字4,5,6没有重复过。 import random l=[] for i in range (10): a=random.randrange(1,21) l.append(a) k=[0]*20 rep=0 re=[] nre=[] nrep=1 for j in range(10): x=l[j] if k[x-1]==0: k[x-1]=l.count(x) if k[x-1]>1: rep+=1 re.append(x) elif k[x-1]>0: nrep+=1 nre.append(x) print("have {} repeated numbers is/are {}".format(rep,re)) print("have {} not repeated numbers is {}".format(nrep,nre))

其实还是老问题就是应该少用count来处理。 import random num=[] for _ in range(10): num.append(random.randrange(1,21)) #num=[11,9,11,7,9,6,11] length=len(num) states=[0]*length samenums=[] diffnums=[] for i in range(length): if states[i]==1: continue flag=True for j in range(i+1,length): if states[j]==1: continue if num[j]==num[i]: states[j]=1 flag=False if not flag: samenums.append(num[i]) else: diffnums.append(num[i]) print(len(samenums),samenums) print(len(diffnums),diffnums)