python - 循环字符串以扩展特定字符 Pyhton
问题描述
Productions = {
"stat_list": [("<stat>", 0.2), ("stat_list", 0.8)],
"stat": [("<cmpd_stat>", 0.2), ("<stat>", 0.3), ("<if_stat>", 0.3), ("<iter_stat>", 0.4), ("
<assgn_stat>", 0.5), ("<decl_stat>", 0.7)],
"cmpd_stat": [("{ <stat_list> }", 0.5)],
#more code...
"type": [("int", 0.2), ("double",0.8)],
"const": [("<digit><digit_seq>",0.7)],
"digit_seq": [("{empty]", 0.2), ("<digit><digit_seq>", 0.8)],
"char": [( "[A-Z]", 0.2), ("[a-z]", 0.4), ("_", 0.7)],
"digit": [([0, 2, 3, 4, 5, 6, 7, 8, 9], 0.5)],
def generateRandom(Productions):
r5 = random.randint(0, 1)
for i in Productions:
if Productions[i] >= r5:
return Productions.get(i)
def getStatementFromExpansion(prog):
start = generateRandom(Productions)
while prog in "<" or ">":
if start == "<stat_list>":
return prog.replace(start, Productions.items(start), 1)
if start == '<stat>':
return prog.replace(start, Productions.items(start), 1)
#more similar code...
prog = "int main () { <stat> return 0; }"
print(getStatementFromExpansion(prog))
所以这个赋值的目的是循环遍历 prog,并且每次它看到一个 <> 时它都会扩展它,例如,<stat_list> 会扩展为 or 或 <stat_list>。3.它会继续做直到没有更多的<>,输出应该是这样的: int main(){int F0Z = 0262;if (22682 / 525)double S1;else h = U;while (8 - 594873){4=5} 返回 0;我目前的错误是 TypeError: '>=' not supported between 'list' and 'int'
解决方案
由于 Productions 是一个列表字典,因此您正在尝试将列表与 int 进行比较。您必须访问您正在比较的 Productions[i] 中的特定值。
例如,现在你有这个键值对:
"type": [("int", 0.2), ("double",0.8)],
并且您想访问 0.2 以与您的 r5 进行比较,您可以使用:
Productions['type'][0][1]
#list at type - first tuple of the list - second value of the tuple
一旦你知道你想要访问什么值,你可以菊花链方括号,因为它返回一个对象,然后你可以使用方括号来访问一些值。
PS get()用于字典,允许您“获取”某个键的值,并且还允许您在键不存在的情况下获取默认值。另一方面,index()为您提供了某个对象在列表中第一次出现的索引位置。
推荐阅读
- rsync - 许多大文件从服务器传输到本地
- php - 匹配文件中的字符串并删除该行
- progress-bar - Toast 通知进度条/数据绑定不起作用
- html - 为什么当 min-height 已设置时,此代码需要设置 css height 属性?
- excel - 多标准索引/匹配与 VBA 中的偏移量类型不匹配
- php - 无法断言两个对象相等 PHP Codeception
- scala - 解析订单文件,按股票代码分组并计算平均订单价格和数量
- swift - 斯威夫特 | 如何在 Firebase 中检测发送方和接收方
- spring-boot - Azure 应用服务:使应用程序在文件系统上读/写
- javascript - onClick 函数在悬停而不是单击时触发