Python学习part4

Task 4

练习题:

列表:

1.(1)(2)

lst=[2,5,6,7,8,9,2,9,9]
lst.append(15)
print(lst)
lst.insert(5,20)
print(lst)


[2, 5, 6, 7, 8, 9, 2, 9, 9, 15]
[2, 5, 6, 7, 8, 20, 9, 2, 9, 9, 15]

(3)

lst=[2,5,6,7,8,9,2,9,9]
lst.extend([2,5,6])
print(lst)

[2, 5, 6, 7, 8, 9, 2, 9, 9, 2, 5, 6]

(4)

lst=[2,5,6,7,8,9,2,9,9]
x=lst.pop(3)
print(lst)

[2, 5, 6, 8, 9, 2, 9, 9]

(5)

lst=[2,5,6,7,8,9,2,9,9]
print(lst[:: -1])

[9, 9, 2, 9, 8, 7, 6, 5, 2]

(6)

lst=[2,5,6,7,8,9,2,9,9]
lst.sort()
print(lst)
lst.sort(reverse=True)
print(lst)

[2, 2, 5, 6, 7, 8, 9, 9, 9]
[9, 9, 9, 8, 7, 6, 5, 2, 2]
lst=[1,[4,6],True]
lst[0]=2
lst[1][0]=8
lst[1][1]=12
print(lst)

[2, [8, 12], True]
class Solution:
    def peakIndexInMountainArray(self,A:List[int])->int:
        if len(A)<3:
            return False
        i=0
        j=len(A)-1
        while A[i]<A[i+1]:
            i+=1
            if i==len(A)-1:
                return False
        while A[j]<A[j-1]:
            j-=1
            if j<0:
                return False
            if i==0 or j==len(A)-1:
                return False
            if j==i:
                return True
            else:
                return False
元组:

1, 2, 1, 2) <class ‘tuple’>
(1, 1) <class ‘tuple’>
2 <class ‘int’>

元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用。显然第三个中的括号被当做成了运算符使用。

元组拆包就是将元组中的元素分别赋给变量。
上述过程属于拆包。

此过程可以算作解压元组,左右结构相对应。所以可以使用一个或多个元素进行占位。

字符串

(1)replace(old, new [, max]) 把 将字符串中的old替换成new,如果max指定,则替换不超过max次。
(2)split(str="", num) 不带参数默认是以空格为分隔符切片字符串,如果num参数有设置,则仅分隔num个子字符串,返回切片后的子字符串拼接的列表。
(3)rstrip([chars]) 删除字符串末尾的空格或指定字符。
2.

不会
3.

class Solution:
   def longestPalindrome(self, s: str) -> str:
       temp, max_p, length = "", "", len(s)  
       for index in range(length): 
           index_left, index_right = index, index
            def compare(l, r):  
               while l != -1 and r != length and s[l] == s[r]: 
                   l, r = l-1, r+1 
               return s[l+1:r] if l == -1 or r == length else s[l+1:r] 

           temp = compare(index_left, index_right) 
           max_p = temp if len(temp) > len(max_p) else max_p  

           try:s[index+1]
           except:continue

           if s[index] == s[index+1]: 
               left, right = index, index + 1
               temp = compare(left, right)  
               max_p = temp if len(temp) > len(max_p) else max_p  
       return max_p 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值