首页 > 解决方案 > 循环字符串以扩展特定字符 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'

标签: python

解决方案


由于 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()为您提供了某个对象在列表中第一次出现的索引位置。


推荐阅读