Question

In: Physics

Problem 5: writing a faster implementation For this homework assignment, you will write a faster implementation...

Problem 5: writing a faster implementation

For this homework assignment, you will write a faster implementation of do_insertions_simple (which we will call do_insertions_fast). We won't need anything extra (no special modules, no advanced algorithms, no Numpy) in order to obtain a considerable speedup.

Let's think about what makes do_insertions_simple slow, and about how we can rewrite the whole thing in a faster way. The biggest problem with do_insertions_simple is that it calls insert once for every element of the insertions list -- or 10,000 times, in our test case above. Insertion into a list is expensive, because it requires all the elements after the insertion point to be rearranged. So, insertions early in the list are especially expensive.

Appending to the end of a list, on the other hand, is very cheap, because nothing has to be rearranged. So, how can we make it that we use insert as little as possible, and instead use append whenever possible?

Here's one strategy for implementing do_insertions_fast:

  1. Create a new, empty list. We will use this list to build up the output.
  2. For each pair (i, x) in insertions, do the following:
    • If i is greater than the current length of the output list, insert x into the output list at the appropriate position.
    • Otherwise, do as follows:
      • Find out how many list elements should fall between the current end of the output list and the place x should go. Take only those elements from the original list l, and concatenate them to the output list.
      • Then append x to the end of the output list.
  3. Finally, after all insertions are done, concatenate any remaining elements of l onto the output list.
  4. Return the output list.

In the below cell, write your implementation of do_insertions_fast. You are not required to use the strategy outlined above, but it's a pretty good one, and I recommend it: using it, you should end up with something at least 100 times faster than do_insertions_simple!

Finally, here's one more hint if you decide to use the above strategy: keep track of the number of elements in l that have gone into the output list as you go along. This number will be useful in implementing the above strategy.

def do_insertions_fast(l, insertions):

    """Implement here a faster version of do_insertions_simple """

    # YOUR CODE HERE

Correctness

First, let's check that you compute the right thing.

import string

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

insertions = [(0, 'a'), (2, 'b'), (2, 'b'), (7, 'c')]

r1 = do_insertions_simple(l, insertions)

r2 = do_insertions_fast(l, insertions)

print("r1:", r1)

print("r2:", r2)

assert_equal(r1, r2)

is_correct = False

for _ in range(20):

    l, insertions = generate_testing_case(list_len=100, num_insertions=20)

    r1 = do_insertions_simple(l, insertions)

    r2 = do_insertions_fast(l, insertions)

    assert_equal(r1, r2)

    is_correct = True

Solutions

Expert Solution

Program

def do_insertions_fast(l, insertions):
"""Implement here a faster version of do_insertions_simple """
new = []
count = 0

for i, x in insertions:
space = i - len(new)
if i <= len(new):
new.insert(i, x)
else:
new += l[count:count+space]
count += space
new.append(x)
  
new += l[count:]

return new


import string
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
insertions = [(0, 'a'), (2, 'b'), (2, 'b'),(7, 'c')]
r1 = do_insertions_simple(l, insertions)
r2 = do_insertions_fast(l, insertions)
print("r1:", r1)
print("r2:", r2)
assert_equal(r1, r2)

is_correct = False
for _ in range(20):
l, insertions = generate_testing_case(list_len=100, num_insertions=20)
r1 = do_insertions_simple(l, insertions)
r2 = do_insertions_fast(l, insertions)
assert_equal(r1, r2)
is_correct = True

output

r1: ['a', 0, 'b', 'b', 1, 2, 3, 'c', 4, 5, 6, 7, 8, 9] r2: ['a', 0, 'b', 'b', 1, 2, 3, 'c', 4, 5, 6, 7, 8, 9]

Hope this helps!

Please let me know if any changes needed.

Thank you!

I hope you're safe during the pandemic


Related Solutions

