csc W5 & W6

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

list.reverse()

reverse the list

The Built-in Function: Range

Python has a built-in function called range that is useful to use when you want to generate a sequence of numbers. You can type help(range) in IDLE if you ever need a reminder. The example below will print all the numbers in the range of 1 to 10. for i in range(10): print (i) The form of range is: range([start,] stop[, step]): return a virtual sequence of numbers from start to stop by step

Here is a nested loop involving 2 for loops: Q: why the first range start at 10, and the second one start at 2?

for i in range(10, 13): for j in range(1, 5): print(i, j) Here is the output: 10 1 10 2 10 3 10 4 11 1 11 2 11 3 11 4 12 1 12 2 12 3 12 4 Notice that when i is 10, the inner loop executes in its entirety, and only after j has ranged from 1 through 4 is i assigned the value 11.

Not "What" but "Where"----Example 2

The second example is described below: def shift_left(L): ''' (list) -> NoneType Shift each item in L one position to the left and shift the first item to the last position. Precondition: len(L) >= 1 >>> shift_left(['a', 'b', 'c', 'd']) ''' first_item = L[0] for i in range(len(L) - 1): L[i] = L[i + 1] L[-1] = first_item For the same reasons as above, merely knowing the value of the items in the list is not enough since we need to know where the items are located; we need to know the index (position) of the item in the list.

List Operations

-lists can be indexed -Lists can also be sliced, using the same notation as for strings i.e. grades = [80,90,70] grades[1:2] [90] -The in operator can also be applied to check whether a value is an item in a list.

We can access the items inside the nested lists like this:

>>> grades[0][0] 'Assignment 1' >>> grades[0][1] 80 >>> grades[1][0] 'Assignment 2' >>> grades[1][1] 90 >>> grades[2][0] 'Assignment 3' >>> grades[2][1] 70

To access a nested item, first select the sublist, and then treat the result as a regular list.

For example, to access 'Assignment 1', we can first get the sublist and then use it as we would a regular list: >>> sublist = grades[0] >>> sublist ['Assignment 1', 80] >>> sublist[0] 'Assignment 1' >>> sublist[1] 80 Both sublist and grades[0] contain the memory address of the ['Assignment 1', 80] nested list.

list.count(object) don't modify

return the # of times object occurs in list

list.sort()

sort the list from smallest to largest

list.index(object) don't modify

return the index of the first occurrence of object; error if not there

range

use for generating a sequence of number represent index in our list. range([start,] stop [, step]) -> range object return a virtual sequence of numbers from start to stop by step i.e. for num in range(3): print (num) 0(int) 1 2

Aliasing

when both varaibles refer to the same object. Consider the following code: >>> lst1 = [11, 12, 13, 14, 15, 16, 17] >>> lst2 = lst1 >>> lst1[-1] = 18 >>> lst2 11, 12, 13, 14, 15, 16, 18] After the second statement executes, lst1 and lst2 both refer to the same list. When two variables refer to the same objects, they are aliases. If that list is modified, both of lst1 and lst2 will see the change. if we use the function call the aliasing list variable, then the list will be modified

Several of Python's built-in functions can be applied to lists, including:

• len(list): return the length of list. • min(list): return the smallest element in list. (in str, the minimum is the lowest alphabic sequence) • max(list): return the largest element in list. • sum(list): return the sum of elements of list (where list items must be numeric).

Applications of Range

There are other options you can specify to range. One option is to let range generate the numbers corresponding to indices of a string or a list. s = 'computer science' for i in range(len(s)): print(i) You can also tell range what index to start at. For instance, the example below starts at index 1 (as opposed to the default which is 0). for i in range(1, len(s)): print(i) You can even specify the "step" for range. The default stepping size is 1, which means that numbers increment by 1. The example below starts at index 1 and its step size is there (goes to every third index). for i in range(1, len(s), 3): print(i)

list.insert(int, object)

return object at the given index, moving items to make room.

side effect

a function or method has a side effect if it returns a value and also modifies an object

list.remove(object)

remove the first occurrence of the object; error if not there

list Methods

A method is a function inside an object.

list.append(object) modify

append object to the end of the list

for loops over indices

