call.py 2.1 KB
Newer Older
F
feilong 已提交
1 2 3 4 5
# -*- coding: UTF-8 -*-
# 作者:幻灰龙
# 标题:Python 函数调用
# 描述:使用函数设计一组 “容器API”:init/set/get/exist

F
feilong 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
# 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

# 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

# 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

F
feilong 已提交
62
def init():
F
feilong 已提交
63
    return {"pre": None, "key": None, "value": None, "next": None}
F
feilong 已提交
64 65 66


def set(dict, key, value):
F
feilong 已提交
67 68 69 70 71 72 73 74
    node = dict
    while node is not None:
        if node['key'] == key:
            return
        last = node
        node = node['next']

    last['next'] = {"pre": last, "key": key, "value": value, "next": None}
F
feilong 已提交
75 76 77


def get(dict, key):
F
feilong 已提交
78 79 80 81 82
    node = dict
    while node is not None:
        if node['key'] == key:
            return node['value']
        node = node['next']
F
feilong 已提交
83 84 85


def exist(dict, key):
F
feilong 已提交
86 87 88 89 90 91 92
    node = dict
    while node is not None:
        if node['key'] == key:
            return True
        node = node['next']

    return False
F
feilong 已提交
93 94


F
feilong 已提交
95
if __name__ == '__main__':
F
feilong 已提交
96 97 98 99 100 101 102 103 104 105
    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))