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


Messages In This Thread
Explaining Code - by kozaizsvemira - Nov-07-2019, 06:30 PM
RE: Explaining Code - by ichabod801 - Nov-07-2019, 06:48 PM
RE: Explaining Code - by kozaizsvemira - Nov-07-2019, 06:53 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  first code - need some explaining of logic korenron 11 4,562 May-12-2019, 09:39 AM
Last Post: korenron
  Please help explaining this recursive function armeros 3 2,811 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