Welcome to Python

I’ve been interested in learning python for a little while, and my new job on campus has finally forced me to take the initiative to do so – iTunes University uses python for a majority of the back-end coding, and with Binghamton trying to set up an iTunes U page, actually knowing python is a huge advantage. I picked up a book last week (“Python Programming for the Absolute Beginner” by Michael Dawson, ISBN-10: 1-59863-112-8), and have been diligently reading through it. At first glance, it seems like a very easy version of C – there are so many shortcuts that can be taken over the traditional C programming I’ve been doing, such as not defining a variable type (ie, int, char, *) and just being able to assign a value to it with the assignment defining it (marc = [] is a list, whereas marc = () is a tuple). As I was reading through and doing the examples, I realized that the list operator can easily be used to implement a stack, and by extension a queue. This reminded me of a lab I had to complete for my C programming class last semester, in which we had to create stacks and queues out of arrays, and then convert an infix (2+3) to a postfix (23+) expression. I decided to test out my understanding of Python up until this point and recreate the data structures and the conversion, leaving out the calculation portion. After a few bumps, I was able to successfully manipulate my stack, and with a few changes in the code, create the queue. The conversion took a little longer, but totaling only 78 lines, is definitely smaller than any C implementation I could create. Anyway, here’s the code and some download links for the files.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#! /usr/bin/python
 
# Stack Implementation using the List operator
 
stack = []
top = -1
choice = None
 
while choice != "0":
	print \
	"""
		Data Structure: Stack
	"""
 
	print "0 - Exit"
	print "1 - Push"
	print "2 - Pop"
	print "3 - Print"
	print "4 - Delete"
 
	choice = raw_input("Menu Option: ")
 
	if choice == "0":
		break
	elif choice == "1":
		push = int(raw_input("Element to push: "))
		stack.append(push)
		top += 1
	elif choice == "2":
		if top >= 0:
			print stack.pop(top)
			top -= 1
		else:
			print "There are no elements in the stack to pop"
	elif choice == "3":
		if top >= 0:
			stack.reverse()
			print "___ << top of stack"
			for element in stack:
				print "", element
			stack.reverse()
		else:
			print "There is no stack to print"
	elif choice == "4":
		stack = []
		top = -1
	else:
		print "Please enter a valid menu option."
 
raw_input("\n\nPress the enter key to exit.")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#! /usr/bin/python
 
# Queue Implementation using the List operator
 
queue = []
front = 0
choice = None
end = -1
 
while choice != "0":
	print \
	"""
		Data Structure: Queue
	"""
 
	print "0 - Exit"
	print "1 - Enqueue"
	print "2 - Dequeue"
	print "3 - Print"
	print "4 - Delete"
 
	choice = raw_input("Menu Option: ")
 
	if choice == "0":
		break
	elif choice == "1":
		enqueue = int(raw_input("Element to enqueue: "))
		queue.append(enqueue)
		end += 1
	elif choice == "2":
		if end &gt;= 0:
			print queue.pop(front)
			end -= 1
		else:
			print "There are no elements in the queue to dequeue"
	elif choice == "3":
		if end &gt;= 0:
			for element in queue:
				print "", element
		else:
			print "There is no queue to print"
	elif choice == "4":
		queue = []
		end = -1
	else:
		print "Please enter a valid menu option."
 
raw_input("\n\nPress the enter key to exit.")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#! /usr/bin/python
 
# Create a postfix expression from an infix expression using stacks and queues
 
infix = [] # infix expression stored in a queue
postfix = [] # postfix expression stored in a queue
numbers = [] # numbers stored in a stack
operators = [] # operators stored in a queue
top = -1 # counter for the top of the infix stack
end = -1 # count for the end of the operators queue
front = 0 # anchor for the front of the operators queue
choice = None # menu choice
expression = "" # string to store the expression to print
 
while choice != "0":
	print \
	"""
		Infix to Postfix Converter
	"""
 
	print "0 - Exit\n1 - Enter Expression\n2 - View Expression\n3 - Convert\n4 - Reset"
 
	choice = raw_input("Menu Option: ")
 
	if choice == "0":
		break
	elif choice == "1":
		exp = raw_input("Please enter the expression: ")
		for letter in exp:
			infix.append(letter)
			top += 1
	elif choice == "2":
		if top &gt;= 0:
			for element in infix:
				expression += element
			print "The expression is:", expression
		else:
			print "Please enter an expression first"
	elif choice == "3":
		expression = ""
		while infix != []:
			x = infix.pop(front)
			top  -= 1
			if x == "(":
				x = infix.pop(front+1)
				top -= 1
			if x != ")":
				if (x &gt;= "0") and (x &lt;= "9"):
					numbers.append(x)
				else:
					operators.append(x)
			else:
				for num in numbers:
					expression += num
				numbers = []
				for op in operators:
					expression += op
				operators = []
		for letter in expression:
			postfix.append(letter)
		expression = ""
		for y in postfix:
			expression += y
		print "The postfix expression is:", expression
	elif choice == "4":
		infix = []
		postfix = []
		numbers = []
		operators = []
		top = -1
		end = -1
		front = 0
		choice = None
		expression = ""
	else:
		print "Please enter a valid menu option."
 
raw_input("\n\nPress the enter key to exit.")

Downloads:
stack.py
queue.py
postfix.py

This entry was written by Marc Budofsky , posted on Sunday October 11 2009at 02:10 pm , filed under Programming, Python and tagged , , , , , . Bookmark the permalink . Post a comment below or leave a trackback: Trackback URL.

One Response to “Welcome to Python”

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>