python基础面试常问编程问题
程序员文章站
2022-07-08 15:49:05
求数值以内的质数,合数及个数#质数def zhishu(number): num=0 for i in range(2,number+1): k=True for j in range(2,i): if i==j: continue if(i%j==0): k=False break if(k==T...
求数值以内的质数,合数及个数
#质数
def zhishu(number):
num=0
for i in range(2,number+1):
k=True
for j in range(2,i):
if i==j:
continue
if(i%j==0):
k=False
break
if(k==True):
print("%d"%i)
num=num+1
print("素数个数%d"%num)
# 合数
def heshu(number):
num = []
for i in range(2,number+1):
for j in range(2,i):
if i==j:
continue
if i%j==0:
print(i)
num.append(i)
break
print(f'{number}以内合数个数:{len(num)}')
九九乘法表
#九九乘法表1
for i in range(1,10):
for j in range(1,i+1):
print('%d*%d=%d'%(i,j,i*j)+'\t',end='') #常用格式化方式#d,%s
print(f'{i}*{j}={i*j}\t',end='') #f-string量格式化字符串
print()
#九九乘法表2
n = 1
while n<=9:
i=1
while i<=n:
print(f'{i}*{n}={i*n}',end=' ')
i=i+1
n=n+1
print()
x,y由人为输入的整数,求x的y次方,不允许使用**
x = int(input('请输入X:'))
y = int(input('请输入Y:'))
res = x
for i in range(y-1):
res *=x
print(res)
裴波那契数列
# 方法1,递归对性能要求较大
def func(x):
if x==0 or x ==1:
return 1
else:
return func(x-1)+func(x-2)
for i in range(10):
print(func(i))
# 方法2,循环方式
def loop(n):
a,b= 1,1
while n>0:
a,b= b,a+b
n-=1
return a
for i in range(10):
print(loop(i))
水仙花数(水仙花数指153=13+53+3**3,位数立方之和等于该数)
for i in range(100,1000):
a = i//100
b = (i-a*100)//10
c = (i-a*100-b*10)
if i == pow(a,3)+pow(b,3)+pow(c,3):
print(i)
冒泡排序
def new_sort(arr):
for i in range(len(arr)):
for j in range(0,len(arr)-i-1):
if arr[j]>arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
list1 = [64, 34, 25, 12, 22, 11, 90]
new_sort(list1)
本文地址:https://blog.csdn.net/qq_42484209/article/details/110825768