In this homework assignment, you will be writing three `void` functions. These functions each take a...
In this homework assignment, you will be writing three `void` functions. These functions each take a single integer parameter. The functions accomplish the following tasks. * The first function prints out the sum of the numbers from 1 up to and including the number passed to it as an argument. * The second function prints out the sum of the even numbers from 2 up to and including the number passed to it as an argument. * The third function...
In writing the background for this weekend’s homework assignment, I realized that I didn’t need to...
In writing the background for this weekend’s homework assignment, I realized that I didn’t need to spend much time with the introduction of the company. Everyone knows Amazon, as a matter of fact, most of us shop on Amazon for many things that we use in our daily life. The company is one of the largest in the world and has over 500,000 employees. The CEO and founder of Amazon, Jeff Bezos, was interviewed at an awards ceremony in 2016...
Iterative implementation of a recursive algorithm executes faster than recursive implementation because no _____ needs to...
Iterative implementation of a recursive algorithm executes faster than recursive implementation because no _____ needs to be maintained. Select one: a. recursion b. iteration c. recurrence d. stack e. array
Topic is Big O Problem 5 Invent a faster solution to the ThreeSum problem. Then determine...
Topic is Big O Problem 5 Invent a faster solution to the ThreeSum problem. Then determine the number of triples of integers that sum to zero in 8ints.txt. Hint 1:Sort the array first (use Java’s built-inArrays.sort(int[] a))method to sort the array first. Hint 2:A pair a[i] and a[j] is part of a triple that sums to zero if and only if the value-(a[i]+ a[j])is in the array (but not a[i] or a[j] ). ----------------- ThreeSum.java import java.util.Arrays; public class ThreeSum...
Java Programming II Homework 2-1 In this assignment you are being asked to write some methods...
Java Programming II Homework 2-1 In this assignment you are being asked to write some methods that operate on an array of int values. You will code all the methods and use your main method to test your methods. Your class should be named Array Your class will have the following methods (click on the method signatures for the Javadoc description of the methods): [ https://bit.ly/2GZXGWK ] public static int sum(int[] arr) public static int sum(int[] arr, int firstIndex, int...
Section 3.1 The Derivative and the Tangent Line Problem Homework Assignment    Find the derivative of...
Section 3.1 The Derivative and the Tangent Line Problem Homework Assignment    Find the derivative of the function by the limit process    f(x)=1/x^2    h(s)=-2√s    Find the equation of the tangent line to the graph of the function at the given point.    f(x)=x^3+1,(-1,0)    f(x)=x-1/x,(1,0) Section 3.2 Basic Differentiation Rules and Rates of Change Homework Assignment    Find the derivative of the function    g(x)=∜x    y=2x^3+6x^2-1    g(t)=π cos⁡t    y=7x^4+2 sin⁡x    y=3/4 e^x+2 cos⁡x...
This is an individual assignment. In writing a paper about each problem, identify the consequences of...
This is an individual assignment. In writing a paper about each problem, identify the consequences of the actions taken, and then determine whether the actions taken represented a greater good, who would benefit from the good, and whether the consequences ethically justify the decisions and actions. The Mayor of a large city was given a free membership in an exclusive golf club by people who have received several city contracts. He also accepted gifts from organizations that have not done...
Instructions for this homework assignment are as follows: write a short answer essay in other words,...
Instructions for this homework assignment are as follows: write a short answer essay in other words, please write your answers clearly and ensure that you are fully answering the question, but at the same time, your answers should be concise. A range of approximately 2-4 sentences per question is ideal until you have explained it all. There is no maximum, but again it should be concise. 1. What is an offer and the 7 Ps of the marketing mix? What...
for this assignment, you are required to write a Retail Innovation Strategy Essay write a 3-5...
for this assignment, you are required to write a Retail Innovation Strategy Essay write a 3-5 page paper dicussing how innovation should be incorporated into a retail strategy. Specifically identify two retail innovations to ensure you have a global reach
Writing Assignment - Part I Choose an example of a Change in Accounting principles. Write a...
Writing Assignment - Part I Choose an example of a Change in Accounting principles. Write a statement paper on how this change would affect the financial statements of a company as they adopt the new principle. Prepare this written statement as if to the Board of Directors of your company. Writing Assignment - Part II Your CEO has inquired about the differences between the direct method and the indirect method of presenting the statement of cash flows. Prepare a memo...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT