Python基础【素数判断、插入字符串、插入排序】

简介: Python基础【素数判断、插入字符串、插入排序】

输出0~n的所有素数

# 请输入一个整数 num
num = int(input('请输入一个整数: '))
def check(num):
    for i in range(2,num+1):
        if num%i==0 and num!=i:
            return False
    return True
# 输出 1 - num(含) 中的所有的素数
for i in range(2,num+1):
    if check(i):
        print(i)

指定位置插入字符串

s = 'abcdefghijklmnopqrstuvwxyz'
text = input()
index = int(input())
res = s[:index]+text+s[index:]
print(res)

插入排序

def insertion_sort(list_sort):
    for i in range(len(list_sort)):
        j = i-1
        while j>=0 and list_sort[j]>list_sort[j+1]:
            tmp = list_sort[j]
            list_sort[j]=list_sort[j+1]
            list_sort[j+1]=tmp
            j = j-1
    return list_sort  # 需要返回排序后的列表
# 测试代码
list_sort=[1,2,5,4,2,8]
insertion_sort(list_sort)
print(list_sort)  # 输出为 [1, 2, 2, 4, 5, 8]
相关文章
|
2月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
297 100
|
2月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
407 99
|
2月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
2月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
2月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
2月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
3月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
297 0
|
3月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
271 92
|
3月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。