quiz 5.3 notes

Ace your homework & exams now with Quizwiz!

A bubble short, while easy to understand and program, is not the most efficient sort.

The algorithm for a recursive sort is even more efficient. Search for "recursive sort" to read more about it.

The most commonly used type codes with arrays are 'b' for int and 'f' for float.

There are other type codes that will not be used in this course, some of which were needed for older versions of Python.

The inner loop tests if the number in the first position is greater than the number with an index equal to the current value of test. If the number in the first position is greater than one of those values, a swap is made. Next n takes the value one, the index of the second number in the list. The number in that position is compared to the later numbers in the list. If it is greater, then a swap is made.

This continues until n equals the index of the second last number in the list, which is then compared to the last number in the list. The end result is an ordered list.

When you create arrays using the array module, all the data values need to be the same type.

You also have to specify the type when you create an array.

Four Dimensions

You could think of a four-dimensional array as a shelf of books. myFourDArray [5] [2] [3] [10] refers to the book with an index of five and the page in that book with an index of two. On that page, this refers to the data value in the row with an index of three and in the column with an index of 10.

​ outputRow = "" for col in faves[row]: outputRow = outputRow + " " + col print(outputRow) The outputRow variable starts out empty for each row. Then the "for col in faves[row]'' loop iterates through the row and adds the new value to the outputRow variable, along with an empty space between values. Then the last line displays the program.

dog red art cat blue English bird green computer science dog red computer science dog blue history

unique feature of lists

is that they can be filled with multiple data types

If you have an application where you are thinking of using an array of string values or an array of mixed types of data values,

lists are what most programmers would choose.

"import *"

means that you do not have to type "array." before every array method. ​​>>> from array import *

bubble sort You can change your list to a list of strings, and it will still work.

myList = [5, 1, 2, 7, 6] length = len(myList) # n is the position being filled # test will step through the list and make comparisons for n in range(length - 1): for test in range(n + 1, length): if myList[n] > myList[test ]: temp = myList[n] myList[n] = myList [test ] myList[test ] = temp print(myList)

This program keeps the items in a row on the same line.

​# a program to fill an array with faves faves = [] # outer loop, one pass = one row for row in range(5): rowList = [] rowList.append(input("Favorite pet? ")) rowList.append(input("Favorite color? ")) rowList.append(input("Favorite class? ")) faves.append(rowList) print(faves) # an even better way to print for row in range(len(faves)): outputRow = "" for col in faves[row]: outputRow = outputRow + " " + col print(outputRow)

a program to fill an array with faves

​# a program to fill an array with faves faves = [] # outer loop, one pass = one row for row in range(5): rowList = [] rowList.append(input("Favorite pet? ")) rowList.append(input("Favorite color? ")) rowList.append(input("Favorite class? ")) faves.append(rowList) print(faves) # better way to print for row in range(len(faves)): for col in faves[row]: print (col)

Python has a built-in function to sort a list

​>>> aList = [10, 5, 1, 8, 7] >>> aList.sort() >>> aList [1, 5, 7, 8, 10]

You can remove the last item with pop().

​>>> arr array('b', [2, 5, 2])

Arrays already have a search method. Use search(target) to search for a particular number. You can ask for the index of the first occurrence of seven with this line. arr.index(7)

​>>> arr array('b', [2, 2, 10, 2, 14, 7, 2]) >>> arr.index(7) 5

You can add a single number with append().

​>>> arr.append(10) >>> arr array('b', [2, 5, 2, 10])

You can count the quantity of occurrences of a particular number with count(number).

​>>> arr.count(2) 4 There are four twos in the array.

You can add a list to the end with extend.

​>>> arr.extend([10, 2, 14, 7, 2]) >>> arr array('b', [2, 2, 10, 2, 14, 7, 2])

You can remove the item at a particular index with pop(index of item). This removes five, which has an index of one.

​>>> arr.pop(1) 5 >>> arr array('b', [2, 2])

The table is a list that holds the rows as members of the faves list.

​>>> faves = [Sam, Juanita, Akbar, Brie, Chris]

You can refer to any row in the table by using the index of the row.

​>>> faves[2] ['bird', 'green', 'computer science']

You can refer to a single data value in the table by using the index of the row and the index of the column, each in its own square brackets.

​>>> faves[4][2] 'history'

By not using "from array import *" , you need to use "array." before every method and property.

​>>> import array >>> arr = array.array('b',[2, 5, 2])

sort a list whose members are combinations of data types? The sort function will only sort by the first member of each number/color pair.

​>>> newList = [ [3,'blue'], [2,'red'], [4,'yellow'], [1,'green'] ] >>> newList.sort() >>> newList [[1, 'green'], [2, 'red'], [3, 'blue'], [4, 'yellow']]

Swapping Values Create a list that holds the numbers 5 and 2. The list is not ordered. You want the list to look like [2, 5]. aList[0] is 5 aList[1] is 2

>>> aList = [5, 2] >>> aList [5, 2]

For instance, an insertion sort takes elements out of the old list and gradually builds a new sorted list.

A bubble short, while easy to understand and program, is not the most efficient sort. Do not worry about these other methods, for you will not be asked about them. Do a search for "sorting algorithms Python" to find out more.For instance, an insertion sort takes elements out of the old list and gradually builds a new sorted list. aList = [7, 3, 10, 1, 4, 8] First put 7 in the new list. >>> newList = [7] Add the next number, 3, to the new list where it belongs, before 7. >>> newList = [3, 7] Keep adding the next number to the new list where it belongs. >>> newList = [3, 7, 10] Keep this up until you have inserted all the numbers into the new list.

