输入字符串,字符串可转换为N*N的数组,数组可认为是一个水域,判断多少天后,水域被全部污染,(数组中只有0和1,0表示纯净, 1表示污染, 每天只可污染上下左右的水域) ,如果开始全部被污染,或永远无法污染,则返回-1; 如:输入 1,0,1,0 ,0,0,1,0,1 转化为数组为: 1 0 1 0 0 0 1 0 1 输出: 2 注释 第一天后水域变为 1 1 1 1 0 1 1 1 1 第二天全部被污染
输入 0,0,0,0 输出: -1
import math
# input_str = '0,0,0,0'
# input_str = '1,1,1,1'
# input_str = '1,0,1,1'
input_str = '1,0,1,0,0,0,1,0,1'
def func(in_str):
"""
1. 转为一维数组
2. 判断是否全为 0 或者 1,是就返回结果
3. 转为 n*n 多维数组
4. 核心实现
循环遍历多维数组,且记录遍历次数,此次数为第几天全部被污染
都被污染,跳出循环
集合记录污染源上下左右坐标,遍历一次多维数组后,将多维数组在集合中的所有坐标标记为已污染(1)
5. 返回遍历次数
"""
formated_list = [int(x) for x in input_str.split(',')]
if all(formated_list) or not any(formated_list):
return -1
# n = math.sqrt(len(formated_list)) # n*n数组的n
n = int(len(formated_list) ** 0.5) # n*n数组的n
index = 0
mult_list = []
while index < len(formated_list):
mult_list.append(formated_list[index:index + n])
index += n
count = 0
while True:
if all([i for item in mult_list for i in item]): # 转为一维数组,判断是否已全部污染
break
temp_set = set()
for i in range(n):
for k in range(n):
if mult_list[i][k]:
if i - 1 >= 0:
temp_set.add((i - 1, k))
if i + 1 < n:
temp_set.add((i + 1, k))
if k - 1 >= 0:
temp_set.add((i, k - 1))
if k + 1 < n:
temp_set.add((i, k + 1))
for tup in temp_set: # 将坐标标记为已污染
mult_list[tup[0]][tup[1]] = 1
count += 1
return count
print(func(input_str))
正整数A和正整数B 的最小公倍数是指 能被A和B整除的最小的正整数值,设计一个算法,求输入A和B的最小公倍数。
数据范围:1≤a,b≤100000
输入描述: 输入两个正整数A和B。
输出描述: 输出A和B的最小公倍数。
示例1 输入:5 7
输出:35
示例2 输入:2 4
输出:4
import sys
for line in sys.stdin:
a = line.split()
x,y = int(a[0]),int(a[1])
if x == y:
print(x)
break
if x>y:
x,y=y,x
temp = x
while temp >0:
if x%temp == 0 and y%temp == 0: # 找出两数的最大公因数
print(int(x*y/temp))
break
temp -= 1
给定字符串,输入字符串中出现次数最多的字母和最大次数【安心筑面试题】
def calc_max_count(s: str):
"""
1. 非空判断
2. 需考虑存在相同最大字数的字母
"""
if len(s) == 0:
return "s can't be none"
max_count = 0
tmp = []
for item in set(s):
curr_count = s.count(item)
if curr_count > max_count:
max_count = curr_count
tmp.clear()
tmp.append(item)
elif curr_count == max_count:
tmp.append(item)
print(max_count,tmp)
给定两个列表[1,2,3....9],[11,12,13.....19],输出[(1,11),(2,12).......(9,19)]
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
l2 = [11, 12, 13, 14, 15, 16, 17, 18, 19]
# 方式一
print(list(map(lambda x, y: (x, y), l1, l2))) # [(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)]
# 方式二
print(list(zip(l1,l2))) # [(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)]