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])
相关推荐
孟健3 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞5 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽8 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程12 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪12 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook13 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python