- Home
- Logic & Programming
- Python programming assignment 2
Python programming assignment 2 Essay Example
- Category:Logic & Programming
- Document type:Math Problem
- Level:Undergraduate
- Page:3
- Words:1643
PYTHON PROGRAMMING ASSIGNMENT 2
SECTION A
-
SHOE_STYLE
Altering the value of SHOE_STYLE in the order system to 6 has a lot of impact in the system. The constant used to access order detail in the list is changed. Lists usually starts at value zero i.e [0, 1, 2, 3, 4, 5]. When the value of SHOE_STYLE is changed to 6, the program terminates when a user chooses option 5 because the range is exceeded.
-
file: size = eval(string.split(line)[SIZE])
In this expression, the built in function eval() is used to execute and return a result of evaluation of the size of the list. It is for this purpose that the expression is user to give the size of the item.
-
Purpose of the readorders(inf) function
# readorders(inf) function is defined
def readorders(inf):
#The list of lines in inf is converted to variable orderlist, this is a declaration.
orderlist = list(string.split(line) for line in inf)
#a variable convertedlist is declared and defined as empty list.
convertedlist=[]
#for loop is used to iterate the ordelist and append items in ordelist to the convertedlist
for element in orderlist:
convertedlist.append([element[0],element[1],element[2],eval(element[3]),eval(element[4]), element[5]])
return convertedlist
-
Replacing the code convertedorderlist = readorders(inf) in the function mysort(): with the code convertedorderlist = list(string.split(line) for line in inf).
The program runs well and sorts the list well. The output is correct.
-
Sorting by ShoeStyle
Program runs well and sorts the list well. The output is correct.
-
Sorting by price
Program runs well and gives the right output. The output is correct.
-
Use of constants
In the function readorders, the code can be changed to use constants in place of literal at
convertedlist.append([element[0],element[1],element[2],eval(element[3]),eval(element[4]),element[5]). This is replaced with constants as convertedlist.append( i in range inf)
-
Use of result in comparevalsGT.
result = list1[skey] > list2[skey]
return result
This expression uses result to hold values for list where first item is greater that second item.
-
Definition of writeout function and improvement of readability
writeout function makes use outf.write(‘n’) to improve readability. Each of the items is therefore printed in new line.
-
infile.seek(0) line
This line (infile.seek(0)) is meant to reset the items in file orders.txt items after a every sort action, removing this line leaves the sorted items with the previous order, hence the subsequent sorting will not be correct.
-
The function insertionsortorders().
The function uses the concept of insertion sort to sort the details of the file in orders.txt. In this function a unique key with a value is assigned to every line in the file.
This is achieved in the following order:-
Function insertionsortordersis() definition
Variable orderList declared as converted( in the function readorders(inf))
Variable sortedList declared as a list of the orderList
For loop used to loop through sortedlist from the beginning to the end of list.
While loop used to loop through items,
Evaluate the items
Re-arrange the items in the list based on the criterion. Re-arrangement is done by inserting the current item to the previous item location based on position.
Print “Orders insertion sorted by item at position” in new line
Write in a new file the final output in the sorted list for output.
-
The function readorders ()
#Finction definition
def readorders(inf):
#tList1 declared as variable to hold list details
tList1= (string.split(line) for line in inf)
#orderList is assisgned the list(tList1) values
orderlist = list(tList1)
#
convertedlist is set as emplty list
convertedlist=[]
SECTION B
Reflection:
-
Code examination
-
In an iteration both for loop and while loop can be nested together to give optimum use of lines of codes.
-
infile.seek(0) is a n expression used to reset file pointer
-
Insertion sort and bubble sort can be used to give sorted list result output. Both do the same function but differently
-
A function can have more than one arguments e.g ordersort(inf, skey, outf)
-
eval() is an inbuilt function used in evaluating options before executions.
-
The function comparevalsGT ()
comparevalsGT has been used to get the greater item in the list between two items in comparison for appropriate insertion in the rightful position. This facilitates sorting is by a given criteria.
# comparevalsGT function definition
def comparevalsGT(listOrders, skey, posn1, posn2):
#declare first item in the list
list1=listOrders[posn1]
#declare second item in the list
list2=listOrders[posn2]
# reset the first item as result if it is greater than second item
result = list1[skey] > list2[skey]
return result
-
The function swapListPositions(sList, posn1, posn2).
# function definition
def swapListPositions(sList, posn1, posn2):
#declare list of items on first position
tmp = sList[posn1]
#swap items in first position with items in second position
sList[posn1]=sList[posn2]
sList[posn2]=tmp
#return result
The swapListPositions function is used to swap items from one position to the other.
The function is only used with bubble sort. Insertion sort program do not use this function.
-
The function mysort().
The function mysort has used the sort in-built function sorted(list); this is a method to sort items in a list. When this in-built function sorted(list) is called, it gives a result of a sorted list.
Arguments in sorted.
The argument in sorted provides the decision function directing sorted() on how to decide on the order between any two items in the list.
Lambda function
Lambda is a construct used to save memory and number of lines of codes. It makes codes simple and smaller.
-
The function insertionsortorders().
#function definition
def insertionsortorders(inf, skey, outf):
# assign variable orderList the list in readorders(inf)
orderList = readorders(inf)
#assign variable sortedList the list in orderList
sortedList = list(orderList)
# use for loop to iterate through sortedList
for index1 in range(1,len(sortedList)):
#assign index2 the index1 values
index2 = index1
currNum = sortedList[index1][skey]
#use while loop to repeat the iteration until the list is sorted
while (currNum < sortedList[index2 — 1][skey] and index2 != 0):
index2 = index2-1
sortedList.insert (index2, sortedList.pop(index1))
#write the sorted result
outf.write(‘n’+»Record insertion sorted by team at position «+ str(skey+1)+’:nn’)
writeout(sortedList, outf, skey) #write sorted orders to given output file
return sortedList
-
The insertion sort achieved in the Book Shop Management system designed using python programming language is illustrated below. The several sorting functions used have been extracted. The function provided in the orders system such as comparevalsGT, swapListPositions and readorders have been renamed and used appropriately in the book shop management system to attain suitable sorting result.
def readbooks(inf):
tList1= (string.split(line) for line in inf)
bookList = list(tList1)#list of lines
convertedlist=[]
for element in bookList: convertedlist.append([element[0],element[1],element[2],eval(element[3]),eval(element[4]),element[5]])
return convertedlist
# this is a function to compare on any given key -e.g. price, size, style etc.
#define comparebooksvalBGfunction
def comparebooksvalBG(clistBooks, skey, posn1, posn2):
#declare list1 as the first item in the list
list1=clistBooks[posn1]
#declare list2 as the second item in the list
list2=clistBooks[posn2]
#compare and give a result of the result of comparison
result = list1[skey] > list2[skey]
return result
def insertionsortbooks(inf, skey, outf):
bookList = readbooks(inf)
sortedList = list(bookList)
for index1 in range(1,len(sortedList)):
index2 = index1
currNum = sortedList[index1][skey]
while (currNum < sortedList[index2 — 1][skey] and index2 != 0):
index2 = index2-1
sortedList.insert (index2, sortedList.pop(index1))
outf.write(‘n’+»Record insertion sorted by item at position «+ str(skey+1)+’:nn’)
writeout(sortedList, outf, skey) #write sorted orders to given outputfile
return sortedList
# sort a given file of strings, sorting on key position, save output to newfile
def booksort(inf, skey, outf):
convertedbookList = list(string.split(line) for line in inf)
#convertedbookList = readbooks(inf)
#use in-built sort function to sort on the skey index of the list
newbookList = sorted(convertedbookList, key=lambda num: num[skey])
writeout(newbookList, outf, skey) #output the new sorted orders to a file
def writeout(bookList, outf, keyposn):
#print «Sorted order list follows » #testing
#print newbookList
#print «Done»
outf.write(«books sorted by item at position «+ str(keyposn+1)+’:n’+’n’)
for books in bookList:
#print order details formatted
outf.write(books[0]+» «+books[1]+» «+books[2]+» «+str(books[3])+ » $»+str(books[4])+» «+books[5])
#write new line
outf.write(‘n’)
def main():
# Open file and display menu
infile = open(DATA_FILE, ‘r’)
choice = menu()
# Execute menu choice
while choice != 20:
if choice == 1:
displayFile(infile)
elif choice == 9:
sortkey = raw_input(«Enter sort key (BookType(1) BookSubject(2) BookCode(3) BookPages(4) BookPrice(5) BookShop(6)): «)
sortkeyval = eval(sortkey) — 1 # align sort key with index 0..5
newfilename = raw_input(«Enter file name to save sorted Books in :»)
print «opening file «, newfilename
sortedfile = open(newfilename, «w»)
booksort(infile,sortkeyval,sortedfile)
print «now doing insertion sort»
infile.seek(0) #reset file pointer
insertionsortbooks(infile,sortkeyval,sortedfile)
sortedfile.close()
print «Wrong number chosen — try again»
# Reset file reading position to start of file and display menu again
infile.seek(0)
choice = menu()
# Close file and end program
infile.close()
print «End of program»
# Execute main function
SECTION C
Bubble sort
Pseudo code
Start = first item on list
Evaluate the first two items
If first > second,
For each pair of adjacent elements, continue to the end of the list.
While swap occur on the last pass, Repeat.
#function definitin
def bubble_sort(teamList)
#set sort_List as list in teamList
sort_List = list (teamList)
# Evaluate the items in the list
for i in range(len(sort_List) -1):
for j in range (len(sort_List) — (i + 1)):
if (sort_List [j] > sort_List [j + 1]):
#swap the position in sorting
swapLocations (sort_List, j, j + 1)
return sort_List
Documentation
This is a python program designed to process the orders in a book shop. It is a sample project of a book shop management system. The program works with data in a text file called data.txt.
The details of the data in the text file are as follows
Book Type |
Book Code |
Book Pages |
Book Cost |
Book Shop |
|
Dictionary |
|||||
Business |
|||||
Periodical |
Business |
||||
Dictionary |
|||||
Computing |
|||||
Periodical |
Computing |
Data types
There are data types used majorly in the program. These are:-
-
Basic data types such as Int, Float and string
-
Containers such as lists
-
Constructs such as Lambda
-
Arrays and pointers
Built-in functions
The Built-in functions used are:-
append()
sorted()
Iteration
There is basic loop such as for, and if.
Advanced iteration has also been used where both if, for and while loop are used, in other cases two lopps has been nested together to achieve the best result.