python-图的字典表示

python-图的字典表示

题目

123 ## 做法1-字典 ```python n=eval(input()) DD=n # 顶点 Bian=0 lenBian=0

for i in range(n):
dict=eval(input()) # eval函数的作用为去掉两侧的字符串,使之直接变成字典格式
tuple1=dict.popitem() # 弹出一个键值对
if tuple1[-1]!={}: # 排除测试中第四条的情况
Bian+=len(tuple1[-1])
dictt = tuple1[-1]

    for j in range(len(dictt)):
        tuplee=dictt.popitem()
        lenBian+=tuplee[-1]

print("{:} {:} {:}".format(DD,Bian,lenBian))

## 做法2-列表
```python
# 去除字符串两边的括号
def removeKuohao(str):
    # print(type(str))
    return str[1:-1]

n=eval(input())
DD=n
Bian=0
lenBian=0
for i in range(n):
    str=input()
    if i==n-1: # 排除测试中第四条信息的情况(多一个})
        str=str[:-1]
    str=removeKuohao(str)# 第一次去除外括号
    index1=str.index("{") # 定位列举边的左括号
    if str[index1+1:-1]!='' :
        lst=str[index1+1:-1].split(',')
        Bian+=len(lst)
        for j in range(len(lst)):
            lstt=lst[j].split(":")
            lenBian+=eval(lstt[-1])
print("{:} {:} {:}".format(DD,Bian,lenBian))
posted @ 2022-04-02 20:07  梧桐灯下江楚滢  阅读(173)  评论(0)    收藏  举报