python简单算法题(二)

1)求一个矩阵的转置

matrix_before = [[1, 4], [2, 5], [3, 6]]

matrix_trans = []

length = len(matrix_before[0])

for j in range(length):

    vectors = []

    for i in matrix_before:

        vectors.append(i[j])

    matrix_trans.append(vectors)

print(matrix_trans)

2)推算任意层的杨辉三角

此题可以用填1法,补0法,置换法,对称法等求解。

以下我用的是置换法:

layer = int(input("input the layer number >>>"))

before = [[1], [1, 1]]   

for i in range(2, layer + 1):

    current_sub = [1] * (i + 1)

    before_sub = before[-1]

    for j in range(i - 1):

        val = before_sub[j] + before_sub[j + 1]

        current_sub[j + 1] = val

    before.append(current_sub)

num = len(before[-1]) * len(str(before[-1][6])) + (len(before[-1]) - 1) * 2

for i in before:

    print('{:^{}}'.format(i, num))

3)生成15个0-15的随机数,分别列出不重复的数与重复的数有哪些,且统计重复的数出现几次。

import random

repeat = {}

unique = []

l = []

for _ in range(10):

    l.append(random.randint(1, 10))

k = [0] * len(l)

for i in range(10):

    k[i] = l.count(l[i])

    if k[i] == 1:

        unique.append(l[i])

    else:

        repeat.fromkeys([l[i]])

        repeat[l[i]] = k[i]

print("random num: ", l)

print("unique num: {}".format(unique))

print("repeat num: {}".format(repeat))

你可能感兴趣的:(python简单算法题(二))