1.判断回文
类似‘aa','aba','abcba','abccba'就是回文
def huiwen(char):
length=len(char)
for i in range(length//2):
if char[i] != char[length-1-i]:
return False
return True
# 使用递归
def huiwen(char):
print(char)
length=len(char)
if length <= 1:
return True
else:
return char[0] == char[-1] and huiwen(char[1:-1])
2.利用sort函数的key关键字排序
class Tu():
def __init__(self, name, amount):
self.name = trader
self.amount = amount
data = [
Tu('d',10000000),
Tu('a', 1000),
Tu('b',10000),
Tu('c',100000),
]
# 通过匿名函数传入要排序的项
def sort_by_amount(data):
data.sort(key=lambda x:x.amount)
return data
3. 检查一个日期,跟当月某个星期几的关系
from datetime import datetime
def _parse(date):
"""
:param date: string '20180911'
:return: datetime
"""
return datetime.strptime(date, "%Y%m%d")
def _check_day(date, day=5):
"""
判定是否是星期几
:param date: datetime
:param day: int,周一为1,周五为5,周天为7
:return:
"""
return date.weekday() + 1 == day
def _count_days(date):
"""
计算日期当月有多少天
:param date: datetime
:return: int
"""
year = date.year
month = date.month
if month == 12:
next_month = 1
next_year = year + 1
else:
next_month = month + 1
next_year = year
return (datetime(next_year, next_month, 1) - datetime(year, month, 1)).days
def _check_date(date, num, day):
"""
日期有没有过该月第几个周几
:param date: string 例如'20180101'
:param num: int,第几个"day"
:param day: int,周几,周一是1,周五是5,周天是7
:return:
"""
count = 0
flag = None
date = _parse(date)
days = _count_days(date)
for i in range(1, days):
the_day = datetime(date.year, date.month, i)
if _check_day(the_day, day):
count += 1
if count == num:
flag = the_day
break
if flag and date > flag:
return True
else:
return False
def CheckDate(date):
return _check_date(date, 3, 5)