我在做Count Vowel Strings in Ranges - LeetCode,下面是我的答案。
class Solution:
def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
acc_arr = list(accumulate(words, lambda acc, word: acc + (word[0] in 'aeiou' and word[-1] in 'aeiou'), initial=0))
res = []
for l, r in queries:
res.append(acc_arr[r + 1] - acc_arr[l])
return res
我觉得 word[0] in 'aeiou' and word[-1] in 'aeiou'不够优雅,有没有好的写法?
优化后的代码如下:
class Solution:
def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
acc_arr = list(accumulate(words, lambda acc, word: acc + all(c in 'aeiou' for c in {word[0], word[-1]}), initial=0))
return [acc_arr[r + 1] - acc_arr[l] for l, r in queries]
1
NessajCN 2023-04-03 15:07:11 +08:00
你重点关注错了
word[0] in 'aeiou' and word[-1] in 'aeiou' 优不优雅无所谓的,对性能没啥影响 但是下面的 for append 不怎么优雅,建议用 list comprehension 或 map |
2
JasonLaw OP @NessajCN #1 对,下面的 for loop 可以替换为 lost comprehension
|
3
featureoverload 2023-04-03 19:11:19 +08:00
`all([c in 'aeiou' for c in (x, y)])`
|
4
JasonLaw OP @featureoverload #3 谢谢,不过可以优化成`all(c in 'aeiou' for c in (x, y))`
|
5
XueXianqi 2023-05-29 16:49:07 +08:00
@featureoverload
`all([c in 'aeiou' for c in (x, y)])`看起来优雅,但是性能考虑得不够周全 Python 中有个叫“短路运算”的,`a and b`,如果 a 不成立,就不去运算 b 了,显然这里的 all 用得就不够优雅了 用 all 还需要注意的是:不能完全代替 and ,比如说: `if a.hasattr("name") and a.name.startswith("A"):` 这里就不能用 all ,如果 a 没有 name 这个 attribute ,就会报错。 |