




































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





































4.8 Lists basics Programmers commonly desire to group related variables together. Containers, which contain references to other objects instead of data, are able to accomplish this. One such container is a list - ANS 4.9 Dictionary basics. A dictionary is represented by the dict object type. A dict maps unique keys to values. A key is like the word "cat" from the English dictionary example. A value describes some data associated with a key, such as a definition. A key can be any immutable type, such as a number, string, or tuple; a value can be any type. - ANS 5.5 Membership operators he in and not in operators, known as membership operators, yield True or False if the left operand matches the value of some element in the right operand, which is always a container. - ANSMembership operators can be used to check whether a string is a substring, or matching subset of characters, of a larger string. For example, 'abc' in '123abcd' returns True because the substring abc exists in the larger string. 6.2 Function parameters
Programmers can influence a function's behavior via an input to the function known as a parameter. - ANSThe function call print_face('x') passes the char value to that parameter. The value passed to a parameter is known as an argument. 6.3 Returning values from functions None is a special keyword that indicates no value. - ANS 6.4 Dynamic typing programmer can call the add function using two integer arguments, as in add(5, 7), which returns a value of 12. Alternatively, a programmer can pass in two string variables, as in add('Tora', 'Bora'), which would concatenate the two strings and return 'ToraBora'. - ANSThe behavior of the function depends on the argument types, a concept called polymorphism. 6.6 Functions are objects A function is also an object in Python, having a type, identity, and value. A function definition like def print_face(): creates a new function object with the name print_face bound to that object. - ANS 6.7 Scope of variables and functions The name of a variable or function object is only visible to part of a program, known as the object's scope. - ANS 6.8 Namespaces and scope resolution
A program with user-defined classes contains two additional types of objects: class objects and instance objects. A class object acts as a factory that creates instance objects. - ANS 7.5 Class constructors. 7.6 Class interfaces. A class interface consists of the methods that a programmer calls to create, modify, or access a class instance. - ANSThe figure below shows the class interface of the RaceTime class, which consists of the init constructor and the print_time() and print_pace() methods. class RaceTime: def init(self, start_time, end_time, distance): # ... def print_time(self):
def print_pace(self):
7.7 Class customization
To customize a class, a programmer implements class methods with special method names that the Python interpreter recognizes. For example, to change how a class instance object is printed, the special str() method can be defined, as illustrated below. - ANSthen when you print(truck) it comes out in a custom way. 7.8 Memory allocation and garbage collection. The process of an application requesting and being granted memory is known as memory allocation. - ANS 8.1 Lists. The list object type is one of the most important and often used types in a Python program. A list is a container, which is an object that groups related objects together. A list is also a sequence; thus, the contained objects maintain a left-to-right positional ordering. - ANS 9.1 Recursive functions. A function may call other functions, including calling itself. A function that calls itself is known as a recursive function. - ANSThe recursive function has an if-else statement, where the if branch is the end of the recursion, known as the base case. The else part has the recursive calls. Such an if-else pattern is quite common in recursive functions. 9.6 Recursive exploration of all possibilities - ANSRecursion is useful for finding all possible paths. 10.1 Constant time operations.
Lower bound: A function f(N) that is ⤠the best case T(N), for all values of N ℠1. Upper bound: A function f(N) that is ℠the worst case T(N), for all values of N ℠1. - ANS 10.4 O notation Big O notation is a mathematical way of describing how a function (running time of an algorithm) generally behaves in relation to the input size. In Big O notation, all functions that have the same growth rate (as determined by the highest order term of the function) are characterized using the same Big O notation. In essence, all functions that have the same growth rate are considered equivalent in Big O notation. - ANS 10.5 Algorithm analysis. Binary search is an algorithm that searches a sorted list for a key by first comparing the key to the middle element in the list and recursively searching half of the remaining list so long as the key is not found. - ANSBinary search first checks the middle element of the list. If the search key is found, the algorithm returns the index. If the search key is not found, the algorithm recursively searches the remaining left sublist (if the search key was less than the middle element) or the remaining right sublist (if the search key was greater than the middle element). 10.8 Analyzing the time complexity of recursive algorithms. The runtime complexity T(N) of a recursive function will have function T on both sides of the equation. Ex: Binary search performs constant time operations, then a recursive call that operates on half of the input, making the runtime complexity T(N) = O(1) + T(N / 2). Such a function is known as a
recurrence relation: A function f(N) that is defined in terms of the same function operating on a value < N. - ANS 11.1 Searching and algorithms. Linear search is a search algorithm that starts from the beginning of a list, and checks each element until the search key is found or the end of the list is reached. - ANS 11.2 Binary search. Binary search is a faster algorithm for searching a list if the list's elements are sorted and directly accessible (such as an array). Binary search first checks the middle element of the list. If the search key is found, the algorithm returns the matching location. If the search key is not found, the algorithm repeats the search on the remaining left sublist (if the search key was less than the middle element) or the remaining right sublist (if the search key was greater than the middle element). lookup java example - ANSint binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the // middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x)
if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first // element int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } } 11.7 Insertion sort. Insertion sort is a sorting algorithm that treats the input as two parts, a sorted part and an unsorted part, and repeatedly inserts the next value from the unsorted part into the correct location in the sorted part. Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. O(n^2) - ANSvoid sort(int arr[]) { int n = arr.length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead
of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } 11.9 Shell sort. ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h'th element is sorted. Shell sort is a sorting algorithm that treats the input as a collection of interleaved lists, and sorts each list individually with a variant of the insertion sort algorithm. Shell sort uses gap values to determine the number of interleaved lists. A gap value is a positive integer representing the distance between elements in an interleaved list. For each interleaved list, if an element is at index i, the next element is at index i + gap value. O(n^2) - ANSint sort(int arr[]) { int n = arr.length; // Start with a big gap, then reduce the gap
Quicksort is a sorting algorithm that repeatedly partitions the input into low and high parts (each part unsorted), and then recursively sorts each of those parts. To partition the input, quicksort chooses a pivot to divide the data into low and high parts. The pivot can be any value within the array being sorted, commonly the value of the middle array element. Once partitioned, each partition needs to be sorted. Quicksort is typically implemented as a recursive algorithm using calls to quicksort to sort the low and high partitions. This recursive sorting process continues until a partition has one or zero elements, and thus already sorted. The quicksort algorithm's runtime is typically O(N log N) - ANS/* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j=low; j
i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index / void sort(int arr[], int low, int high) { if (low < high) { / pi is partitioning index, arr[pi] is now at right place */
// Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays / int L[] = new int[n1]; int R[] = new int[n2]; /Copy data to temp arrays/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; / Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else {
arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any / while (i < n1) { arr[k] = L[i]; i++; k++; } / Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } 11.15 Bucket sort. Bucket sort is a numerical sorting algorithm that distributes numbers into buckets, sorts each bucket with an additional sorting algorithm, and then concatenates buckets together to build the sorted result. A bucket is a container for numerical values in a specific range. Ex: All numbers in the
int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; } 11.16 Radix sort. Radix sort is a sorting algorithm designed specifically for integers. The algorithm makes use of a concept called buckets and is a type of bucket sort. Any array of integer values can be subdivided into buckets by using the integer values' digits. A bucket is a collection of integer values that all share a particular digit value. Ex: Values 57, 97, 77, and 17 all have a 7 as the 1's digit, and would all be placed into bucket 7 when subdividing by the 1's digit. Radix sort is a sorting algorithm specifically for an array of integers: The algorithm processes one digit at a time starting with the least significant digit and ending with the most significant. Two steps are needed for each digit. First, all array elements are placed into buckets based on the current digit's value. Then, the array is rebuilt by removing all elements from buckets, in order from lowest bucket to highest. - ANS// The main function to that sorts arr[] of size n using // Radix Sort static void radixsort(int arr[], int n) { //Findthemaximumnumbertoknownumberofdigits int m = getMax(arr, n); // Do counting sort for every digit. Note that // instead of passing digit number, exp is passed.
// exp is 10^I where i is current digit number for (int exp = 1; m/exp > 0; exp *= 10) countSort(arr, n, exp); } 11.18 Overview of fast sorting algorithms. 11.20 Bubble sort Bubble sort is a sorting algorithm that iterates through a list, comparing and swapping adjacent elements if the second element is less than the first element. Bubble sort uses nested loops. Given a list with N elements, the outer i-loop iterates N times. Each iteration moves the largest element into sorted position. The inner j-loop iterates through all adjacent pairs, comparing and swapping adjacent elements as needed, except for the last i pairs that are already in the correct position,. O(n^2) - ANSvoid bubbleSort(int arr[]) { int n = arr.length; for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) { // swap arr[j+1] and arr[i] int temp = arr[j]; arr[j] = arr[j+1];