第二章 Python速成 2 1 基礎內容

2021-07-30 21:10:08 字數 2354 閱讀 8561

# -*- coding: utf-8 -*-

"""created on thu apr 20 07:42:11 2017

@author: tang

第二章:python速成

2.1基礎內容

"""#2.1.3 空白形式

for i in [1,2,3,4,5]:

print i

for j in [1,2,3,4,5]:

print j

print j+i

print i

print 'donw loop'

#可以用乙個\來表示乙個語句在下一行續寫 括號中的自動省不用\

two_plus_three=2+\

3print two_plus_three

#輸出==5

#2.1.4 模組

import re

my_regex=re.compile("[0-9]+",re.i)

#當模組名字過長或者已經被占用,就可以用as使得模組名被替換

import re as regex

my_regex=regex.compile("[0-9]+",regex.i)

#2.1.5演算法

from __future__ import division #表示引入小數除法,當需要取整用a//b

#2.1.6 函式

def double(x):

"""可以填寫函式說明"""

return x*2

return f(1)

my_double=double

#2.1.9列表

#切取列表

x=range(10)#x是列表[0,1...,9]

first_three=x[:3]

print first_three

#[0, 1, 2]

three_to_end=x[3:]

print three_to_end

#[3, 4, 5, 6, 7, 8, 9]

#通過操作符 in 確認列表成員

a=1 in [1,2,3]

print a

#true

#2.1.10 元祖

my_tuple=(1,2)

try:

my_tuple[1]=3

except typeerror:

print 'cannot modify a tuple'#即驗證了元祖的不可更改性

#2.1.11 字典

grades=

grades["joel"]=90

print grades["joel"]

grades["kate"]=100#增加乙個kate

print grades["kate"]

tweet=

tweet_key=tweet.keys()#把字典中的所有鍵儲存在變數tweet_key中

tweet_values=tweet.values()#把字典中的所有鍵儲存在變數tweet_values中

print "user" in tweet_key

#1.defaultdict

from collections import defaultdict,counter #從模組中匯出乙個函式

#這裡表示我要新增乙個空列表,每當單詞出現的時候,這個單詞鍵對應的值加一

word_counts=defaultdict(int)

document=

for word in document:

word_counts[word]+=1

print word_counts['as']

#輸出結果=1

print word_counts['cc']

#輸出結果=0

#2.counter直接生成對映

c=counter([0 ,1,2,0])#c 生成了

#2.1.12 集合

#使用原因:快速操作 快速檢查

#使用原因二:彙總其中重複元素

item_list=[1,2,3,1,2,3]

print len(item_list)#6

print len(set(item_list))#3

#2.1.13 控制流

for x in range(10):

if x==3:

continue #直接繼續迴圈

if x==5:

break #退出所有迴圈

print x

#輸出結果:0 1 2 4

#2.1.14 真和假

#all 函式 取值為乙個列表 當所有的元素為真返回真

#any 有乙個就返回真

第二章 2 1插入排序

2.1 1 以圖2 2為模型,說明insertion sort在陣列a 上的執行過程。31 31 41 31 41 59 26 31 41 59 26 31 41 58 59 2.1 2重寫過程insertion sort,使之按非公升序 而不是非降序 排序。insertion sort for j...

第二章 演算法基礎

引言 演算法導論 在本章將向我們介紹乙個演算法設計和分析框架,在後續的章節也將在這個框架的基礎上來分許演算法。名詞解釋 1 偽 偽 就是以最清晰 最簡潔的表示方法來說明演算法,而忽略資料抽象 模組性和錯誤處理的問題 2 迴圈不變式 每次迴圈從陣列a中取出第j個元素插入有序數列a 1 j 1 然後遞增...

第二章 演算法基礎

2.1 插入排序 insertion sort 時間複雜度 o n 對於少量元素的排序,是乙個有效的演算法。為什麼叫插入排序呢?可以模擬撲克牌整牌 將未排序的數字通過遍歷插入到已排好序的數字中的對應位置 如何實現呢 num j 1 key 插入 for int i 1 i n i printf n ...