Skip to content

Commit 41f2602

Browse files
authored
Fixes & Simplify Q28.
1. 方法一,原始缩进错误 2. 原来使用幂运算,既不清晰,速度也不快,多写很多东西,甚至还需要反转字符串。 3. 添加方法四
1 parent f5bb6c1 commit 41f2602

File tree

1 file changed

+19
-17
lines changed

1 file changed

+19
-17
lines changed

README.md

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -691,39 +691,41 @@ G: global 全局作用域
691691
B: build-in 内置作用
692692

693693
python在函数里面的查找分为4种,称之为LEGB,也正是按照这是顺序来查找的
694-
### 28.字符串123″转换成123,不使用内置api,例如int()
695-
方法一: 利用str 函数
694+
### 28.字符串 `"123"` 转换成 `123`,不使用内置api,例如 `int()`
695+
方法一: 利用 `str` 函数
696696
```python
697697
def atoi(s):
698-
s = s[::-1]
699698
num = 0
700-
for i,v in enumerate(s):
701-
for j in range(0,10):
699+
for v in s:
700+
for j in range(10):
702701
if v == str(j):
703-
num += j *(10**i)
704-
return num
702+
num = num * 10 + j
703+
return num
705704
```
706-
方法二: 利用ord函数
705+
方法二: 利用 `ord` 函数
707706
```python
708707
def atoi(s):
709-
s = s[::-1]
710708
num = 0
711-
for i, v in enumerate(s):
712-
offset = ord(v) - ord('0')
713-
num += offset *(10 **i)
709+
for v in s:
710+
num = num * 10 + ord(v) - ord('0')
714711
return num
715712
```
716-
方法三: 利用eval函数
713+
方法三: 利用 `eval` 函数
717714
```python
718715
def atoi(s):
719-
s = s[::-1]
720716
num = 0
721-
for i, v in enumerate(s):
722-
t = '%s *1 ' %v
717+
for v in s:
718+
t = "%s * 1" % v
723719
n = eval(t)
724-
num += n *(10 ** i)
720+
num = num * 10 + n
725721
return num
726722
```
723+
方法四: 结合方法二,使用 `reduce`,一行解决
724+
```python
725+
from functools import reduce
726+
def atoi(s):
727+
return reduce(lambda num, v: num * 10 + ord(v) - ord('0'), s, 0)
728+
```
727729
### 29.Given an array of integers
728730
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。示例:给定nums = [2,7,11,15],target=9 因为 nums[0]+nums[1] = 2+7 =9,所以返回[0,1]
729731
```python

0 commit comments

Comments
 (0)