先记录三个面试题
获取list中重复次数最多的一个数
def countFreNum(targetList):
"""
获取list中重复次数最多的一个数
方案:通过遍历list,将list元素添加到dict中的key,重复次数作为value,对value做排序找出重复次数最多的元素
:param targetList: 入参
:return:
"""
#
if not isinstance(targetList, list):
return "目标内容非list"
if len(targetList) == 0:
return "目标list内容为空"
# 保存统计结果到dict中
res = {}
for i in targetList:
if i in res.keys():
res[i] = res[i] + 1
else:
res[i] = 1
print (res)
# 将dict中value转为list 遍历list排序
valueList = list(res.values())
for li in range(len(valueList) - 1):
for lj in range(li+1, len(valueList)):
if valueList[li] <= valueList[lj]:
valueList[li], valueList[lj] = valueList[lj], valueList[li]
print(valueList)
# 取最大的value值 遍历dict取key值 出现次数最多的数,可能不止一个
freNum =[]
for k, v in res.items():
if v == valueList[0]:
freNum.append(k)
print("重复出现次数最多的数:" + ', '.join(str(i) for i in freNum) + ", 重复出现" + str(valueList[0]) + "次")
return freNum
查找字符串中对应字符串,并替换
def replaceStr(rStr, reStr, repStr):
"""
查找字符串中对应字符串,并替换
方案: 循环做查找替换操作,用while, for循环会叠字查找多次问题(补充说明)("aaaaaaab", "aa")
:param rStr: 原字符串
:param reStr: 要查找替换的字符串
:param repStr: 要替换为的字符串
:return:
"""
targetStr = ""
reLen = len(reStr)
count = 0
while count < len(rStr):
print( count)
if rStr[count:count + reLen] == reStr:
targetStr = targetStr + repStr
count = count + reLen
else:
targetStr = targetStr + rStr[count]
count = count + 1
print(targetStr)
return targetStr
获取输入整数的最小不重复数
def minNum(num):
"""
获取输入参数的最小不重复数
不重复数定义:每一位上的数与相邻的两个数都不相等
方案: 遍历一个数字所有位上的数,如果出现任意一个两个相邻的数相等即不是要找的数
:param num: 原数据
:return: 不重复数
"""
if not isinstance(num, int):
return "目标内容非整数数值"
if num < 10:
return num
tag = True
while tag:
num = num + 1
numStr = str(num)
count = 0
for i in range(0, len(numStr)-1):
if numStr[i] == numStr[i+1]:
count = count + 1
if count == 0:
break
print(num)
return num