1.判斷回文
類(lèi)似‘a(chǎn)a','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函數(shù)的key關(guān)鍵字排序
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),
]
# 通過(guò)匿名函數(shù)傳入要排序的項(xiàng)
def sort_by_amount(data):
data.sort(key=lambda x:x.amount)
return data
3. 檢查一個(gè)日期,跟當(dāng)月某個(gè)星期幾的關(guān)系
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):
"""
計(jì)算日期當(dāng)月有多少天
: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):
"""
日期有沒(méi)有過(guò)該月第幾個(gè)周幾
:param date: string 例如'20180101'
:param num: int允华,第幾個(gè)"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)