基础算法题(python)——翻转矩阵后的得分,错误的集合,单词替换
五、翻转矩阵后的得分
题目:
有一个二维矩阵 A 其中每个元素的值为 0 或 1 。
移动是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1,将所有 1 都更改为 0。
在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的得分就是这些数字的总和。
返回尽可能高的分数。
示例:
输入:[[0,0,1,1],[1,0,1,0],[1,1,0,0]]
输出:39
解释:
转换为 [[1,1,1,1],[1,0,0,1],[1,1,1,1]]
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
思路:(1)首先横向遍历翻转,条件是A[i][0] == 0
(2)纵向则需要根据当前列0的个数,大于一半需要翻转
代码:
import numpy as np
rows = eval(input("输入二维矩阵的行数:"))
cols = eval(input("输入二维矩阵的列数:"))
# 数组元素个数
count = rows * cols
# 生成一个只有1和0的rows * cols的二维矩阵
matrix = np.random.randint(2,size=count).reshape(rows ,cols)
print("原矩阵为:")
print(matrix)
# 判断每行的第一个元素是否为0,为0则进行转换
for i in range(0, matrix.shape[0]):
if matrix[i][0] == 0:
for j in range(0, matrix.shape[1]):
if matrix[i][j] == 1:
matrix[i][j] = 0
else:
matrix[i][j] = 1
# 判断每列中1的个数是否大于等于0的个数,否则进行转换
for j in range(0, matrix.shape[1]):
count_0 = 0
count_1 = 0
for i in range(0, matrix.shape[0]):
if matrix[i][j] == 0:
count_0 += 1
else:
count_1 += 1
# 1的个数 < 0的个数,进行转换
if count_0 > count_1:
for i in range(0, matrix.shape[0]):
if matrix[i][j] == 1:
matrix[i][j] = 0
else:
matrix[i][j] = 1
# 计算得分
score = 0
for i in range(0, matrix.shape[0]):
index = 1
for item in matrix[i]:
score += item * pow(2, matrix.shape[1]-index)
index += 1
print("变换后的矩阵为:")
print(matrix)
print("最高得分为:" + str(score))
六、错误的集合
题目:
代码:
nums = eval(input("输入错误的数组:"))
# 建立1到n的循环
for i in range(1, len(nums)+1):
# 定义出现次数
total_count = 0
# 循环判断输入的错误数组
for j in range(0, len(nums)):
# 计算数组中每个元素出现次数
if i == nums[j]:
total_count += 1
# 找出出现2次的数
if total_count == 2:
twice_num = i
# 找出出现0次的数
elif total_count == 0:
zero_num = i
print("返回结果:")
print([twice_num, zero_num])
七、单词替换
代码:
"""
示例:
输入: dict(词典) = ["cat", "bat", "rat"]
sentence(句子) = "the cattle was rattled by the battery"
输出: "the cat was rat by the bat"
"""
# 输入字典和句子
word_dict = eval(input("输入字典:"))
sentence = eval(input("输入句子:"))
# 句子分割为单词列表
sentence_list = sentence.split(" ")
# 找出包含词根的单词并最短替换
for word in word_dict:
for index, sen in enumerate(sentence_list):
if word in sen:
sentence_list[index] = word
# 输出替换后句子
print("词根替换后的句子为:")
print(" ".join(sentence_list))