Question

Implement these in Python 3 preferably.

Task: Implement the following algorithms to solve the Stock Span Problem using the ADT for a Stack in ython. The implementation of the ADT of a Stack (10 points) Implementation of computeSpans1 (20 points) Implementation of computeSpan2 (30 points) Provide the derived computational complexity of both computeSpans1 and computeSpans2 (40 points) Algorithm computeSpans1 (P) Input: an n-element list P of numbers such that P[i] is the prices of the stock on day I Output: an n-element list s of numbers such that S[i] is the span of the stock on day I for i ← 0 to n-1 do k←0; done ← false while (k<=1) or not done if P[1-k] P[i] k← then true <= k+1 else done return S Algorithm computeSpans2 (P) Input: an n-element list P of numbers such that P[i] is the prices of the stock on day I Output: an n-element list s of numbers such that S[i] is the span of the stock on day I Let D be an empty stack for i ← 0 to n-1 do h←0; done ← false while not (D.isEmpty ) or done) do if P[ǐ] then >= P[D.top ( )] else done ← true D.pop ( ) if D.isEmpty() then h←-1 else h< D . top ( ) D.push (i) return S

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

computeSpans1.py
-------------------------------------------------------------
import time
def computeSpans1(P):
    S = []
    start = time.time()
    for i in range(len(P)):
        k = 0
        done = False
        while (k<=i) and not done:
                if (P[i-k] <= P[i]):
                    k = k+1
                else:
                    done = True
        S.append(k)
    end = time.time()
    return S, end
P=[4,3,1,2,1,3,7]
S=computeSpans1(P)
print(S)
----------------------------------------------------------
computeSpans2.py
-----------------------------------
from Stack2 import *
import time
def computeSpans2(P):
    S = []
    D = Stack()

    start = time.time()
    for i in range(len(P)):
        h = 0
        done = False
        while not (D.is_empty() or done):
            if P[i] >= P[D.peek()]:
                D.pop()
            else:
                done = True
        if D.is_empty():
            h = -1
        else:
            h = D.peek()

        S.append(i - h)
        D.push(i)
    end = time.time()
    return S, end
prices = [4, 3, 1, 2, 1, 3, 7]
print(computeSpans2(prices))
-----------------------------------------------------------
Stack.py
----------------------------------
class Stack:
    def __init__(self):
        self.items = []

    def is_empty(self):
        if not self.items:
            return True
        else:
            return False

    def push(self, items):
        self.items.append(items)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items) - 1]

    def size(self):
        return len(self.items)


Add a comment
Know the answer?
Add Answer to:
Implement these in Python 3 preferably. Task: Implement the following algorithms to solve the Stock Span...
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
  • PLEASE CODE IN C++ AND MAKE IT COPYABLE! In this project, you will design and implement...

    PLEASE CODE IN C++ AND MAKE IT COPYABLE! In this project, you will design and implement an algorithm to determine the next greater element of an element in an array in Θ(n) time, where 'n' is the number of elements in the array. You could use the Stack ADT for this purpose. The next greater element (NGE) for an element at index i in an array A is the element that occurs at index j (i < j) such that...

  • [PYTHON] Objective Complete the function definitions generateRandomPoint,isIncircle, and ApproximatePI generateRandomPoi...

    [PYTHON] Objective Complete the function definitions generateRandomPoint,isIncircle, and ApproximatePI generateRandomPoint(): Returns a list (x,y) where x and y are uniformly sampled from the range [0,4 isIncircle(x,y): Returns True if p is in the circle; otherwise, False (Note: The point p is in the circle if its distance from the center of the circle is less than or equal to the radius of the circle.) ApproximatePI (n): Generates n random points within the square and returns 4 P(A) Example #1 Input:...

  • Convert following code to implement linked list C++ language #include<iostream> using namespace std; int top =...

    Convert following code to implement linked list C++ language #include<iostream> using namespace std; int top = -1; //globally defining the value of top, as the stack is empty void push(int stack[], int x, int n) { if (top == -1) //if top position is the last of posiition of stack,means stack is full { cout << "Stack is full Overflow condition"; } else { top = top + 1; //incrementing top position stack[top] = x; //inserting element on incremented position...

  • Please explain the python code below L1 = [2, 15, 'Carol', 7.4, 0, -10, -6, 42,...

    Please explain the python code below L1 = [2, 15, 'Carol', 7.4, 0, -10, -6, 42, 27, -1, 2.0, 'hello', [2, 4], 23] print("L1 =",L1) odds =[] evens=[] list=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',',','.'] no=0 for i in L1: i=str(i) for j in list: if i.find(j)>=0: no=1 if no==1: None else: i=int(i) if i%2==0: evens.append(i) else: odds.append(i) no=0      ...

  • The language is python thr language is python I Expert Q&A Done The language is python....

    The language is python thr language is python I Expert Q&A Done The language is python. 10. The following is the algorithm for Merge Sort, one of the best sorting algorithms and one hat is recursive. Wine the merge sort function and draw the stack and heap dagrams for execution on the list |5, 8,9,1,4. 10 Algorithm: Mergesort Ingut an unsorted list b 1. If there is only one iten L. It is sorted, return L 2, Split L Sn...

  • **TStack.py below** # CMPT 145: Linear ADTs # Defines the Stack ADT # # A stack (also called a pushdown or LIFO stack)...

    **TStack.py below** # CMPT 145: Linear ADTs # Defines the Stack ADT # # A stack (also called a pushdown or LIFO stack) is a compound # data structure in which the data values are ordered according # to the LIFO (last-in first-out) protocol. # # Implementation: # This implementation was designed to point out when ADT operations are # used incorrectly. def create(): """ Purpose creates an empty stack Return an empty stack """ return '__Stack__',list() def is_empty(stack): """...

  • 1) Which of the following is NOT true about a Python variable? a) A Python variable...

    1) Which of the following is NOT true about a Python variable? a) A Python variable must have a value b) A Python variable can be deleted c) The lifetime of a Python variable is the whole duration of a program execution.   d) A Python variable can have the value None.        2) Given the code segment:        What is the result of executing the code segment? a) Syntax error b) Runtime error c) No error      d) Logic error 3) What...

  • Stacks and Java 1. Using Java design and implement a stack on an array. Implement the...

    Stacks and Java 1. Using Java design and implement a stack on an array. Implement the following operations: push, pop, top, size, isEmpty. Make sure that your program checks whether the stack is full in the push operation, and whether the stack is empty in the pop operation. None of the built-in classes/methods/functions of Java can be used and must be user implemented. Practical application 1: Arithmetic operations. (a) Design an algorithm that takes a string, which represents an arithmetic...

  • General Instructions In this task, answer all the following questions and complement each answer with a...

    General Instructions In this task, answer all the following questions and complement each answer with a detailed explanation 1. Design a 0(n log n)-time algorithm that, given a set S of n integer numbers and another integer x determines whether or not there exist two elements in S whose sum is exactly x 2. A Stack data structure provides Push and Pop, the two operations to write and read data, respectively. Extend this data structure so that, in addition 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