Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Explaining Code
#1
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?
Reply
#2
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))
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Awesome, thank you. Your code is much easier to read.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  first code - need some explaining of logic korenron 11 4,429 May-12-2019, 09:39 AM
Last Post: korenron
  Please help explaining this recursive function armeros 3 2,760 Nov-14-2018, 05:55 AM
Last Post: armeros

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020