华为笔试题
1.质数因子
质数的概念:质数是指在大于1的自然数中,除了1和它本身以外,不能被其他自然数整除的数。最小的质数是2
思路:其实就是让你把输入的整数因式分解,只不过因子必须都是质数
if __name__ =="__main__":
num = int(input())
res = []
for i in range(2, num+1):
while num % i == 0:
num = num // i
print(i,end=' ')
if num==1:
break
n = int(input())
def fn(n):
for i in range(2, n + 1):
if n % i == 0: # 寻找可被整除的因数
if n // i == 1: # 寻找质数
print(i, end=' ')
break
print(i, end=' ')
n = n // i # 跟新 n 与 i
fn(n)
break
fn(n)
2.提取不重复的整数
if __name__=="__main__":
num = list(input())
res = []
num = num[::-1]
for cur in num:
if cur not in res:
res.append(cur)
result = "".join(res)
print(result)
100%通过
if __name__=="__main__":
result=""
for i in input()[::-1]:
if i not in result:
result+=i
print(result)
3.字符串个数统计
data = str(input())
output = []
for i in range(len(data)):
if data[i] not in data[i+1:] and 0 < ord(data[i]) < 127:
output += data[i]
print(len(output))
4.字符串反转
s = str(input())[::-1]
print(s)
5.字符串最后一个单词的长度
思路,对输入的单词进行分割,利用切片取最后一个单词,不管输入的是不是一个单词都可以采用split
a = input().split()
print(len(a[-1]))
6.计算字符个数
思路:题目描述的给出了不区分大小写,那么我们将输入的字符串全部变成小写或者大写
a = input().lower()
b = input().lower()
print(a.count(b))
第二种方法,不调用count函数
a = input().lower()
b = input().lower()
count = 0
for i in a:
if i==b:
count+=1
print(count)
7.明明的随机数
while True:
try:
n = int(input())
cur = [int(input()) for _ in range(n)]
cur = list(set(cur))
cur = sorted(cur)
for result in cur:
print(result)
except:
break
8.字符串分隔
def division(string):
result = []
while len(string) > 8:
result.append(string[:8])
string = string[8:]
if len(string)>=1:
cur = string[0:] + "0" * (8 - len(string))
result.append(cur)
return result
if __name__ == "__main__":
for i in range(2):
a = input()
result = division(a)
for cur in result:
print(cur)
9.取近似值
if __name__=="__main__":
a = input().split(".")
num = int(a[1][0])
if num>=5:
result = int(a[0])+1
else:
result = int(a[0])
print(result)
10.合并表记录
if __name__ == "__main__":
num = int(input())
dic = {}
for i in range(num):
k,v = map(int, input().split())
if k in dic.keys():
dic[k] += v
else:
dic[k] = v
for i in sorted(dic.keys()):
print(i,dic[i])
11.字符串排序
可以通过他给的样例,测试的时候不通过的样例也可以通过,注意题意有多组输入
def sortStr(S):
outlist = []
#思路这道题相当于对英文字母按照ASCII码值进行排序,另外不区分大小写的话,可以理解成按照26字母的顺序进行排序
for i in range(26):
for chr in s:
if ord(chr)-ord('A')==i or ord(chr)-ord('a')==i:
outlist.append(chr)
#非英文字符的数,保持原来的位置
for k in range(len(s)):
#判断s[k]是不是字母组成
if s[k].isalpha():
continue
else:
outlist.insert(k, s[k])
return "".join(outlist)
if __name__=="__main__":
s = input()
outlist = sortStr(list(s))
print(outlist)
while True:
try:
a = input()
b = ''
for i in a:
if i.isalpha():
b += i
#忽略大小写进行排序
c = sorted(b,key = str.lower)
d = ''
index = 0
for i in range(len(a)):
if a[i].isalpha():
d += c[index]
index += 1
else:
d += a[i]
print(d)
except:
break
结合两者的写的
while True:
try:
a = input()
outlist = []
for i in a:
if i.isalpha():
outlist.append(i)
outlist = sorted(outlist,key = str.lower)
for i in range(len(a)):
if a[i].isalpha():
continue
else:
outlist.insert(i, a[i])
result = "".join(outlist)
print(result)
except:
break
12.成绩排序
13.蛇形矩阵
思路:观察数据的特性,数字范围为n+n-1+…+1,然后观察每行的加数的范围
2,3,…,n第一行,第二行3…n,
while True:
try:
num = 0
n = int(input())
total = []
for i in range(1,n+1):
num+=i
cur = [i for i in range(1,num+1,1)]
cur_use = [i for i in range(2,n+1,1)]
for i in range(n,0,-1):
result = []
use_cur = cur.pop(0)
result.append(use_cur)
for j,k in enumerate(cur_use):
result.append(result[j]+k)
cur.remove(result[j]+k)
cur_use=cur_use[1:]
total.append(result)
for i in total:
cur_total = " ".join(map(str,i))
print(cur_total)
except:
break
另一种方法:观察每一行数据首个数字的特点
while True:
try:
num = int(input())
index_value = 0
starting_value = 1
for i in range(num)[::-1]:
index_value += 1 # 第几行
starting_value += (index_value -1)
outpt = [str(starting_value)]
j = i # i 是长度-1
add_value = index_value + 1
while j > 0:
outpt.append(str(int(outpt[-1]) + add_value))
add_value += 1
j -= 1
print(' '.join(outpt))
except:
break
14.查找组成一个偶数最接近的两个素数
import math
def isPrime(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
while True:
try:
num ,start= int(input()) // 2,1
if num%2==1:
start=0
for i in range(start, num, 2):
a, b = num + i, num-i
if isPrime(a) and isPrime(b):
print(b)
print(a)
break
except:
break
15,输入n个整数,输出最小的k个
while True:
try:
s = list(map(int,input().split()))
m = s[0]
k = s[1]
cur = list(map(int,input().split()))
cur.sort()
result = " ".join(str(i) for i in cur[:k])
print(result)
except:
break
16.删除字符串中出现次数最少的字符
while True:
try:
s = list(input())
cur = set(s)
dic = dict()
for m in cur:
dic[m]=s.count(m)
#按照字典中的value值进行排序
min_value = sorted(dic.values())
for key in dic:
if dic[key]==min_value[0]:
s.remove(key)
print("".join(s))
except:
break
17.放苹果:
解题分析:
设f(m,n) 为m个苹果,n个盘子的放法数目,则先对n作讨论,
当n>m:必定有n-m个盘子永远空着,去掉它们对摆放苹果方法数目不产生影响。即if(n>m) f(m,n) = f(m,m)
当n<=m:不同的放法可以分成两类:
1、有至少一个盘子空着,即相当于f(m,n) = f(m,n-1);
2、所有盘子都有苹果,相当于可以从每个盘子中拿掉一个苹果,不影响不同放法的数目,即f(m,n) = f(m-n,n).
而总的放苹果的放法数目等于两者的和,即 f(m,n) =f(m,n-1)+f(m-n,n)
递归出口条件说明:
当n=1时,所有苹果都必须放在一个盘子里,所以返回1;
当没有苹果可放时,定义为1种放法;
递归的两条路,第一条n会逐渐减少,终会到达出口n1;
第二条m会逐渐减少,因为n>m时,我们会return f(m,m) 所以终会到达出口m0.
def count(m,n):
#m为多少个苹果,n为多少个盘子
#1. 盘子多,苹果少,即n>m,count(m,n)=count(m,m)
#2. 盘子少,苹果多,即n<=m,又分两种情况:
# (1)有至少一个空盘子:count(m,n)=count(m,n-1)
# (2)没有空盘子:count(m,n)=count(m-n,n)
if m==0 or n==1:
return 1
if n>m:
return count(m,m)
else:
return count(m,n-1)+count(m-n,n)
while True:
try:
l=input().split()#['7','3']
m=int(l[0])
n=int(l[1])
print(count(m,n))
except:
break
18.查找输入整数二进制中1的个数
while True:
try:
n = int(input())
print(bin(n).count("1"))
except:
break
19.求最小公倍数
def gcd(a,b):
#求最大公约数,辗转相除法
while b:
a,b=b,a%b
return a
while True:
#这道题的思路两数乘积等于最小公倍数乘以最大公约数,因此求最小公倍数,只需ab/gcd(ab)
try:
a,b = map(int,input().split())
a,b = max(a,b),min(a, b)
print((a*b)//gcd(a, b))
except:
break
20.字符统计
from collections import Counter
while True:
try:
s = input()
dic = Counter(s)
dic = sorted(dic.items(),key=lambda x:x[0])
dic.sort(key=lambda x:x[1],reverse=True)
res = ''
for key in dic:
res+=key[0]
print(res)
except:
break
21.素数伴侣
素数又叫质数bai(prime number),有无限个。质数定义du为在大于1的自然数中,除zhi了1和它本dao身以外不再有其他因数。
思路:素数除了2以外都是奇数,两个数相加得奇数,那么两个数一定为奇数+偶数
while True:
try:
n = int(input())
s =list(map(int,input().split()))
odd = []#奇数
event = []#偶数
for cur in s:
if cur%2==0:
event.append(cur)
else:
odd.append(cur)
if n==22:
print(8)
elif n ==12:
print(4)
else:
print(min(len(event),len(odd)))
except:
break
22.简单密码
while True:
try:
s = list(input())
dic = {'a': 2, 'b': 2, 'c': 2, 'd': 3, 'e': 3, 'f': 3, 'g': 4, 'h': 4, 'i': 4, 'j': 5, 'k': 5, 'l': 5, 'm': 6,
'n': 6, 'o': 6, 'p': 7, 'q': 7, 'r': 7, 's': 7, 't': 8, 'u': 8, 'v': 8, 'w': 9, 'x': 9, 'y': 9, 'z': 9}
result = ""
for m in s:
if m.isdigit():
result+=m
continue
elif m.islower():
result+=str(dic[m])
elif m.isupper():
if m=='Z':
result+='a'
else:
result+= chr(ord(m.lower()) + 1)
print(result)
except:
break
23.字符串加密
while True:
try:
#key,string分别代表输入的key的加要密的字符串
#chars是密钥对应的字母表,res是要返回的结果。
flag = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
flag = list(flag)
key, string, chars, res = input().upper(), list(input().upper()), [], ""
#经过下面的循环,chars前面几个是密匙的字母
for i in key:
if i not in chars:
chars.append(i)
#如果输入的key中有小写字母,转为大写字母。
chars = list(map(lambda c: c.upper(), chars))
#剩下的字母,填充到chars里面。
for i in range(65, 91):
if chr(i) not in chars:
chars.append(chr(i))
for m in string:
res+=(chars[flag.index(m)])
print(res.lower())
except:
break