携程笔试4.14
菜鸡继字节后第二次akhhhhhh,虽然难度不是很大
第一题
画U,模拟
n = int(input()) temp = '*' * n + '.' * (2 * n) + '*' * n grid = [temp for _ in range(4*n)] for i in range(3*n, 4*n): temp = i - 3 * n + 1 grid[i] = '.' * temp + '*' * n + '.' * (2 * n - 2 * temp) + '*' * n + '.' * temp for i in range(4*n): print(grid[i])
第二题
from collections import defaultdict n = 3 nums = [2, 3, 3] pattern = 'BBB' h_b = defaultdict(int) h_r = defaultdict(int) for i in range(len(nums)): if pattern[i] == 'B': h_b[nums[i]] += 1 else: h_r[nums[i]] += 1 res = 0 for key in list(set(h_b.keys()) - (set(h_b.keys()) - set(h_r.keys()))): res += h_b[key] * h_r[key] print(res)
第三题
脑补了一下大致可行就写了 可是偶数那个一开始写错了 debug了半小时 最后发现是'100101'这种情况,一开始想着第一个是1就一定是1了。
string = input() if len(string) % 2 == 0: p = 1 res1 = 0 for i in range(len(string)): if string[i] == '0': res1 += abs(i - p) p += 2 p = 1 res2 = 0 for i in range(len(string)): if string[i] == '1': res2 += abs(i - p) p += 2 res = min(res1, res2) else: temp = 0 for i in range(len(string)): if string[i] == '1': temp += 1 else: temp -= 1 if temp > 0: p = 0 res = 0 for i in range(len(string)): if string[i] == '1': res += abs(p - i) p += 2 else: p = 0 res = 0 for i in range(len(string)): if string[i] == '0': res += abs(p - i) p += 2 print(res)
第四题
动态规划
dp[i][j],i是数的下标,j是0-8,表示除以9的余数
可以优化为2*9的不然会爆内存
string = input() dp = [[0] * 9 for _ in range(2)] remain = int(string[0]) % 9 dp[0][remain] = 1 mod = 10 ** 9 + 7 for i in range(1, len(string)): for j in range(9): temp = (j - int(string[i])) % 9 if j == int(string[i]) % 9: dp[1][j] = (dp[0][j] + dp[0][temp] + 1) % mod else: dp[1][j] = (dp[0][j] + dp[0][temp]) % mod dp[0] = dp[1][:] print(dp[-1][0])#携程笔试##春招##实习##笔试题目##校招#