Python - 代碼片段,Snippets,Gist
阿新 • • 發佈:2018-06-16
abc col In lee radi [1] pytho del a + b
說明
代碼片段來自網上搬運的或者自己寫的
華氏溫度轉攝氏溫度
"""
將華氏溫度轉換為攝氏溫度
F = 1.8C + 32
Version: 0.1
Author: 駱昊
Date: 2018-02-27
"""
f = float(input(‘請輸入華氏溫度: ‘))
c = (f - 32) / 1.8
print(‘%.1f華氏度 = %.1f攝氏度‘ % (f, c))
輸入圓的半徑計算計算周長和面積
""" 輸入半徑計算圓的周長和面積 Version: 0.1 Author: 駱昊 Date: 2018-02-27 """ import math radius = float(input(‘請輸入圓的半徑: ‘)) perimeter = 2 * math.pi * radius area = math.pi * radius * radius print(‘周長: %.2f‘ % perimeter) print(‘面積: %.2f‘ % area)
輸入年份判斷是不是閏年
"""
輸入年份 如果是閏年輸出True 否則輸出False
Version: 0.1
Author: 駱昊
Date: 2018-02-27
"""
year = int(input(‘請輸入年份: ‘))
# 如果代碼太長寫成一行不便於閱讀 可以使用\或()折行
is_leap = (year % 4 == 0 and year % 100 != 0 or
year % 400 == 0)
print(is_leap)
英制單位與公制單位互換
""" 英制單位英寸和公制單位厘米互換 Version: 0.1 Author: 駱昊 Date: 2018-02-28 """ value = float(input(‘請輸入長度: ‘)) unit = input(‘請輸入單位: ‘) if unit == ‘in‘ or unit == ‘英寸‘: print(‘%f英寸 = %f厘米‘ % (value, value * 2.54)) elif unit == ‘cm‘ or unit == ‘厘米‘: print(‘%f厘米 = %f英寸‘ % (value, value / 2.54)) else: print(‘請輸入有效的單位‘)
擲骰子決定做什麽
""" 擲骰子決定做什麽事情 Version: 0.1 Author: 駱昊 Date: 2018-02-28 """ from random import randint face = randint(1, 6) if face == 1: result = ‘唱首歌‘ elif face == 2: result = ‘跳個舞‘ elif face == 3: result = ‘學狗叫‘ elif face == 4: result = ‘做俯臥撐‘ elif face == 5: result = ‘念繞口令‘ else: result = ‘講冷笑話‘ print(result)
百分制成績轉等級制
"""
百分制成績轉等級制成績
90分以上 --> A
80分~89分 --> B
70分~79分 --> C
60分~69分 --> D
60分以下 --> E
Version: 0.1
Author: 駱昊
Date: 2018-02-28
"""
score = float(input(‘請輸入成績: ‘))
if score >= 90:
grade = ‘A‘
elif score >= 80:
grade = ‘B‘
elif score >= 70:
grade = ‘C‘
elif score >= 60:
grade = ‘D‘
else:
grade = ‘E‘
print(‘對應的等級是:‘, grade)
輸入三條邊長如果能構成三角形就計算周長和面積
"""
判斷輸入的邊長能否構成三角形
如果能則計算出三角形的周長和面積
Version: 0.1
Author: 駱昊
Date: 2018-02-28
"""
import math
a = float(input(‘a = ‘))
b = float(input(‘b = ‘))
c = float(input(‘c = ‘))
if a + b > c and a + c > b and b + c > a:
print(‘周長: %f‘ % (a + b + c))
p = (a + b + c) / 2
area = math.sqrt(p * (p - a) * (p - b) * (p - c))
print(‘面積: %f‘ % (area))
else:
print(‘不能構成三角形‘)
上面的代碼中使用了math模塊的sqrt函數來計算平方根。用邊長計算三角形面積的公式叫做海倫公式。
實現一個個人所得稅計算器
"""
輸入月收入和五險一金計算個人所得稅
Version: 0.1
Author: 駱昊
Date: 2018-02-28
"""
salary = float(input(‘本月收入: ‘))
insurance = float(input(‘五險一金: ‘))
diff = salary - insurance - 3500
if diff <= 0:
rate = 0
deduction = 0
elif diff < 1500:
rate = 0.03
deduction = 0
elif diff < 4500:
rate = 0.1
deduction = 105
elif diff < 9000:
rate = 0.2
deduction = 555
elif diff < 35000:
rate = 0.25
deduction = 1005
elif diff < 55000:
rate = 0.3
deduction = 2755
elif diff < 80000:
rate = 0.35
deduction = 5505
else:
rate = 0.45
deduction = 13505
tax = abs(diff * rate - deduction)
print(‘個人所得稅: ¥%.2f元‘ % tax)
print(‘實際到手收入: ¥%.2f元‘ % (diff + 3500 - tax))
輸入一個數判斷是不是素數
"""
輸入一個正整數判斷它是不是素數
Version: 0.1
Author: 駱昊
Date: 2018-03-01
"""
from math import sqrt
num = int(input(‘請輸入一個正整數: ‘))
end = int(sqrt(num))
is_prime = True
for x in range(2, end + 1):
if num % x == 0:
is_prime = False
break
if is_prime and num != 1:
print(‘%d是素數‘ % num)
else:
print(‘%d不是素數‘ % num)
輸入兩個正整數,計算最大公約數和最小公倍數
"""
輸入兩個正整數計算最大公約數和最小公倍數
Version: 0.1
Author: 駱昊
Date: 2018-03-01
"""
x = int(input(‘x = ‘))
y = int(input(‘y = ‘))
if x > y:
(x, y) = (y, x)
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
print(‘%d和%d的最大公約數是%d‘ % (x, y, factor))
print(‘%d和%d的最小公倍數是%d‘ % (x, y, x * y // factor))
break
打印三角形圖案
"""
打印各種三角形圖案
*
**
***
****
*****
*
**
***
****
*****
*
***
*****
*******
*********
Version: 0.1
Author: 駱昊
Date: 2018-03-01
"""
row = int(input(‘請輸入行數: ‘))
for i in range(row):
for _ in range(i + 1):
print(‘*‘, end=‘‘)
print()
for i in range(row):
for j in range(row):
if j < row - i - 1:
print(‘ ‘, end=‘‘)
else:
print(‘*‘, end=‘‘)
print()
for i in range(row):
for _ in range(row - i - 1):
print(‘ ‘, end=‘‘)
for _ in range(2 * i + 1):
print(‘*‘, end=‘‘)
print()
實現計算求最大公約數和最小公倍數的函數
def gcd(x, y):
(x, y) = (y, x) if x > y else (x, y)
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
return factor
def lcm(x, y):
return x * y // gcd(x, y)
實現判斷一個數是不是回文數的函數
def is_palindrome(num):
temp = num
total = 0
while temp > 0:
total = total * 10 + temp % 10
temp //= 10
return total == num
實現判斷一個數是不是素數的函數
def is_prime(num):
for factor in range(2, num):
if num % factor == 0:
return False
return True if num != 1 else False
寫一個程序判斷輸入的正整數是不是回文素數
if __name__ == ‘__main__‘:
num = int(input(‘請輸入正整數: ‘))
if is_palindrome(num) and is_prime(num):
print(‘%d是回文素數‘ % num)
在屏幕上顯示跑馬燈文字
import os
import time
def main():
content = ‘北京歡迎你為你開天辟地…………‘
while True:
# 清理屏幕上的輸出
os.system(‘cls‘) # os.system(‘clear‘)
print(content)
# 休眠200毫秒
time.sleep(0.2)
content = content[1:] + content[0]
if __name__ == ‘__main__‘:
main()
設計一個函數產生指定長度的驗證碼,驗證碼由大小寫字母和數字構成
import random
def generate_code(code_len=4):
"""
生成指定長度的驗證碼
:param code_len: 驗證碼的長度(默認4個字符)
:return: 由大小寫英文字母和數字構成的隨機驗證碼
"""
all_chars = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘
last_pos = len(all_chars) - 1
code = ‘‘
for _ in range(code_len):
index = random.randint(0, last_pos)
code += all_chars[index]
return code
設計一個函數返回給定文件名的後綴名
def get_suffix(filename, has_dot=False):
"""
獲取文件名的後綴名
:param filename: 文件名
:param has_dot: 返回的後綴名是否需要帶點
:return: 文件的後綴名
"""
pos = filename.rfind(‘.‘)
if 0 < pos < len(filename) - 1:
index = pos if has_dot else pos + 1
return filename[index:]
else:
return ‘‘
設計一個函數返回傳入的列表中最大和第二大的元素的值
def max2(x):
m1, m2 = (x[0], x[1]) if x[0] > x[1] else (x[1], x[0])
for index in range(2, len(x)):
if x[index] > m1:
m2 = m1
m1 = x[index]
elif x[index] > m2:
m2 = x[index]
return m1, m2
計算指定的年月日是這一年的第幾天
def is_leap_year(year):
"""
判斷指定的年份是不是閏年
:param year: 年份
:return: 閏年返回True平年返回False
"""
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
def which_day(year, month, date):
"""
計算傳入的日期是這一年的第幾天
:param year: 年
:param month: 月
:param date: 日
:return: 第幾天
"""
days_of_month = [
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
][is_leap_year(year)]
total = 0
for index in range(month - 1):
total += days_of_month[index]
return total + date
def main():
print(which_day(1980, 11, 28))
print(which_day(1981, 12, 31))
print(which_day(2018, 1, 1))
print(which_day(2016, 3, 1))
if __name__ == ‘__main__‘:
main()
打印楊輝三角
def main():
num = int(input(‘Number of rows: ‘))
yh = [[]] * num
for row in range(len(yh)):
yh[row] = [None] * (row + 1)
for col in range(len(yh[row])):
if col == 0 or col == row:
yh[row][col] = 1
else:
yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]
print(yh[row][col], end=‘\t‘)
print()
if __name__ == ‘__main__‘:
main()
雙色球選號
from random import randrange, randint, sample
def display(balls):
"""
輸出列表中的雙色球號碼
"""
for index, ball in enumerate(balls):
if index == len(balls) - 1:
print(‘|‘, end=‘ ‘)
print(‘%02d‘ % ball, end=‘ ‘)
print()
def random_select():
"""
隨機選擇一組號碼
"""
red_balls = [x for x in range(1, 34)]
selected_balls = []
for _ in range(6):
index = randrange(len(red_balls))
selected_balls.append(red_balls[index])
del red_balls[index]
# 上面的for循環也可以寫成下面這行代碼
# sample函數是random模塊下的函數
# selected_balls = sample(red_balls, 6)
selected_balls.sort()
selected_balls.append(randint(1, 16))
return selected_balls
def main():
n = int(input(‘機選幾註: ‘))
for _ in range(n):
display(random_select())
if __name__ == ‘__main__‘:
main()
可以使用random模塊的sample函數來實現從列表中選擇不重復的n個元素。
約瑟夫環問題
"""
《幸運的基督徒》
有15個基督徒和15個非基督徒在海上遇險,為了能讓一部分人活下來不得不將其中15個人扔到海裏面去,有個人想了個辦法就是大家圍成一個圈,由某個人開始從1報數,報到9的人就扔到海裏面,他後面的人接著從1開始報數,報到9的人繼續扔到海裏面,直到扔掉15個人。由於上帝的保佑,15個基督徒都幸免於難,問這些人最開始是怎麽站的,哪些位置是基督徒哪些位置是非基督徒。
"""
def main():
persons = [True] * 30
counter, index, number = 0, 0, 0
while counter < 15:
if persons[index]:
number += 1
if number == 9:
persons[index] = False
counter += 1
number = 0
index += 1
index %= 30
for person in persons:
print(‘基‘ if person else ‘非‘, end=‘‘)
if __name__ == ‘__main__‘:
main()
Python - 代碼片段,Snippets,Gist