1. 程式人生 > 其它 >python 筆試題 英方_筆試題python基礎總結

python 筆試題 英方_筆試題python基礎總結

技術標籤:python 筆試題 英方

#python
a = [1, 2, 3]
b=a
a.append(4)
b.append(5)
print(a,b)

輸出:

[1, 2, 3, 4, 5]

[1, 2, 3, 4, 5]

>>> a=[1,2,3]
>>> b=a
>>> b=[x-1 for x in a]
>>> b
[0, 1, 2]
>>> a
[1, 2, 3]

位運算

&1等價於%2,偶數二進位制編碼末位為0,奇數為1,所以偶數&1=0,奇數&1=1

b8c168a2475b4266dbd32027cdc7d0a9.png

>>1等價於//2,只適用於整數

ece267ea78f0a9f3e17ae633514f1631.png

<<1等價於*2,只適用於整數

python中不用宣告型別

c2896d796c3d9c91a2e973ce568311fe.png
a,a=3,2
print(a)#輸出2,先賦左再賦右

字典

dict.get()方法:

dict.get(key, default=None):函式返回指定鍵的值,如果值不在字典中返回預設值。

字串

>>> str= 'abca'
#從下標1開始,查詢在字串裡第一個出現的子串:返回結果3;若未寫1則預設從下標0開始查詢
print(str.find('a',1))
 3

>>> s="hai kuo tian kong"#擷取
>>> print(s[3:])
 kuo tian kong

>>str = 'akakak'
>>str = str.replace('k',' 8') # 將字串裡的k全部替換為8
>>print str
 'a8a8a8'

>>s=" the sky is blue "#spilt
>>print(s.spilt())#輸出['the', 'sky', 'is', 'blue']
>>print(s.spilt(' '))#輸出['', 'the', 'sky', 'is', 'blue', '']

投票演算法

#取一個數組中的眾數
class Solution:
    def majorityElement(self, nums):
        temp=nums[0]
        count=1
        for i in range(1,len(nums)):
            if nums[i]==temp:
                count+=1
            else:
                count-=1
            if count==0:
                temp=nums[i]
                count=1
        return nums

C++ 語言中的堆(即優先佇列)為大根堆,而 Python 語言中的對為小根堆,所以需要取相反數。

在自定義類中呼叫函式

class Solution:
    def reverseWords(self, s):
        arr=s.split()
        c=" ".join(reversed(arr))
        return c
    def returnval(self,s):
        return self.reverseWords(s)#在不同函式下呼叫
a=Solution()
s=" the sky is blue "
print(a.returnval((s)))#輸出blue is sky the

對比

class Solution:
    def returnval(self,s):
        def reverseWords(self, s):
            arr=s.split()
            c=" ".join(reversed(arr))
            return c
        return reverseWords(self,s)#在同一個函式下呼叫
a=Solution()
s=" the sky is blue "
print(a.returnval((s)))#輸出blue is sky the

賦值

a,b=3,2
a,b=b,a
print(a,b)#a=2,b=3

等價於

a,b=3,2
c=b,a
a,b=c
print(type(c),c)
print(a,b)

c3895d869404763f310fe1b576315ac7.png

字典與指標

lookup={}
def insert(word):
    """
    Inserts a word into the trie.
    """
    tree = lookup#tree指向lookup
    for a in word:
        if a not in tree:
            tree[a] = {}#{c:{}}#{c:{o:{}}}#{c:{o:{d:{}}}}
        tree = tree[a]#tree指向c:後面的{}#tree指向o:後面的{}#tree指向d:後面的{}
    # 單詞結束標誌
    #{c:{o:{d:{#:#}}}}
    tree["#"] = "#"
insert("cod")
print(lookup)#{'c': {'o': {'d': {'#': '#'}}}}