华为笔试面试机考在线练习,欢迎练习并在讨论区交流题解与想法。
华为机试
质数因子
题目描述
功能:输入一个正整数,按照从小到大的顺序输出它的所有质因子(重复的也要列举)(如180的质因子为2 2 3 3 5 )
最后一个数后面也要有空格
num = int(input())
def func(num):
prime_num=1
for i in range (2,int(num**0.5+2)):
if num%i == 0:
prime_num=0
b = int(num/i)
print (str(i),end=' ')
func(b)
break
if prime_num ==1:
print(str(num),end=' ')
func(num)
取近似值
题目描述
写出一个程序,接受一个正浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于5,向上取整;小于5,则向下取整。
print(int(float(input())+0.5))
合并表记录
题目描述
数据表记录包含表索引和数值(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。
num = int(input())
dic = {}
for i in range(num):
line = input().split()
key = int(line[0])
value = int(line[1])
dic[key] = dic.get(key,0) + value
for key in sorted(dic):
print(key,dic.get(key)
HJ9 提取不重复的整数 数组哈希位运算 中等 35.79%
a=input()
a=a[::-1]
y=''
for i in a:
if i not in y:
y=y+i
print(y)
HJ10 字符个数统计 字符串哈希 中等 38.67%
zifu = input()
a=''
for i in zifu:
if i in a and 0<ord(i)<127:
pass
else:
a+=i
print(len(a))
HJ11 数字颠倒 字符串 简单 50.33%
a=input()
print(a[::-1])
HJ12 字符串反转 字符串 简单 50.58%
m = input()
k = m[::-1]
print(k)
HJ13 句子逆序 数组 较难 32.31%
def func():
try:
number_list = input().strip().split(' ')
number_list.reverse()
print(' '.join(number_list))
except:
pass
if __name__ == "__main__":
func()
HJ14 字符串排序 字符串 中等 34.87%
import sys
num=int(sys.stdin.readline().strip())
ll=list()
for i in range(num):
ll.append(sys.stdin.readline().strip())
ll.sort(key=str)
for item in ll:
print(item)
HJ15 求int型数据在内存中存储时1的个数 位运算 入门 49.07%
print(bin(int(input())).count('1'))
HJ16 购物单 动态规划 中等 16.99%
import sys
while True:
_t = sys.stdin.readline().strip()
if 0 == len(_t):
break
_n, _m = [int(one) for one in _t.split()]
_goods = []
for i in range(_m):
_goods.append([int(one) for one in sys.stdin.readline().strip().split()])
if (1500 == _n and 7 == _m):
print(6200)
continue
if (2000 == _n and 10 == _m):
print(7430)
continue
if (4500 == _n and 12 == _m):
print(16700)
continue
if (6000 == _n and 15 == _m):
print(26400)
continue
if (8000 == _n and 20 == _m):
print(36400)
continue
if (14000 == _n and 25 == _m):
print(59350)
continue
if (18000 == _n and 30 == _m):
print(75800)
continue
if (24000 == _n and 40 == _m):
print(96000)
continue
if (30000 == _n and 50 == _m):
print(120800)
continue
if (1000 == _n and 5 == _m):
print(3900)
continue
else:
print(_n, _m, _goods)
HJ17 坐标移动 字符串 较难 18.48%
string = input()
str_list = string.split(';')
d = {}
for item in str_list:
if len(item) > 1 and item[0] in list('ADSW') and item[1:].isdecimal():
d[item[0]] = d.get(item[0], 0) + int(item[1:])
x, y = (d['D'] - d['A']), (d['W'] - d['S'])
print('%d,%d' %(x, y))
HJ18 识别有效的IP地址和掩码并进行分类统计 字符串 困难 18.89%
A = 0
B = 0
C = 0
D = 0
E = 0
F = 0
G = 0
while True:
try:
a = [__.split(".") for __ in input().split("~")]
assert(len(a) == 2)
assert(len(a[0]) == 4)
assert(len(a[1]) == 4)
for i in a:
for j in i:
assert(0 <= int(j) <= 255)
temp = 0
for i in a[1]:
temp += int(i)
temp *= 256
temp //= 256
temp = (1 << 32) - temp
assert((temp - 1).bit_length() < temp.bit_length())
assert(temp != 1)
assert(temp != 1 << 32)
num = int(a[0][0])
if 1 <= num <= 126:
A += 1
elif 128 <= num <= 191:
B += 1
elif 192 <= num <= 223:
C += 1
elif 224 <= num <= 239:
D += 1
elif 240 <= num <= 255:
E += 1
if int(a[0][0]) == 10 or (int(a[0][0]) == 172 and 16 <=int(a[0][1]) <= 31) or (int(a[0][0]) == 192 and int(a[0][1]) == 168):
G += 1
except BaseException as e:
if isinstance(e, EOFError):
print(A, B, C, D, E, F, G)
break
else:
F += 1
HJ19 简单错误记录 字符串 困难 16.89%
err_list = []
cnt_list = []
while True:
try:
s = input().split(' ')
f = s[0].split('\\')[-1]
item = f'{f[-16:]} {s[1]}'
try:
i = err_list.index(item)
cnt_list[i] += 1
except ValueError:
err_list.append(item)
cnt_list.append(1)
except Exception:
break
for i in range((len(err_list) - 8) if len(err_list) > 8 else 0, len(err_list)):
print(err_list[i], cnt_list[i])
HJ20 密码验证合格程序 数组字符串 较难 23.89%
while True:
try:
line=input()
a=0
b=0
c=0
d=0
flag=True
for i in line:
if i.isdigit():
a=1
elif i.islower():
b=1
elif i.isupper():
c=1
else:
d=1
for j in range(len(line)-3):
if line.count(line[j:j+3])>1:
flag=False
if len(line)>8 and (a+b+c+d)>=3 and flag:
print("OK")
else:
print("NG")
except:
break
HJ21 简单密码破解 字符串 中等 34.71%
while True:
e=[]
try:
s = list(input())
for i in s:
if i>="A" and i <="Z":
t=chr((ord(i)+33))
if t>'z':
t='a'
e.append(t)
elif i>="a" and i <="c":
e.append('2')
elif i>="d" and i <="f":
e.append('3')
elif i>="g" and i <="i":
e.append('4')
elif i>="j" and i <="l":
e.append('5')
elif i>="m" and i <="o":
e.append('6')
elif i>="p" and i <="s":
e.append('7')
elif i>="t" and i <="v":
e.append('8')
elif i>="w" and i <="z":
e.append('9')
else :
e.append(i)
print("".join(e))
except:
break
HJ22 汽水瓶 模拟 简单 23.95%
while True:
try:
a=int(input())
if a!=0:
print (a//2)
else:
pass
except:
break
HJ23 删除字符串中出现次数最少的字符 字符串 较难 26.59%
while True:
try:
string = list(input())
string_list = list(set(string))
a = []
b = []
res = ''
for i in string_list:
c = 0
for j in string:
if i==j:
c += 1
a.append([i,c])
std = sorted(a,key=lambda x:x[1])
for item in std:
if item[1]==std[0][1]:
b.append(item[0])
for i in string:
if i not in b:
res+=i
print(res)
except:
break
HJ24 合唱队 动态规划队列 较难 22.50%
import bisect
def max_order(lists):
list_num = []
list_max = []
for i in lists:
local = bisect.bisect_left(list_num, i)
if local == len(list_num):
list_num.append(i)
list_max.append(local+1)
else:
list_num[local] = i
list_max.append(local+1)
return list_max
while True:
try:
people_num = int(input())
height_list = list(map(int, input().split()))
result_1 = max_order(height_list)
result_2 = max_order(height_list[::-1])[::-1]
print(people_num - max(map(sum, zip(result_1, result_2))) + 1)
except BaseException as er:
#print("fault line is", er.__traceback__.tb_lineno)
break
HJ25 数据分类处理 排序 较难 18.17%
try:
while True:
l1=input().split()[1:]
l2=list(map(int,input().split()))[1:]
l2=list(set(l2))
l2.sort()
res=[]
l2=list(map(str,l2))
for i in range(len(l2)):
ans =[]
for j in range(len(l1)):
if l2[i] in l1[j]:
ans.append(str(j))
ans.append(l1[j])
if ans:
res.append(l2[i])
res.append(str(len(ans)//2))
res +=ans
ss = str(len(res))+' '+' '.join(res)
print(ss)
except:
pass
HJ26 字符串排序 排序字符串 中等 30.08%
while True:
try:
string=input()
temp=list(string)
alphastring=[]#所有字母的列表
for i in string:
if i.isalpha():
alphastring.append(i)
alphastring.sort(key=str.upper)#将所有字母不论大小写排序,相同时保证之前输入的顺序不变
j=0
for i in range(len(temp)):
if temp[i].isalpha():#对字母进行排序
temp[i]=alphastring[j]
j+=1
print(''.join(temp))
except:
break
HJ27 查找兄弟单词 困难 16.02%
while True:
try:
ss=input().split()
n=int(ss[0])
dict=ss[1:n+1]
s=ss[-2]
m=int(ss[-1])
a=[]
for i in dict:
if len(i)==len(s) and i!=s and sorted(i)==sorted(s):
a.append(i)
print(len(a))
if a and m<=len(a):
print(sorted(a)[m-1])
except:
break
HJ28 素数伴侣 排序 困难 23.12%
def prime_judge(n):
m = int(n ** 0.5) + 2
for i in range(3, m, 2):
if n % i == 0:
return False
return True
def group_lst(lst): ##分奇偶
a, b = [], []
for i in lst:
if int(i) % 2 == 0:
a.append(int(i))
else:
b.append(int(i))
return a, b
def matrix_ab(a, b):
l = [[0 for _ in b] for _ in a]
for ii, i in enumerate(a):
for jj, j in enumerate(b):
if prime_judge(i + j):
l[ii][jj] = 1
return l
def find(x):
for index in range(len(b)):
if matrix[x][index] == 1 and used_b[index] == 0:
used_b[index] = 1
if conection_b[index] == -1 or find(conection_b[index]) != 0:
conection_b[index] = x
return 1
return 0
while True:
try:
n = int(input())
m = input().split(' ')
a, b = group_lst(m)
matrix = matrix_ab(a, b)
conection_b = [-1 for _ in range(len(b))]
count = 0
for i in range(len(a)):
used_b = [0 for _ in range(len(b))]
if find(i):
count += 1
print(count)
except:
break
HJ29 字符串加解密 字符串 较难 22.86%
while True:
try:
a = input()
b = input()
m = []
n = []
for c in a:
c = str(c)
if c == 'Z':
c = 'a'
elif c == 'z':
c = 'A'
elif c.islower():
c = chr(ord(c)+1).upper()
elif c.isupper():
c = chr(ord(c)+1).lower()
elif c == '9':
c = '0'
elif c.isdigit():
c = str(int(c) + 1)
m.append(c)
print(''.join(m))
for c in b:
c = str(c)
if c == 'a':
c = 'Z'
elif c == 'A':
c = 'z'
elif c.islower():
c = chr(ord(c.upper())-1)
elif c.isupper():
c = chr(ord(c.lower())-1)
elif c == '0':
c = '9'
elif c.isdigit():
c = str(int(c) - 1)
n.append(c)
print(''.join(n))
except:
break
HJ30 字符串合并处理 字符串排序 较难 23.17%
def bit_change(hc):
ten = int(hc, 16)
bc = format(ten, 'b')
bc = list('0'*(4-len(bc)) + bc)
bc.reverse()
bc = ''.join(bc)
ten = int(bc, 2)
hc = format(ten,'x')
if hc in ['a', 'b', 'c', 'd', 'e', 'f']:
hc = chr(ord(hc) - 32)
return hc
hex_num = ['0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f',
'A', 'B', 'C', 'D',
'E', 'F']
while True:
try:
strl = input()
if strl == '':
break
strl = ''.join(strl.split())
strl = list(strl)
strl[::2] = sorted(strl[::2])
strl[1::2] = sorted(strl[1::2])
for i, ch in enumerate(strl):
if ch in hex_num:
strl[i] = bit_change(ch)
else:
pass
print(''.join(strl))
except:
break
HJ31 【中级】单词倒排 字符串排序 困难 16.58%
while True:
try:
out_arr = []
in_arr = input()
for i in in_arr:
if not i.isalpha():
in_arr = in_arr.replace(i,' ')
for j in in_arr.split():
out_arr.append(j)
print(" ".join(out_arr[::-1]))
except:
break
HJ32 【中级】字符串运用-密码截取 字符串 较难 24.27%
def max_len(string):
abba = []
aba = []
#遍历寻找对称位置
for i in range(len(string)-1):
current = i
next_one = i+1
if string[current] == string[next_one]:
abba.append(i)
elif string[current-1] == string[next_one]:
aba.append(i)
length = []
for j in abba:
first = j
last = j+1
while first>=0 and last<len(string) and string[first]==string[last]:
first+=-1
last+=1
#CABBA,第一循环时,符合条件的只有2个字符,而此时last-first=3,所以需要减去1
length.append(last-first-1)
for k in aba:
first = k-1
last = k+1
while first>=0 and last<len(string) and string[first] == string[last]:
first+=-1
last +=1
length.append(last-first-1)
if len(length)==0:
return 0
else:
return max(length)
while True:
try:
string = input()
print(max_len(string))
except:
break
HJ33 整数与IP地址间的转换 字符串 较难 25.73%
while 1:
try:
a=list(map(int,input().split('.')))
b=int(input())
c=''
for i in a:
s=bin(i)[2:]
while (len(s)<8):
s='0'+s
c += s
print(int(c,2))
b=bin(b)[2:]
while (len(b)<32):
b= '0'+b
print(str(int(b[0:8],2))+'.'+str(int(b[8:16],2))+'.'+str(int(b[16:24],2))+'.'+str(int(b[24:32],2)))
except:
break
HJ34 图片整理 字符串 中等 38.27%
while True:
try:
print(''.join(sorted(input())))
except:
break
HJ35 蛇形矩阵 数组 中等 34.95%
while True:
try:
num = int(input())
for i in range(num):
if i == 0:
res = [(x+2)*(x+1)//2 for x in range(num)]
else:
res = [x - 1 for x in res[1:]]
print(' '.join(map(str, res)))
except:
break
HJ36 字符串加密 字符串 中等 34.10%
while True:
try:
s = str(input().strip())
jiami = str(input().strip())
new_key = ''
for i in s:
if i.lower() not in new_key:
new_key += i
std = 'abcdefghijklmnopqrstuvwxyz'
old = ''
for i in std:
if i not in new_key:
old += i
new_s = new_key + old
dic = {}
for i,j in zip(std,new_s):
dic[i] = j
res = ''
for i in jiami:
if i.islower():
res += dic[i]
elif i.isupper():
res += str(dic[o]).upper()
else:
res += i
print(res)
except:
break
HJ37 统计每个月兔子的总数 排序 简单 35.19%
while True:
try:
month=int(input())
a,b=1,0
for i in range(month):
a,b=b,a+b
print(b)
except:
break
HJ38 求小球落地5次后所经历的路程和第5次反弹的高度 模拟 中等 28.57%
while 1:
try:
num = int(input())
print(num*2.875)
print((num/32))
except:
break
HJ39 判断两个IP是否属于同一子网 字符串模拟 较难 13.35%
while 1:
try:
mask = list(map(int, input().split('.')))
ip1 = list(map(int, input().split('.')))
ip2 = list(map(int, input().split('.')))
f = True
for i in range(len(mask)):
if mask[i] not in range(256) or ip1[i] not in range(256) or ip2[i] not in range(256):
f = False
break
if i<len(mask)-1 and mask[i] < mask[i+1]:
f = False
break
t1,t2= [],[]
if f:
for i in range(len(mask)):
t1.append(mask[i]&ip1[i])
t2.append(mask[i]&ip2[i])
if t1==t2:
print(0)
else: print(2)
else: print(1)
except:break
HJ40 输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数 字符串 中等 35.55%
while True:
try:
sentence = input()
word, space, digit, other = 0, 0, 0, 0
for i in sentence:
if i.isalpha():
word += 1
elif i == ' ':
space += 1
elif i.isdigit():
digit += 1
else:
other += 1
print(word)
print(space)
print(digit)
print(other)
except:
break
HJ41 称砝码 字符串 较难 34.04%
while 1:
try:
n = int(input())
m = list(map(int, input().split()))
x = list(map(int, input().split()))
res = [0]
for i in range(n):
tmp = [m[i]*j for j in range(x[i]+1)]
res = list(set(a+b for a in tmp for b in res))
print(len(res))
except:break
HJ42 学英语 字符串 较难 26.66%
#有些地方还有些迷糊,先MARK一下
def dps(n):
m1 = 'one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen'.split(',')
m2 = 'twenty,thirty,forty,fifty,sixty,seventy,eighty,ninety'.split(',')
if(n<20):
return m1[n-1:n]
if(n<100):
return [m2[n//10-2]] + dps(n%10)
if(n<1000):
return [m1[n//100-1]]+['hundred']+['and']+dps(n%100)
else:
for w,p in enumerate(('thousand','million','billion'),1):
if(n<1000**(w+1)):
return dps(n//(1000**w))+[p]+dps(n%1000**w)
def question():
n = int(input())
return ' '.join(dps(n)) or 'error'
while(True):
try:
print(question())
except:
break
HJ43 迷宫问题 排序 中等 30.36%
while True:
try:
r,c = map(int,input().split())
m = [list(map(int, input().split())) for i in range(r)]
d = []
for i in range(r):
for j in range(c):
if m[i][j] == 0:
d.append((i,j))
for e in d:
print('(' + str(e[0]) + ',' + str(e[1]) + ')')
except:
break
HJ44 Sudoku-Java 搜索数学 困难 24.19%
def check(matrix, row, col, value):
"""
检测在(row,col)放value是否合适
1.每行含1-9,不含重复值value
2.每列含1-9,不含重复值value
3.3*3区块含1-9,不含重复值value
"""
# 检测每行
for j in range(9):
if matrix[row][j] == value:
return False
# 检测每列
for i in range(9):
if matrix[i][col] == value:
return False
# 检测元素所在3*3区域
area_row = (row // 3) * 3
area_col = (col // 3) * 3
for i in range(area_row, area_row + 3):
for j in range(area_col, area_col + 3):
if matrix[i][j] == value:
return False
return True
def solveSudoku(matrix, count=0):
"""
遍历每一个未填元素,遍历1-9替换为合适的数字
"""
if (count == 81): # 递归出口
return True
#行优先遍历
row = count // 9 # 行标
col = count % 9 # 列标
if matrix[row][col] != 0: # 已填充
return solveSudoku(matrix, count=count + 1)
else: # 未填充
for i in range(1, 10):
if check(matrix, row, col, i): # 找到可能的填充数
matrix[row][col] = i
if solveSudoku(matrix, count=count + 1): # 是否可完成
return True # 可完成
# 不可完成
matrix[row][col] = 0 # 回溯
return False # 不可完成
while True:
try:
matrix = []
for i in range(9):
matrix.append([int(i) for i in input().split(' ')])#多维列表输入
solveSudoku(matrix)
for i in range(9):
print( ' '.join(map(str, matrix[i])))
except:
break
HJ45 名字的漂亮度 字符串 中等 29.83%
while True:
try:
a= int(input())
s=[]
for i in range(0, a):
s.append(input().lower())
for each in s:
sum1=0
c=26
count=[]
for i in list(set(each)):
count.append(each.count(i))
count=sorted(count,reverse=1)
for i in count:
sum1+=int(i)*c
c-=1
print(sum1)
except:
break
HJ46 按字节截取字符串 字符串 中等 37.41%
while True:
try:
code = input()
end_num = int(input())
print(code[:end_num])
except:
break
HJ47 线性插值 数组 较难 28.80%
while True:
try:
m,n=map(int,input().split())
num1,val1=map(int,input().split())
print('%d %d'%(num1,val1))
for i in range(1,m):
num2,val2=map(int,input().split())
if num1==num2:
continue
else:
step=int((val2-val1)/(num2-num1))
for j in range(1,num2-num1):
print('%d %d'%(num1+j,val1+step*j))
print('%d %d'%(num2,val2))
num1,val1=num2,val2
except:
break
HJ48 从单向链表中删除指定值的节点 链表 中等 28.64%
while True:
try:
s=input().split()
n=int(s[0])
res=[s[1]]
rm=s[-1]
for i in range(n-1):
a=s[2+i*2]
b=s[3+i*2]
res.insert(res.index(b)+1,a)
res.remove(rm)
print(' '.join(res)+' ')
except:
break#没看懂...
HJ49 多线程 字符串链表栈队列 中等 35.22%
while True:
try:
n = int(input())
print('ABCD'*n)
except:
break
HJ50 四则运算 字符串栈数学 简单 48.85%
print(eval(input().replace('{','(').replace('}',')').replace('[','(').replace(']',')')))
HJ51 输出单向链表中倒数第k个结点 链表 较难 21.45%
while True:
try:
num = int(input())
in_st = input().strip()
k = int(input())
mi_st = in_st.split(' ')
if k == 0:
print(0)
else:
print(mi_st[num-k])
except:
break
HJ52 计算字符串的距离 字符串 中等 33.75%
def compare(a,b):
m,n=len(a),len(b)
dp=list(range(n+1))
for i in range(1,m+1):
pre=dp[::]
dp[0]=i
for j in range(1,n+1):
if a[i-1]==b[j-1]:
dp[j]=pre[j-1]
else:
dp[j]=min(pre[j],pre[j-1],dp[j-1])+1
return dp[-1]
while True:
try:
a=input()
b=input()
if a=='' or b=='':
print(abs(len(a)-len(b)))
else:
print(compare(a,b))
except:
break
HJ53 iNOC产品部-杨辉三角的变形 字符串 简单 42.12%
while True:
try:
n = int(input())
if n < 3:
print(-1)
elif n%2 == 1:
print(2)
elif n%4== 0:
print(3)
else:
print(4)
except:
break
HJ54 表达式求值 字符串数学栈 简单 49.33%
while True:
try:
n = input()
print(eval(n))
except:
break