Because len returns the number of items in a list, it can be used with range to iterate over all the indices. This loop prints all the values in a list: for i in range(len(lst)): print(lst[i]) This also gives us flexibility to process only part of a list. For example, We can print only the first half of the list: i.e. for i in range(len(lst) // 2): print(lst[i]) Or every other element: for i in range(0, len(lst), 2): print(lst[i])

Not "What" but "Where"----Example 1 *

The first example is described below: def count_adjacent_repeats(s): ''' (str) -> int Return the number of occurrences of a character and an adjacent character being the same. >>> count_adjacent_repeats('abccdeffggh') 3 ''' repeats = 0 for i in range(len(s) - 1): if s[i] == s[i + 1]: repeats = repeats + 1 return repeats We want to compare a character in the string with another character in the string beside it. This is why we iterate over the indices because the location is important, and only knowing the value of the character does not provide us with enough information. This is how we are able to count repeated characters in a string. We can't execute the body of the loop if i islen(s) - 1 because we compare to s[i + 1], and that would produce an IndexError.

for loops over list

The general form of a for loop over a list is: for variable in list: body

Nested Lists (one list inside the other)

Lists can contain items of any type, including other lists. These are called nested lists. Here is an example. >>> grades = [['Assignment 1', 80], ['Assignment 2', 90], ['Assignment 3', 70]] >>> grades[0] ['Assignment 1', 80] >>> grades[1] ['Assignment 2', 90] >>> grades[2] ['Assignment 3', 70]

Types of list elements

Lists elements may be of any type. Lists can also contain elements of more than one type. i.e. street_address = [10, 'Main Street']

i.e. (list of int) -> NoneType

NoneType: doesn't return anything or return none.

type list ([ ] indicate list)

Our programs will often work with collections of data. One way to store these collections of data is using Python's type list. The general form of a list is: [expr1, expr2, ..., exprN] It's the only type we can modify for now

Not "What" but "Where"

Previously, we have written loops over characters in a string or items in a list. However, sometimes there are problems where knowing the value of the items in a list or the characters in a string is not enough; we need to know where it occurs (i.e. its index).

Bodies of Loops

The bodies of loops can contain any statements, including other loops. When this occurs, this is known as a nested loop.

parallel list

Two lists are parallel if they have the same length and the items at each index are somehow related. The items at the same index are said to be at corresponding positions. Consider these two lists: list1 = [1, 2, 3] list2 = [2, 4, 2] In these two lists, the corresponding element of list1[0] is list2[0], the corresponding element of list2[1] is list1[1], and so on.

Mutability

We say that lists are mutable: they can be modified. All the other types we have seen so far (str, int, float and bool) are immutable: they cannot be modified.

list.extend(list)

append the items in the list parameter to the * list

list.count() and list.index()

are the methods that return information about lists.

Example of Nested Loops

def calculate_averages(grades): ''' (list of list of number) -> list of float Return a new list in which each item is the average of the grades in the inner list at the corresponding position of grades. >>> calculate_averages([[70, 75, 80], [70, 80, 90, 100], [80, 100]]) [75.0, 85.0, 90.0] ''' averages = [] # Calculate the average of each sublist and append it to averages. for grades_list in grades: # Calculate the average of grades_list. total = 0 for mark in grades_list: total = total + mark averages.append(total / len(grades_list)) return averages In calculate_averages, the outer for loop iterates through each sublist in grades. We then calculate the average of that sublist using anested, or inner, loop, and add the average to the accumulator (the new list, averages).

Example of Corresponding Elements *

def match_characters(s1, s2): ''' (str, str) -> int Return the number of characters in s1 that are the same as the character at the corresponding position of s2. Precondition: len(s1) == len(s2) >>> match_characters('ate', 'ape') 2 >>> match_characters('head', 'hard') 2 ''' num_matches = 0 for i in range(len(s1)): if s1[i] == s2[i]: num_matches = num_matches + 1 return num_matches The function above counts the corresponding elements of the two strings that are the same character. If a character ofs1 at index i is the same as the character of s2 at the same index, then we increment num_matches by 1 (since they match). Otherwise, we continue on to the next pair of corresponding elements and compare them.

comment

help programmer to understand the function. Python will ignore the information after # each time read a code, try to understand the relationship b/w variables and write the comment. so next time you don't need to think it again

list.pop()

remove and return the item at the end of the list (optional *index to remove from anywhere)


संबंधित स्टडी सेट्स