The simplest algorithm is the bubble sort.

A bubble sort starts with finding the item that should be listed first. It works it way through the list, comparing each element to the first one. The items are swapped if they are in the wrong order. Then you determine which item should be second in the list by comparing what is currently second to each of the following items. The items are swapped, if necessary.

Common Mistakes

A common mistake is to combine the indices together in one bracket, such as myData [4, 1, 2]. Another common mistake is to use commas between the brackets, such as myData [4] , [1] , [2]. The correct way is to have separate brackets for each index with no commas: myData[4] [1] [2].

What if you wanted to sort the list by the color instead of by the number? You can do that yourself by writing your own sort function.

A key aspect of sorting is how you swap values.

One Dimension

A one-dimensional array is a list of numbers or other data types: [23, 'dog', 2.34, 10, 200]. myStuff[3] refers to the item with an index of three in the list.

Three Dimensions

A three-dimensional array is like a book, where there is a two-dimensional table on each page. myData[4] [1] [2] refers to the item on the page with an index of four. On that page, choose the item in the row with an index of one and the column with an index of two.

Two Dimensions

A two-dimensional array is like a table. otherStuff[3] [2] refers to the item in the row with an index of three and the column with an index of two.

Python has an array module in the Python Standard Library that you can import

Arrays store data more compactly and efficiently than lists. If you have large amounts of arithmetic data and plan to a lot of arithmetic operations, arrays use less resources.

________0 1 2 0_____dog_red__art 1______cat__blue_English 2_____bird_green_computer science 3_____dog_red__computer science 4_____dog_blue_history

Each row can be represented as a list. ​>>> Sam = ['dog', 'red', 'art'] >>> Juanita = ['cat', 'blue', 'English'] >>> Akbar = ['bird', 'green', 'computer science'] >>> Brie = ['dog', 'red', 'computer science'] >>> Chris = ['dog', 'blue', 'history']

More Dimensions

How could you picture a five-dimensional array? You can think of a five-dimensional array as a library full of shelves of books. Assume the shelves are numbered. myFiveDArray[2] [5] [2] [3] [10] refers to the shelf with an index of two, the book on that shelf with an index of five, and the page in that book with an index of two. On that page, this refers to the data value in the row with an index of three and in the column with an index of 10.

Remember Case Matters When Sorting Strings

If the words are all lowercase, they get sorted in alphabetical order. If there is a mixture of upper- and lowercase, you will want to use the string function lower() to compare string values. For instance, if A and B hold words, you can use the lower() function to compare them. That way, you do not have to worry about the difference in ASCII value between an uppercase and lowercase letter. ​if A.lower() > B.lower():

The array module from the Python Standard Library only allows for numeric data. The array module is very efficient when you have a large quantity of numeric data, especially if you plan to do a lot of calculations.

Lists, on the other hand, allow you to have any kind of data type, including a mixture of data types.

An array is an ordered list of data values.

Most programming languages have built-in code for arrays In most languages, the members of an array must all be of the same data type Python has some very unique characteristics and one of them is that there is no official array type built-in Where other languages use arrays, Python lists can be used.

Look what happens if you assign the value of aList[1] to alist[0]. ​>>> aList[0] = aList[1] >>> aList [2, 2]

Oh no! You lost the five. The solution to this problem is to use a new variable to hold the five until you complete the swap. ​>>> aList = [5, 2] >>> temp = aList[0] >>> aList[0] = aList[1] >>> aList[1] = temp >>> aList [2, 5]

sort function bubble sort of an array. This function works on any list that uses indices and holds data values that can be compared with the greater than operator.

​def sort(myList): length = len(myList) # n is the position being filled # index will step through the list and make comparisons for n in range(length - 1): for index in range(n + 1, length): if myList[n] > myList[index]: temp = myList[n] myList[n] = myList [index] myList[index] = temp return(myList) import array arr = array.array('b',[5, 1, 2, 7, 6]) newArr = sort(arr) print(newArr)

The program would work with any list that can be compared with the greater than operation (>). The variable length is set to the length of the list. The variable n starts out being zero, the index of the first number in the list. The other numbers in the list are compared to the first number with the inner loop.

​for test in range(n + 1, length):

Did you notice that you slipped an int into the data values (23)? When you display your array, you will see that Python converted the int 23 to the float 23.0.

​​>>> arr array('f', [1.5, 3.5999999046325684, 23.0])

if you want an array filled with floats, the first value in the parentheses ('f') tells Python that the array will be filled with floats. The second value in the parentheses are the initial values to fill your array.

​​>>> arr = array('f',[1.5, 3.6, 23])

the list below contains each of these: int, float, string, tuple, dictionary and a list.

​​>>> myList = [25, 2.7, 'dog', (5,7), {3:'red'}, ['list in a list']]

The following code will print the type of each item. ​​>>> for item in myList: print('Item: ', item, ' Type: ', type(item) )

​​Item: 25 Type: Item: 2.7 Type: Item: dog Type: Item: (5, 7) Type: Item: {3: 'red'} Type: Item: ['list in a list'] Type: <class 'list'>


Related study sets

Vascular Disorder NCLEX questions

View Set

Unit 1: Developing a Writing Strategy: Tutorial

View Set

ChatGPT prompts to quiz you for grammar test

View Set

Experiment #2 Boiling point and melting point determination

View Set

The "Iron Triangle"- AP Government

View Set