简体   繁体   中英

Why there is a run time error in this python program?

I have C++ background and very new to Python. I might be making a simple mistake.

def make_polish(s) :
    no_of_pluses = 0
    polish_str = []
    i = 0
    for index in range(len(s)):
        print s[index]
        if '+' == s[index]:
            no_of_pluses = no_of_pluses + 1
        if '*' == s[index]:
            polish_str[i] = s[index-1] """Index out of range error here."""
            i = i + 1 
            polish_str[i] = s[index+1]
            i = i + 1
            polish_str[i] = '*'
            i = i + 1

    return polish_str 

print make_polish("3*4")

Your list polish_str is always empty. You need to do:

polish_str.append(s[index-1])

Instead of:

polish_str[i] = s[index-1] # """Index out of range error here."""
i = i + 1 

When you create the list polish_str = [] it's not allocating space for it as it does in C/C++. It's a dynamic data structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM