匿名用户
1级
2017-12-02 回答
导入python提供的random这个库。
Python代码例子
1.输入三个变量,然后按小到大输出
[python] view plain copy
x = int(input('please input x:'))
y = int(input('please input y:'))
z = int(input('please input z:'))
if x > y :
x, y = y, x
if x > z :
x, z = z, x
if y > z :
y, z = z, y
print(x,y,z)
2、求101-200的素数
[python] view plain copy
from math import sqrt
def isprime(n):
k = int(sqrt(n))
for i in range(2,k+1):
if n % i == 0:
return 0
return 1
if __name__ == '__main__':
for n in range(101, 201):
if isprime(n) ==1:
print(n, end = ' ')
[python] view plain copy
版本二:
[python] view plain copy
n = int(input('please input n:'))
for i in range(2,n+1):
j = i
for j in range(2,n):
if i % j ==0:
break
if j == i :
print(i,end=' ')
3.水仙花
[python] view plain copy
for i in range(100,1000):
a = i%10
b = i%100//10
c = i//100
if a**3+b**3+c**3 == i:
print(i, end=' ')
4.分解质因子
[python] view plain copy
n=int(input('please input n:'))
result=[]
i=2
str1=str(n)+'='
while n>1:
if n%i==0:
n/=i
result.append(str(i))
i -= 1
i +=1
str1+='*'.join(result)
print(str1)
函数版
[python] view plain copy
def f(n):
result=[]
i=2
str1=str(n)+'='
while n>1:
if n%i==0:
n/=i
result.append(str(i))
i -= 1
i +=1
str1+='*'.join(result)
return str1
if __name__ == '__main__':
for i in range(80,100):
print(f(i))
5.统计字符串字符个数,空格字符个数,数字字符个数,其他字符个数
[python] view plain copy
import string
s=input('please input string:')
letters = 0
space = 0
digit = 0
others =0
for ch in s:
if ch.isalpha():
letters += 1
elif ch.isspace():
space += 1
elif ch.isdigit():
digit += 1
else:
others += 1
print(letters, space , digit, others)
6.lamba 实现两数求最值
[python] view plain copy
MAX = lambda x, y:(x>y)*x + (y>x)*y
MIN = lambda x, y:(x
if __name__ == '__main__':
print('max={0} , min={1}'.format(MAX(10,2), MIN(10,2)))
7.输入一个整数,如果为奇数那么sum=1+1/3+.....+1/n
如果为偶数那么 sum=1/2+1/4+....+1/n
[python] view plain copy
def f(n):
sum=0.0
if n%2 == 1:
for i in range(1, n+1, 2):
sum += 1/i
else:
for i in range(2, n+1, 2):
sum += 1/i
return sum
if __name__ == '__main__':
n=int(input('please input n:'))
print(f(n))
8.查找一个age最高的name
[python] view plain copy
if __name__ == '__main__':
person = {'shao':23, 'wang':20, 'zhang':21, 'he':22}
flag = 1
maxk=''
for (k, v) in person.items():
if flag == 1:
maxk = k
flag = 0
else:
if person[maxk] < v:
maxk = k
print(maxk, person[maxk])
9.向文件里面输入一串字符
[python] view plain copy
if __name__ == '__main__':
string = input('please input string:')
with open('f:/test.txt', 'a') as file:
file.write(string)
file.close()
10.python 对文件操作,两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排序)
[python] view plain copy
import string
if __name__ == '__main__':
with open('f:/A.txt', 'r') as file_A:
stringA=file_A.read()
with open('f:/B.txt', 'r') as file_B:
stringB=file_B.read()
stringA+=stringB
stringA=list(stringA)
stringA.sort()
stringA=''.join(stringA)
with open('f:/C.txt', 'a') as file_C:
file_C.write(stringA)
file_A.close()
file_B.close()
file_C.close()