#!usr/bin/python
# -*- coding: utf-8 -*-
# 字串去重後排序
from functools import reduce
s = "sheckjffs"
str_list = list(set(s))
str_list.sort()
s = "".join(str_list)
print(s)
# 列表擴充套件
a = [2, 4, 7, 1]
b = [4, 6, 8, 3]
a.extend(b)
# 氣泡排序
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
bubbleSort(a)
# 列表獲取偶數位元素
a = [1, 2, 3, 4]
b = [i for i in a if i % 2 == 1]
print(b)
# 字典刪除元素合併字典
a = {"a": "b", "c": "d"}
a.pop("a")
b = {"e": "f"}
a.update(b)
print(a)
# 下列輸出是啥
def test_1(x, y, z):
if x > 0 and y == 0:
z = z + x
return z
elif x == 2 or z > 1:
return z + 1
else:
return z
def add(n, i):
return n + i
def test():
for i in range(4):
yield i
g = test()
for n in [1, 10, 5]:
g = (add(n, i) for i in g)
print("===========")
print(list(g))
# 所有的結果都是生成器表達式,不呼叫它,不從裏面取值就不會取值
# 當n=1時,g=(add(1, i) for i in g),其中g=test()即g =(add(1, i) for i in test()) 結果是1,2,3,4
# 當n=10時,括號裏邊的g是上一次回圈結束時的g,即括號中的g g =(add(1, i) for i in test()),
# 括號外的g=(add(10, i) for i in (add(10, i) for i in test()))
n = 1
g = (add(n, i) for i in test())
print(next(g))
# print(list(g)) # [1, 2, 3, 4]
n = 10
g = (add(n, i) for i in (add(n, i) for i in test()))
# print(list(g)) # [20, 21, 22, 23]
n = 5
g = (add(n, i) for i in (add(n, i) for i in (add(n, i) for i in test())))
g = (add(n, i) for i in (add(n, i) for i in (5, 6, 7, 8)))
g = (add(n, i) for i in (10, 11, 12, 13))
g = (15, 16, 17, 18)
L = [1, 2, 3, 5, 6]
B = "".join([str(i) for i in L])
# ls cd pwd mv cp touch mkdir cat wc su rm -rf kill -9 ifconfig
# 給列表中的字典排序:假設有如下 list 物件
alist = [{"name": "a", "age": 20}, {"name": "b", "age": 30}, {"name": "c", "age": 25}]
# 將 alist 中的元素按照 age 從大到小排序。
# 答:利用list的內建函數sort來進行排序
alist = [{"name": "a", "age": 20}, {"name": "b", "age": 30}, {"name": "c", "age": 25}]
alist.sort(key=lambda x: x['age'], reverse=True)
print(alist)
# 將a,b he爲字典
a = ['a', 'b', 'c', 'd', 'e']
b = [1, 2, 3, 4, 5]
c = dict(zip(a, b))
print(c)
# zip() 函數用於將可迭代的物件作爲參數,將物件中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。
# 如果各個迭代器的元素個數不一致,則返回列表長度與最短的物件相同,利用 * 號操作符,可以將元組解壓爲列表。
# selenium 中難點介紹:1.多級frame,2.元素等待,使用WebDriverWait和expected_conditions 進行回圈等待查詢元素,超時就退出。3.下載框不屬於瀏覽器的需要用
# PyuserInput中的pykeyboard進行處理4.selenium 無法處理的一些操作使用execute_js執行js操作來進行卷軸等操作
def binary_search1(alist, target):
low = 0
hight = len(alist)
while low < hight:
mid = int((low + hight) / 2)
guess = alist[mid]
if guess == target:
return mid
elif guess > target:
hight = mid
elif guess < target:
low = mid + 1
return -1
# def binary_search(alist, target, low, high):
# mid = int((low + high) / 2)
# if alist[mid] == target:
# return mid
# elif alist[mid] < target:
# return binary_search(alist, target, mid, high)
# elif alist[mid] > target:
# return binary_search(alist, target, low, mid)
# 二進制和十進制轉換
def ten_to_bin(num):
'''
十進制轉二進制,取餘數,然後餘數到過來
:param num:
:return:
'''
result = ''
while num != 0:
yu = num % 2
num = num // 2
print(num, yu)
result = str(yu) + result
return result
def bin_to_ten(num):
'''
二進制轉十進制,對應位置數位乘以2的(n-i-1)次方,n爲數位長度
:param num:
:return:
'''
n = len(str(num))
result = 0
for i in range(n):
result = result + int(2 ** (n - i - 1)) * int(str(num)[i])
return result
print("============5252=======")
print(ten_to_bin(21))
print(bin_to_ten(10101))
# 字典按照鍵或值排序
my_dict = {'lilee': 25, 'age': 24, 'phone': 12}
print(dict(sorted(my_dict.items(), key=lambda x: x[0])))
print(dict(sorted(my_dict.items(), key=lambda x: x[1])))
# 計算兩個日誌之間相隔天數
import time
import sys
def dateinput():
date = input('please input the first date: ')
return date
def datetrans(tdate):
spdate = tdate.replace("/", "-")
try:
datesec = time.strptime(spdate, '%Y-%m-%d')
except ValueError:
print
"%s is not a rightful date!!" % tdate
sys.exit(1)
return time.mktime(datesec)
def daysdiff(d1, d2):
daysec = 24 * 60 * 60
return int((d1 - d2) / daysec)
# date1 = dateinput()
# date2 = dateinput()
# date1sec = datetrans(date1)
# date2sec = datetrans(date2)
# print("The number of days between two dates is: ", daysdiff(date1sec, date2sec))
"""
設計一個函數,對傳入的字串(假設字串中只包含小寫字母和空格)進行加密操作,
加密的規則是a變d,b變e,c變f,……,x變a,y變b,z變c,空格不變,返回加密後的字串
"""
def caesar_encrypt(string):
base = ord('a')
encrypted_string = ''
for ch in string:
if ch != ' ':
curr = ord(ch)
diff = (curr - base + 3) % 26
ch = chr(base + diff)
encrypted_string += ch
return encrypted_string
def main():
print(caesar_encrypt('attack at dawn')) # dwwdfn dw gdzq
print(caesar_encrypt('dinner is on me')) # glqqhu lv rq ph
main()
"""
設計一個函數,生成指定長度的驗證碼(由數位和大小寫英文字母構成的隨機字串)
"""
from random import randrange
def generate_code(length=4):
all_chars = 'abcdefghijklmnopqrstuvwxyzABDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
all_chars_len = len(all_chars)
code = ''
for _ in range(length):
index = randrange(all_chars_len)
code += all_chars[index]
return code
# 劍指offer)輸入一個遞增排序的陣列和一個數字S,在陣列中查詢兩個數,使得他們的和正好是S,如果有多對數位的和等於S,輸出兩個數的乘積最小的。
# #
# # 思路:選定第一個數位,然後遍歷後面的數位求和並與S比較,需要n-1次,不行的話再選定第2,3,,,n個數字,需要n^2次,時間複雜度比較高。
# # 更簡單的方法可以是定義兩個指針,第一個指向第一個元素,第二個指向最後一個元素,兩個元素相加,如果等於S則輸出這兩個元素,如果大於,
# # 則將第二個指針向前移一位,再求和進行比較;如果小於,則將第一個指針向前移一位,再進行求和比較。
def get_num(data, sum_num):
if not data or not sum_num:
return []
i = 0
j = len(data) - 1
result = []
while i < len(data) and j > 0:
if data[i] + data[j] == sum_num:
result.append((data[i], data[j]))
elif data[i] + data[j] > sum_num:
j = j - 1
elif data[i] + data[j] < sum_num:
i = i + 1
return result
# 查詢同名學生資訊
# select * from student where name in (select name from student group by name having count(name)>1);
# 實現棧結構
class Stack(object):
# 初始化棧爲空列表
def __init__(self):
self.items = []
# 判斷棧是否爲空,返回布爾值
def is_empty(self):
return self.items == []
# 返回棧頂元素
def peek(self):
return self.items[len(self.items) - 1]
# 返回棧的大小
def size(self):
return len(self.items)
# 入棧
def push(self, item):
self.items.append(item)
# 出棧
def pop(self):
return self.items.pop()
# 選擇排序,選擇一個數作爲最小數的下標,然後拿這個數依次跟其他數進行對比,如果有比它小的數,就記錄下那個值的下標,然後進行元素互換
def select_sort(alist):
n = len(alist)
for i in range(n):
min = i
for j in range(i + 1, n):
if alist[j] < alist[i]:
min = j
alist[min], alist[i] = alist[i], alist[min]
return alist
print(select_sort([1, 5, 7, 2, 3, 6, 9, 77]))
# 檔案中有三個欄位,時間2020-08-12,userid,存取次數,求每個使用者每個月存取的次數的和
def get_visit_time_by_month(month):
dict_visit = {}
with open("a.txt", "r")as f:
for line in f.readlines():
time, user_id, count = line.split(" ")
month1 = time[4:6]
if month1 == month:
if user_id in dict_visit.keys():
dict_visit[user_id] = dict_visit[user_id] + count
else:
dict_visit[user_id] = count
return dict_visit
alist = [1, 2, 5, 9, 11, 15, 52]
# target = binary_search(alist, 52, 0, len(alist) - 1)
# print(target)
# 可變型別做預設參數,可變型別值一直增加
def f(x, l=[]):
print("===============%s" % id(l))
print(l)
for i in range(x):
l.append(i * i)
print("結束後%s" % l)
f(2)
f(3, [3, 2, 1])
f(3)
f(3)
# ===============12139056
# []
# 結束後[0, 1]
# ===============51299512
# [3, 2, 1]
# 結束後[3, 2, 1, 0, 1, 4]
# ===============12139056
# [0, 1]
# 結束後[0, 1, 0, 1, 4]
# ===============12139056
# [0, 1, 0, 1, 4]
# 結束後[0, 1, 0, 1, 4, 0, 1, 4]
# Python 是強型別的動態指令碼語言
# 列印結果說出理由
l = []
for i in range(10):
l.append({'num': i})
print(l)
l = []
a = {'num': 0}
for i in range(10):
a['num'] = i
l.append(a)
print(l)
# 一句話解決階乘函數
def get_jiecheng(n):
reduce(lambda x, y: x * y, range(1, n + 1))
print("++++++++++++++")
# fibnaci數列
def fib(n):
alist = [0, 1]
for i in range(1, n):
alist.append(alist[i] + alist[i - 1])
return alist
def fib2(n):
alist = [1, 1]
if n < 1:
return -1
if n == 1 or n == 2:
return 1
if n > 2:
return fib2(n - 1) + fib2(n - 2)
print(fib(10))
print([fib2(i) for i in range(1, 11)])
# 單例模式
class single:
_instance = None
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = object.__new__(cls)
return cls._instance
# 二分查詢
def twofind(n, l):
min = 0
max = len(l)
if n in l:
while True:
mid = int((max + min) / 2)
if n > l[mid]:
min = mid
elif n < l[mid]:
max = mid
else:
if n == l[mid - 1]:
return (mid - 1)
else:
return (mid)
else:
return -1
'''
求兩個字串的最長公共子串
思想:建立一個二維陣列,判斷對應位置是否相等,相等記爲1,最後數這個陣列對角線上爲1的最大長度
'''
def getNumofCommonSubstr(str1, str2):
lstr1 = len(str1)
lstr2 = len(str2)
record = [[0 for i in range(lstr2 + 1)] for j in range(lstr1 + 1)] # 多一位
maxNum = 0 # 最長匹配長度
p = 0 # 匹配的起始位
for i in range(lstr1):
for j in range(lstr2):
if str1[i] == str2[j]:
# 相同則累加
record[i + 1][j + 1] = record[i][j] + 1
if record[i + 1][j + 1] > maxNum:
# 獲取最大匹配長度
maxNum = record[i + 1][j + 1]
# 記錄最大匹配長度的終止位置
p = i + 1
# print(record)
return str1[p - maxNum:p], maxNum
str1 = 'abcdef'
str2 = 'mcdea'
res = getNumofCommonSubstr(str1, str2)
print(res)
# 求質因數
def get_zhi(num):
alist = []
while num > 1:
for i in range(2, num + 1):
if num % i == 0:
alist.append(i)
num = int(num / i)
if num == 1:
break
return alist
print(get_zhi(20))
# 列印函數執行時間裝飾器
def get_exec_time(fun):
def wapper(*args,**kwargs):
start_time= time.time()
fun(*args,**kwargs)
end_time = time.time()
print(end_time-start_time)
return wapper