tuple1 = dict() tuple1[(1,1,1)] = 3 tuple1[(1,1,2)] = 4 tuple1[(1,1)] = 2 total = 0 for k in tuple1: total += tuple1[k] print(len(tuple1) + total)
时间: 2024-04-21 15:28:02 浏览: 22
这段代码的输出结果是 7。
首先,代码创建了一个空字典 `tuple1`。然后,它添加了三个键值对:`(1,1,1):3`,`(1,1,2):4` 和 `(1,1):2`。
接下来,代码使用一个循环遍历字典的所有键并将键对应的值加起来,最终结果是 `total = 3+4+2 = 9`。
最后,代码打印了 `len(tuple1)`,即字典中键值对的数量,也就是3,再加上 `total` 的值,也就是7。因此,输出结果是7。
相关问题
python输入tuple转化为dict
可以使用Python的内置函数zip()和dict()将tuple转换为dict。
代码示例:
```
t = ('a', 'b', 'c')
d = dict(zip(t, range(len(t))))
print(d)
```
输出结果:
```
{'a': 0, 'b': 1, 'c': 2}
```
解释:
1. zip()函数将tuple中的元素和一个range对象中对应索引的元素进行打包,返回一个zip对象。
2. dict()函数将zip对象转换为字典。
python构造LR(1)分析器代码
LR(1)分析器是一种自下而上的语法分析器,它可以通过读入输入符号串来生成语法分析树。下面是Python中构造LR(1)分析器的代码示例:
1. 定义文法
```python
grammar = {'S': [('E',)],
'E': [('E', '+', 'T'), ('T',)],
'T': [('T', '*', 'F'), ('F',)],
'F': [('(', 'E', ')'), ('id',)]}
```
2. 构造LR(1)自动机
```python
from collections import defaultdict
class LR1Automaton:
def __init__(self, grammar):
self.states = []
self.transitions = defaultdict(dict)
self.start_state = ('S\'', ('S',))
self.states.append(self.start_state)
self.closure(self.start_state, grammar)
self.build(grammar)
def closure(self, state, grammar):
queue = [state]
while queue:
current_state = queue.pop(0)
for production in grammar[current_state[1][0]]:
dot_index = current_state[1].index('.')
if dot_index < len(current_state[1]) - 1 and current_state[1][dot_index + 1] in grammar:
for first_set in self.first(current_state[1][dot_index + 2:], current_state[1][dot_index + 1], grammar):
new_state = (current_state[1][dot_index + 1], ('.',) + production, first_set)
if new_state not in self.states:
self.states.append(new_state)
self.transitions[current_state][current_state[1][dot_index + 1]].append(new_state)
queue.append(new_state)
def first(self, symbols, lookahead, grammar):
first_set = set()
if not symbols:
first_set.add(lookahead)
elif symbols[0] not in grammar:
first_set.add(symbols[0])
else:
for production in grammar[symbols[0]]:
first_set.update(self.first(production + symbols[1:], lookahead, grammar))
return first_set
def build(self, grammar):
queue = [self.start_state]
while queue:
current_state = queue.pop(0)
for symbol in set([i[0] for i in current_state[1] if i.index('.') < len(i) - 1]):
next_state = self.goto(current_state, symbol)
if next_state not in self.states:
self.states.append(next_state)
queue.append(next_state)
self.transitions[current_state][symbol] = next_state
def goto(self, state, symbol):
new_state = []
for production in state[1]:
dot_index = production.index('.')
if dot_index < len(production) - 1 and production[dot_index + 1] == symbol:
new_state.append(production[:dot_index] + (symbol, '.') + production[dot_index + 2:])
closure_set = set(new_state)
for item in new_state:
closure_set |= set(self.closure(item, grammar))
return state[0], tuple(closure_set)
```
3. 构造LR(1)分析表
```python
class LR1Parser:
def __init__(self, grammar):
self.action = {}
self.goto = {}
self.automaton = LR1Automaton(grammar)
self.build()
def build(self):
for i, state in enumerate(self.automaton.states):
for production in state[1]:
if production.index('.') == len(production) - 1:
if state == self.automaton.start_state:
self.action[i, '$'] = 'accept'
else:
for j, item in enumerate(self.automaton.states):
if item[0] == state[0] and (production[:-1], '.') in item[1]:
for symbol in state[2]:
self.action[i, symbol] = 'reduce', j, production[:-1]
elif production[production.index('.') + 1] not in self.automaton.transitions[state]:
continue
else:
next_state = self.automaton.transitions[state][production[production.index('.') + 1]]
for symbol in state[2]:
if symbol in grammar:
self.goto[i, symbol] = self.automaton.states.index(next_state)
else:
self.action[i, symbol] = 'shift', self.automaton.states.index(next_state)
def parse(self, tokens):
stack = [0]
i = 0
while True:
if (stack[-1], tokens[i]) in self.action:
action = self.action[stack[-1], tokens[i]]
if action[0] == 'shift':
stack.append(tokens[i])
stack.append(action[1])
i += 1
elif action[0] == 'reduce':
for _ in range(len(action[2]) * 2):
stack.pop()
stack.append(action[2])
stack.append(self.goto[stack[-2], stack[-1]])
elif action == 'accept':
return True
else:
return False
```
4. 测试LR(1)分析器
```python
grammar = {'S': [('E',)],
'E': [('E', '+', 'T'), ('T',)],
'T': [('T', '*', 'F'), ('F',)],
'F': [('(', 'E', ')'), ('id',)]}
parser = LR1Parser(grammar)
print(parser.parse(['id', '+', 'id', '*', 'id', '$']))
```
输出结果为True,表示输入的符号串符合文法规则。