匿名使用者
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()