Question

Next, create a simple benchmark experiment using the timeit module as we did in class. • Run each of your functions 1 time (e

Topic: Algorithm Analysis 1. [40 points] Minimum in list algorithms - benchmark and plot Write two Python functions to find t

0 0
Add a comment Improve this question Transcribed image text
Answer #1

NOTE: Since the list size is very large, output generation takes time, so wait patiently while running program.

Here the value of scale is set to 1, setting it to 0.0000000001 may produce the required result.

CODE:

import random
import timeit 

def f_linear(x):
    minimum = x[0]
    for i in x:
        if i < minimum:
            minimum = i
    return minimum

def f_quadratic(x):
    min = x[0]
    l = len(x)
    for i in range(l):
        for j in range(i+1,l):
            if x[i]<x[j] and x[i]<min:
                min = x[i]
    return min


linear = []
quad = []
s=[]
print("Size","Linear      ","Quad ","Ratio")
for size in range(1000,20000+1,2000):
    #Creating list of required size
    l = [random.randint(1,1000) for _ in range(size)]
    
    # Calling the above functions and saving their time
    t = timeit.Timer('f_linear(l)','from __main__ import f_linear,l')
    linear_time = t.timeit(number = 1)
    p = timeit.Timer('f_quadratic(l)','from __main__ import f_quadratic,l')
    quad_time = p.timeit(number = 1)
    
    # Calculate ratio
    ratio = quad_time/linear_time
    
    # Printing the data
    print(size,format(linear_time,'.10f'),format(quad_time,'.4f'),int(ratio))
    
    # Appending time to lists for further plotting
    linear.append(linear_time)
    quad.append(quad_time)
    s.append(size)
    
import matplotlib.pyplot as plt
import math
plt.plot(s,linear,'r-',label='Linear')
plt.plot(s,quad,'b-',label='Quadratic')
scale = 1
y1 = [scale*math.log(n) for n in linear]
y2 = [scale*n*math.log(n) for n in quad]
plt.plot(s,y1,'y-',label='Log time')
plt.plot(s,y2,'g-',label='nLog time')

                

OUTPUT:

import random import timeit def f linear(x): minimum = x[0] for i in x: if i < minimum: minimum = i return minimum def f_quad

quad = [] S=[] print(Size, Linear , Quad , Ratio) for size in range (1000, 20000+1, 2000): #Creating list of required

Size Linear Quad Ratio 1000 0.0000282000 0.0380 1347 3000 0.0001049000 0.3357 3200 5000 0.0001179000 0.9323 7907 7000 0.00016

Add a comment
Know the answer?
Add Answer to:
Next, create a simple benchmark experiment using the timeit module as we did in class. •...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PROGRAM DESCRIPTION Using the given class definitions for either C++, create a minimum heap that stores...

    PROGRAM DESCRIPTION Using the given class definitions for either C++, create a minimum heap that stores integers and and implements a minimum priority queue. (Your program can be "hard coded" for integers - it does not need to use templates, generics, or polymorphism.) Your data structure must always store its internal data as a heap. Your toString function should return a string with the heap values as a comma separated list, also including the size of the heap as well....

  • You have a complex project involving m independent tasks. Since the tasks can be performed in...

    You have a complex project involving m independent tasks. Since the tasks can be performed in parallel, the time to complete the project will be the maximum time taken by any task. You’d like to hire one of k companies to do the whole project, and you’re given a 2- dimensional list x with k rows and m columns, where x[i][j] is the amount of time company i would take to complete task j. Write a Python function hire(x) to...

  • C++: Create a class called "HashTable" This class will implement hashing on an array of integers...

    C++: Create a class called "HashTable" This class will implement hashing on an array of integers Make the table size 11 Implement with linear probing. The hash function should be: h(x) = x % 11 Create search(), insert() and delete() member functions. Search should return the index of where the target is located, insert should allow the user to insert a value, and delete removes the desired value from the table. In main perform the following: 1. Insert: 17 11...

  • Using an appropriate definition of ListNode, design a simple linked list class called StringList with the...

    Using an appropriate definition of ListNode, design a simple linked list class called StringList with the following member functions: void add (std::string); int positionOf (std::string); bool setNodeVal(int, std::string); std::vector<std::string> getAsVector(); a default constructor a copy constructor a destructor The add() function adds a new node containing the value of the parameter to the end of the list. The positionOf() function returns the (zero-based) position in the list for the first occurrence of the parameter in the list, or -1 if...

  • Before you start For this homework, we will need to import some libraries. You need to...

    Before you start For this homework, we will need to import some libraries. You need to execute the following cell only once; you don't need to copy this in every cell you run. In [ ]: import pandas import numpy from urllib.request import urlretrieve from matplotlib import pyplot %matplotlib inline ​ #This library is needed for testing from IPython.display import set_matplotlib_close set_matplotlib_close(False) Introduction In this homework, you will work with data from the World Bank. The subject of study is...

  • How can I write this code (posted below) using vectors instead of arrays? This is the...

    How can I write this code (posted below) using vectors instead of arrays? This is the task I have and the code below is for Task 1.3: Generate twenty random permutations of the number 0, 1, 2, ..., 9 using of the algorithms you designed for Task 1.3. Store these permutations into a vector and print them to the screen with the additional information of unchanged positions and number of calls torand(). Calculate the total numbers of unchanged positions. Compare...

  • 1. (10 points) Write an efficient iterative (i.e., loop-based) function Fibonnaci(n) that returns the nth Fibonnaci...

    1. (10 points) Write an efficient iterative (i.e., loop-based) function Fibonnaci(n) that returns the nth Fibonnaci number. By definition Fibonnaci(0) is 1, Fibonnaci(1) is 1, Fibonnaci(2) is 2, Fibonnaci(3) is 3, Fibonnaci(4) is 5, and so on. Your function may only use a constant amount of memory (i.e. no auxiliary array). Argue that the running time of the function is Θ(n), i.e. the function is linear in n. 2. (10 points) Order the following functions by growth rate: N, \N,...

  • Part 1: Using Idle Write a Python Script that Does the Following 1. At the top...

    Part 1: Using Idle Write a Python Script that Does the Following 1. At the top of your program, import the math library as in from math import * to make the functions in the math module available. Create a variable and assign into it a constant positive integer number of your choice. The number should be at most 10. 1 Suppose we call this variable x for this writeup document Try something like x = 4 2. Create another...

  • This is an assignment for my algorithm class which I have written the code partially and...

    This is an assignment for my algorithm class which I have written the code partially and only need to complete it by adding a time function that calculates the average running time. We could use any programming language we want so I am using C++. I am including the instruction and my partial code below. Thank you! Implement linearSearch(a,key) and binarySearch( a,key)functions. Part A.In this part we will calculate theaverage-case running time of each function.1.Request the user to enter a...

  • The file Sorting.java contains the Sorting class from Listing 9.9 in the text. This class implements...

    The file Sorting.java contains the Sorting class from Listing 9.9 in the text. This class implements both the selection sort and the insertion sort algorithms for sorting any array of Comparable objects in ascending order. In this exercise, you will use the Sorting class to sort several different types of objects. 1. The file Numbers.java reads in an array of integers, invokes the selection sort algorithm to sort them, and then prints the sorted array. Save Sorting.java and Numbers.java to...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT