# 基于函数的API设计，理解接口与实现分离

使用函数设计一组 “容器API”：init/set/get/exist，用例如下：

```python
# -*- coding: UTF-8 -*-
def init():
    # TODO(You): 实现初始化

def set(dict, key, value):
    # TODO(You): 实现初始化

def get(dict, key):
    # TODO(You): 实现获取接口

def exist(dict, key):
    # TODO(You): 实现判断接口

if __name__ == '__main__':
    dict = init()
    for i in range(10):
        key = "key_{}".format(i)
        value = i
        set(dict, key, value)

    test_key = "key_4"
    if exist(dict, test_key):
        test_value = get(dict, test_key)
        print("key is: {}, value is: {}".format(test_key, test_value))
```

请选出下面对`TODO`方法的实现代码中，<span style="color:red">错误</span> 的实现。

## template

```python
def init():
    return {}

def set(dict, key, value):
    dict[key] = value

def get(dict, key):
    return dict.get(key)

def exist(dict, key):
    return dict.get(key) is not None

if __name__ == '__main__':
    dict = init()
    for i in range(10):
        key = "key_{}".format(i)
        value = i
        set(dict, key, value)

    test_key = "key_4"
    if exist(dict, test_key):
        test_value = get(dict, test_key)
        print("key is: {}, value is: {}".format(test_key, test_value))
```

## 答案

```python
def init():
    return {"pre": None, "key": None, "value": None, "next": None}

def set(dict, key, value):
    node = dict
    while node is not None:
        if node['key'] == key:
            return
        node = node['next']
    node['next'] = {"pre": node, "key": key, "value": value, "next": None}

def get(dict, key):
    node = dict
    while node is not None:
        if node['key'] == key:
            return node['value']
        node = node['next']

def exist(dict, key):
    node = dict
    while node is not None:
        if node['key'] == key:
            return True
        node = node['next']
    return False
```

## 选项

### A

```python
def init():
    return []

def set(dict, key, value):
    if not key in dict or dict.index(key) % 2 != 0:
        dict.append(key)
        dict.append(value)

def get(dict, key):
    if key in dict:
        pos = dict.index(key)
        if pos % 2 == 0:
            return dict[pos+1]
    return None

def exist(dict, key):
    return key in dict and dict.index(key) % 2 == 0
```

### B

```python
def init():
    return [], []

def set(dict, key, value):
    keys, values = dict
    if not key in keys:
        keys.append(key)
        values.append(value)

def get(dict, key):
    keys, values = dict
    if not key in keys:
        return None
    else:
        return values[keys.index(key)]

def exist(dict, key):
    keys, values = dict
    return key in keys
```

### C

```python
def init():
    return {}

def set(dict, key, value):
    dict[key] = value

def get(dict, key):
    return dict.get(key)

def exist(dict, key):
    return dict.get(key) is not None
```
