Explaining Code - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Explaining Code (/thread-22312.html) |
Explaining Code - kozaizsvemira - Nov-07-2019 Hi, As I am learning python I am wondering about following code: openList = ['[', '{', '('] closeList = [']', '}', ')'] def check(Str): stack = [] for i in Str: if i in openList: stack.append(i) elif i in closeList: pos = closeList.index(i) if (len(stack) > 0) and (openList[pos] == stack[len(stack) -1 ]): stack.pop() else: print(len(stack)) return 'Unbalanced' if len(stack) == 0: print(len(stack)) return 'Balanced' string = '{[()]}' string2 = '[)' print(string, check(string), string2, check(string2))I understand what it does, but I've never found a full explanation of what [] do in an example like this: openList[pos] if I understand correctly we are looking for a position and since those two lists are same length we can use it as correct position? also this line of code: stack[len(stack) -1 ] writing it as len(stack) - 1 returns wrong results, but what does it mean to python when we say [] I know it's a list, but how does it python see when we write list[len(list)], are we saying create another list to list len of list? RE: Explaining Code - ichabod801 - Nov-07-2019 In general list_name[position] refers to the item in list_name at index position. You can use it on the right side of an equals sign (or without an equals sign) to get that value, or you can use it on the left side of an equals sign to assign to that index. >>> foo = [1, 2, 3] >>> foo[1] 2 >>> foo[1] = 'two' >>> foo [1, 'two', 3]That code is very clunky. Here's how I might rewrite it: opens = ('[', '{', '(') close_to_open = {']': '[', '}': '{', ')': '('} # use a dict for easy retrieval of appropriate symbol def check(text): stack = [] for char in text: # don't use single letter variables if char in opens: stack.append(char) elif char in close_to_open: opening = close_to_open[char] # simpler retrieval if stack and (opening == stack[-1]): # lists are true if not empty, -1 is the last item in a list stack.pop() else: print(len(stack)) return 'Unbalanced' if not stack: # lists are False if empty return 'Balanced' string = '{[()]}' string2 = '[)' print(string, check(string), string2, check(string2)) RE: Explaining Code - kozaizsvemira - Nov-07-2019 Awesome, thank you. Your code is much easier to read. |