Skip to content

Commit ceb86c4

Browse files
authored
Merge pull request #41 from nasyxx/patch-7
Fixes & Simplify Q28.
2 parents 28d4572 + 41f2602 commit ceb86c4

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
@@ -689,39 +689,41 @@ G: global 全局作用域
689689
B: build-in 内置作用
690690

691691
python在函数里面的查找分为4种,称之为LEGB,也正是按照这是顺序来查找的
692-
### 28.字符串123″转换成123,不使用内置api,例如int()
693-
方法一: 利用str 函数
692+
### 28.字符串 `"123"` 转换成 `123`,不使用内置api,例如 `int()`
693+
方法一: 利用 `str` 函数
694694
```python
695695
def atoi(s):
696-
s = s[::-1]
697696
num = 0
698-
for i,v in enumerate(s):
699-
for j in range(0,10):
697+
for v in s:
698+
for j in range(10):
700699
if v == str(j):
701-
num += j *(10**i)
702-
return num
700+
num = num * 10 + j
701+
return num
703702
```
704-
方法二: 利用ord函数
703+
方法二: 利用 `ord` 函数
705704
```python
706705
def atoi(s):
707-
s = s[::-1]
708706
num = 0
709-
for i, v in enumerate(s):
710-
offset = ord(v) - ord('0')
711-
num += offset *(10 **i)
707+
for v in s:
708+
num = num * 10 + ord(v) - ord('0')
712709
return num
713710
```
714-
方法三: 利用eval函数
711+
方法三: 利用 `eval` 函数
715712
```python
716713
def atoi(s):
717-
s = s[::-1]
718714
num = 0
719-
for i, v in enumerate(s):
720-
t = '%s *1 ' %v
715+
for v in s:
716+
t = "%s * 1" % v
721717
n = eval(t)
722-
num += n *(10 ** i)
718+
num = num * 10 + n
723719
return num
724720
```
721+
方法四: 结合方法二,使用 `reduce`,一行解决
722+
```python
723+
from functools import reduce
724+
def atoi(s):
725+
return reduce(lambda num, v: num * 10 + ord(v) - ord('0'), s, 0)
726+
```
725727
### 29.Given an array of integers
726728
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。示例:给定nums = [2,7,11,15],target=9 因为 nums[0]+nums[1] = 2+7 =9,所以返回[0,1]
727729
```python

0 commit comments

Comments
 (0)