Python - 代码片段,Snippets,Gist

说明

代码片段来自网上搬运的或者自己写的

华氏温度转摄氏温度

f = float(input('请输入华氏温度: '))
c = (f - 32) / 1.8
print('%.1f华氏度 = %.1f摄氏度' % (f, c))

输入圆的半径计算计算周长和面积

import math

radius = float(input('请输入圆的半径: '))
perimeter = 2 * math.pi * radius
area = math.pi * radius * radius
print('周长: %.2f' % perimeter)
print('面积: %.2f' % area)

输入年份判断是不是闰年

year = int(input('请输入年份: '))
# 如果代码太长写成一行不便于阅读 可以使用\或()折行
is_leap = (year % 4 == 0 and year % 100 != 0 or
           year % 400 == 0)
print(is_leap)

英制单位与公制单位互换

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('请输入有效的单位')

掷骰子决定做什么

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)

百分制成绩转等级制


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)

输入三条边长如果能构成三角形就计算周长和面积

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函数来计算平方根。用边长计算三角形面积的公式叫做海伦公式。

实现一个个人所得税计算器

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))

输入一个数判断是不是素数

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)

输入两个正整数,计算最大公约数和最小公倍数

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

打印三角形图案

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 random_str(random_length=8):
    str = ''
    # 生成字符串的可选字符串
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(random_length):
        str += chars[random.randint(0, length)]
    return str

设计一个函数返回给定文件名的后缀名

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()

数字时钟

from time import sleep


class Clock:
    """[数字时钟]

    Args:

    """

    def __init__(self, hour=0, minute=0, second=0):
        """[初始化时间]
            hour (int, optional): Defaults to 0. [Representing hour]
            minute (int, optional): Defaults to 0. [Representing minute]
            second (int, optional): Defaults to 0. [Representing second]
        """

        self._hour = hour
        self._minute = minute
        self._second = second

    def run(self):
        """[走字]

        Bad:
            1. 面条代码(spagetti code)
        """

        while True:
            print(self)
            self._second += 1
            if self._second == 60:
                self._second = 0
                self._minute += 1

                if self._minute == 60:
                    self._minute = 0
                    self._hour += 1

                    if self._hour == 24:
                        self._hour = 0
            sleep(1)

    def __str__(self):
        """[显示时间]
        """
        return '%02d:%02d:%02d' % (self._hour, self._minute, self._second)


def main():
    """[主程序入口]
    """
    clock = Clock(9, 11, 57)
    clock.run()

if __name__ == '__main__':
    main()

二维坐标

from math import sqrt


class Point:
    """[二维坐标,用(x,y)表示]
    """

    def __init__(self, x=0, y=0):
        """[坐标构造函数]
            x (int, float, optional): Defaults to 0. [坐标x]
            y (int, float, optional): Defaults to 0. [坐标y]
        """

        self.x = x
        self.y = y

    def move_to(self, x, y):
        """[移动到指定位置]
        
        Args:
            x ([int, float]): [新的坐标x]
            y ([int, float]): [新的坐标y]
        """
        self.x = x
        self.y = y 

    
    def moved_by(self, dx, dy):
        """[移动指定的增量]
        
        Args:
            dx ([int, float]): [坐标x的增量]
            dy ([int, float]): [坐标y的增量]
        """
        self.x += dx
        self.y += dy

    def distance_to(self, other):
        """[计算到另一个坐标的距离]
        
        Args:
            other ([class Point]): [另一个坐标]
        """
        dx = self.x - other.x
        dy = self.y - other.y
        return sqrt(dx ** 2 + dy ** 2)

    def __str__(self):
        """[调用print()的时候,调用此方法,for users!]
        """
        return '(%s, %s)' % (str(self.x), str(self.y))


def main():
    p1 = Point(3, 5)
    p2 = Point()

    print(p1)
    print(p2)

    p2.moved_by(-1, 2)

    print(p2)

    print(p1.distance_to(p2))


if __name__ == '__main__':
    main()

用装饰器模拟session,或者说用装饰器实现验证功能

user_session = {'username': None, 'login_status': False}


def login_required(func):
    def wrapper(*args, **kwargs):
        if user_session['username'] and user_session['login_status']:
            func(*args, **kwargs)
        else:
            print('没有足够权限')
    return wrapper


def auth_func(func):
    def wrapper(*args, **kwargs):
        username = input('用户名: ').strip()
        password = input('密码: ').strip()
        if username == 'sb' and password == '123':
            user_session['username'] = username
            user_session['login_status'] = password
            func(*args, **kwargs)
        else:
            print('用户名或者密码错误')

    return wrapper


@auth_func
def index():
    print('欢迎来到京东')


@login_required
def home(name):
    print('欢迎回家%s' % name)


@login_required
def shopping_cart():
    print('购物车里有 [%s,%s,%s]' % ('袜子', '鞋子', '娃娃'))


index()
home('allen')
shopping_cart()

判断是否属于类的方法(method)

def hasmethod(obj, name):
    return hasattr(obj, name) and isinstance(getattr(obj, name), types.MethodType)

BeautifulSoup提取优化

def get_sub_soup(soup, rules):
    if isinstance(rules, (list, tuple)):
        for rule in rules:
            soup = get_sub_soup(soup, rule)

            next_sibling = rule.pop("find_next_sibling", None)
            if soup and next_sibling:
                soup = soup.find_next_sibling(next_sibling)
    elif isinstance(rules, dict):
        temp = rules.pop("find_next_sibling", None)
        if soup:
            soup = soup.find(**rules)
        rules.update(find_next_sibling=temp)

    return soup

def ismethod(obj, name):
    return hasattr(obj, name) and isinstance(getattr(obj, name), types.MethodType)

def get_soup_attr(obj, attrs):
    if isinstance(attrs, (list, tuple)):
        result = obj
        for attr in attrs:
            result = get_soup_attr(result, attr)
    else:
        if isinstance(obj, dict):
            result = obj.get(attrs)
        elif ismethod(obj, attrs):
            result = getattr(obj, attrs)()
        elif isinstance(obj, Tag):
            result = getattr(obj, attrs)
        else:
            return obj

    return result


def parse_soup(soup, rules, attrs, default_result=None):
    """

    :param soup: soup
    :param rules: [{'name': 'div'}, {'name': 'a'}]
    :param attrs: "text" or ["text"] or ["attrs", "href"]
    :param default_result: '' or []
    :return:
    """
    result = default_result
    soup = get_sub_soup(soup, rules)
    if soup:
        result = get_soup_attr(soup, attrs)

    return result

完全去除空格

class SpacesRemover(object):
    """
    去除空格
    """

    def __call__(self, s):
        return ''.join(s.split())

    def __ror__(self, s):
        return self(s)


remove_spaces = SpacesRemover()
posted @ 2018-06-16 16:40  Rocin  阅读(422)  评论(0编辑  收藏  举报