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])
相关推荐
金銀銅鐵13 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1118 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0020 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent
星云穿梭2 天前
用Python写一个带图形界面的学生管理系统——完整教程
python