给自己改改代码(python)(记录)

使用try except 处理数组越界之类的问题

try:
<语句>        #运行别的代码
except <名字><语句>        #如果在try部份引发了'name'异常
except <名字><数据>:
<语句>        #如果引发了'name'异常,获得附加的数据
else:
<语句>        #如果没有异常发生
finally:
<语句>    #退出try时总会执行

二维数组迭代时使用变量而非i j 索引

boxTypes[j][0]*boxTypes[j][1]

# 改成这种,[0][1]容易搞混

for numberOfBoxes, numberOfUnitsPerBox in boxTypes:

return 可以写 == 判断表达式

# heap[0] = stk[-1]
return False if heap[0] == 'f' else True
#改成
return stk[-1] == 't'

使用enumerate(sequence, [start=0])

for c in command:
# 改成enumerate 这样可以使用下标 enumerate(sequence, [start=0])
for i, c in enumerate(command):

使用sum 不仅可以计算加和,也可以用于统计多个字符的出现次数

class Solution:
    def halvesAreAlike(self, s: str) -> bool:
        s = s.lower()
        half = len(s)//2
        s1 = s[:half]
        s2 = s[half:]
        aeiou = ['a','e','i','o','u']
        count1 = count2 = 0
        
        for c in s1: 
            if c in aeiou:count1 += 1
        for c in s2:
            if c in aeiou:count2 += 1
        #return s1,s2
        return count1 == count2
        
# 改成
class Solution:
    def halvesAreAlike(self, s: str) -> bool:
        VOWELS = "aeiouAEIOU"
        a, b = s[:len(s) // 2], s[len(s) // 2:]
        return sum(c in VOWELS for c in a) == sum(c in VOWELS for c in b)

reduce()
第一个参数是自定义函数my_prod,第二个参数是可迭代对象 numbers,返回累乘结果。
使用accumulate()累加
第一个参数是迭代对象,第二个才是函数对象,返回的还是一个迭代对象。

# 1732. 找到最高海拔
class Solution:
    def largestAltitude(self, gain: List[int]) -> int:
        res = last = 0
        for i in range(len(gain)):
            last += gain[i]
            res = max(res,last)
        return res




class Solution:
    def largestAltitude(self, gain: List[int]) -> int:
        return max(accumulate(gain, initial=0)) # accumulate 返回的还是一个迭代对象。

使用replace
str.replace(old, new[, max])


#一个简单的字符串替换题
# 1678. 设计 Goal 解析器
class Solution:
    def interpret(self, command: str) -> str:
        result = ''
        last_c = ''
        for c in command:
            if c == 'G':result += c
            elif c == ')' and last_c == '(':result += 'o'
            elif c == ')' and last_c == 'l':result += 'al'
            last_c = c
        return result

# 改成 无脑调库
# Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串)
# 如果指定第三个参数max,则替换不超过 max 次。
# str.replace(old, new[, max])

class Solution:
    def interpret(self, command: str) -> str:
        return command.replace("()","o").replace("(al)","al")

使用字典

#最简单的方法是直接对字符串 sss 进行排序。
#我们首先遍历给定的字符串 order\textit{order}order,将第一个出现的字符的权值赋值为 111,第二个出现的字符的权值赋值为 222,以此类推。在遍历完成之后,所有未出现字符的权值默认赋值为 000。
#随后我们根据权值表,对字符串 sss 进行排序,即可得到一种满足要求的排列方案。

class Solution: #我写的是用二维数组
    def customSortString(self, order: str, s: str) -> str:
        s_o = [[c,0] for c in s]
        for i in range(len(s_o)):
            for j in range(len(order)):
                if s_o[i][0] == order[j]:
                    s_o[i][1] = j
                    break
        s_o.sort(key=lambda ele: ele[1], reverse=False)
        return "".join([i[0] for i in s_o] )


#改成
#这里用字典更整洁更快
class Solution:
    def customSortString(self, order: str, s: str) -> str:
        val = defaultdict(int)
        for i, ch in enumerate(order):
            val[ch] = i + 1
        
        return "".join(sorted(s, key=lambda ch: val[ch]))


你可能感兴趣的:(python,开发语言)