---
# System prepended metadata

title: 複習Python

---

# 複習Python

## python[::-1]和[-1]用法
[::-1]順序相反操作
[-1]讀取倒數第一個元素
[3 ::-1]從下標為3（從0開始）的元素開始翻轉讀取
同樣適用於字符串

eg:
```python=
a=[1,2,3,4,5]
b=a[::-1]
```
output
```
[5, 4, 3, 2, 1]
```

```python=
b=a[-1]
```
output
```
5
```
```python=
b=a[3::-1]
```
output
```
[4, 3, 2, 1]
```

## map() 使用方法
map() 的使用方法，基本上是 map(function, iterable) 就好。 function 輸入我們要使用的函數， iterable 輸入我們要迭代輸入的對象，比如說一個 List。

## [leetcode] Reverse Integer
```python=
class Solution:
    def reverse(self, x: int) -> int:
        reverseValue = int(str(abs(x))[::-1])

        if x > 0:
            reverseValue = reverseValue
        else:
            reverseValue = -reverseValue

        if pow(-2, 31) < reverseValue < pow(2, 31) - 1:
            return reverseValue
        else:
            return 0
```

## [leetcode] Palindrome Number
```python=
class Solution:
    def isPalindrome(self, x: int) -> bool:
        return str(x) == str(x)[::-1]
```

## [leetcode] Roman to Integer
```python=
class Solution:
    def romanToInt(self, s: str) -> int:
        roman_to_integer = {'I': 1,
                            'V': 5,
                            'X': 10,
                            'L': 50,
                            'C': 100,
                            'D': 500,
                            'M': 1000}

        s = s.replace('IV', 'IIII') \
             .replace('IX', 'VIIII') \
             .replace('XL', 'XXXX') \
             .replace('XC', 'LXXXX') \
             .replace('CD', 'CCCC') \
             .replace('CM', 'DCCCC')
        
        return sum(map(roman_to_integer.get, s))
```

