Python 编程题 第七节:没出现过的数字、替换空格、快乐数、立方根、最长公共前缀

没出现过的数字

python 复制代码
import random
n=int(input(""))
nums=[]
for i in range(n):
    nums.append(random.randint(1,n))
print(nums)
lst=[]
for i in range(1,n):
    if i not in nums:
        lst.append(i)
print(lst)

替换空格

方法一(replace函数)

python 复制代码
str="Hellow world"
print(str.replace(" ","%"))

方法二(手搓函数)

python 复制代码
str="Hellow world"
def func(s):
    str=""
    for i in s:
        if i !=" ":
            str+=i
        else:
            str+="%"
    return str
print(func(str))

快乐数

很巧妙的方法通过change()函数

python 复制代码
def change(x):
    sum=0
    while x>0:
        j=x%10
        sum+=j*j
        x=x//10
    return sum
def happynum(n):
    while n>9:#当两位数的时候进行转换
        n=change(n)
    if n==1:
        return True
    else:
        return False

print(happynum(18))

立方根

math库里的pow函数

python 复制代码
import math
n=int(input())
res=math.pow(n,1/3)
print(res)

最长公共前缀

先排序,拿最小的去比较

python 复制代码
strs=["abca","abc","abca","abc","abcc","ab","abcccd"]
strs.sort()
s=""
m=len(strs[1])
for i in strs:
    if i[0:m]!=strs[1][0:m]:
        m-=1
print(strs[1][0:m])
相关推荐
databook9 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室9 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三11 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271114 小时前
Python之语言特点
python
刘立军14 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机18 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机19 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i20 小时前
django中的FBV 和 CBV
python·django
c8i20 小时前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python