Question

In: Computer Science

Q: Using Python: Am trying to write a code that can be tested. Any assistance will...

Q: Using Python: Am trying to write a code that can be tested. Any assistance will be appreciated.

Would want Help in understanding and solving this example from Data Structure & Algorithms (Computer Science) with the steps of the solution to better understand, thanks.

The purpose of this assignment is the application of queues.

A prime number is a positive integer other than 1 and is divisible only by 1 and itself. For example, 7 is a prime number because the only positive factors of 7 are 1 and 7. On the other hand, 12 is not a prime number because 2, 3, 4, and 6 are also factors of 12.

You are asked to write a function to compute the prime numbers up to a given value. The function is named sieve and it will take an integer n as parameter. The function should return a list that contains all prime numbers up to (and including, if appropriate) n, the numbers in the returned list must be in ascending order.

def sieve (n):

For example:

• sieve (10) ➔ [2, 3, 5, 7]

• sieve (11) ➔ [2, 3, 5, 7, 11]

• sieve (20) ➔ [2, 3, 5, 7, 11, 13, 17, 19]

• sieve (100) ➔ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

The approach we will use is called the Eratosthenes sieve, which is discovered 2,300 years ago by Eratosthenes. We will explain the process in modern language and use a queue data structure in the process.

We start by creating an empty queue and enqueue all the numbers from 2 to n (inclusively, and in ascending order) into the queue.

During each round, the first number k at the front of the queue is a prime number; dequeue and append it to the result. Then we go through each number in the queue and delete the
numbers that are divisible by k. The easiest way to do this is first dequeue a number from the queue, if the number is divisible by k, do nothing (that is, we discard the number), otherwise, enqueue it back to the queue (and keep it). (Note that you may have to keep track the number of dequeues you have to do.)

The process finishes when the queue becomes empty.

Examples:

>>> runTestCase (50) Test 50 failed - expecting a list of length 630, got one of length 1 instead.


from ArrayQueue import ArrayQueue

def sieve (n):     return [1]

Solutions

Expert Solution

Here is the code in python with screenshot

=====================================================================================

def sieve (n):
      
    primes = [True for i in range(n+2)]
    p = 2
    while (p * p <= n): 
          
        # If prime[p] is not changed, then it is a prime 
        if (primes[p] == True): 
              
            # Update all multiples of p 
            for i in range(p * 2, n+2, p):
                primes[i] = False
        p += 1
    # returns the list of primes upto n
    return [i for i in range(2,n+1) if primes[i]==True]


  
print(sieve (10))
print(sieve (11))
print(sieve (20))
print(sieve (100))

=======================================================================================

thanks !


Related Solutions

Using Python, I am trying to integrate 'iloc' into the line of code below? This line...
Using Python, I am trying to integrate 'iloc' into the line of code below? This line is replacing all the '1' values across my .csv file and is throwing off my data aggregation. How would I implement 'iloc' so that this line of code only changes the '1's integers in my 'RIC' column? patient_data_df= patient_data_df.replace(to_replace=[1], value ="Stroke") Thank you:)
This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
how to write a code with python function trying to find minimum difference between any two...
how to write a code with python function trying to find minimum difference between any two elements in a list
I am trying to write code for a program in Visual Studo using Visual Basic programming...
I am trying to write code for a program in Visual Studo using Visual Basic programming language that computes the factorial of an entered number by using a For Loop. My problem is that it keeps re-setting the variable for Factorial. Below is my code if anyone can help. I want it to multiply the given number by that number - 1, then continuing to do so until it hits zero without multiplying by zero. Private Sub BtnCalculate_Click(sender As Object,...
I am trying to write a code in C for a circuit board reads in a...
I am trying to write a code in C for a circuit board reads in a temperature from a sensor on the circuit board and reads it onto a 7-segment LED display. How exactly would you code a floating 2 or 3 digit reading onto the LED display? I am stuck on this part.
I am trying to write the code for an 8 bit adder in VHDL so that...
I am trying to write the code for an 8 bit adder in VHDL so that I can program it onto my Elbert V2 Spartan 3A FPGA Development Board, but I keep getting errors. Any ideas what I am doing wrong? library IEEE; use IEEE.STD_LOGIC_1164.ALL; entity adder8bit is Port ( a : in STD_LOGIC_VECTOR(7 downto 0); b : in STD_LOGIC_VECTOR(7 downto 0); cin : in STD_LOGIC; o : out STD_LOGIC_VECTOR(7 downto 0); cout : out STD_LOGIC); end adder8bit; architecture Behavioral...
Working with Python. I am trying to make my code go through each subject in my...
Working with Python. I am trying to make my code go through each subject in my sample size and request something about it. For example, I have my code request from the user to input a sample size N. If I said sample size was 5 for example, I want the code to ask the user the following: "Enter age of subject 1" "Enter age of subject 2" "Enter age of subject 3" "Enter age of subject 4" "Enter age...
For these of string functions, write the code for it in C++ or Python (without using...
For these of string functions, write the code for it in C++ or Python (without using any of thatlanguage's built-in functions) You may assume there is a function to convert Small string into the language string type and a function to convert your language's string type back to Small string type. 1. int [] searchA,ll(string in...str, string sub): returns an array of positions of sub in in...str or an one element array with -1 if sub doesn't exist in in...str
Using python as the coding language please write the code for the following problem. Write a...
Using python as the coding language please write the code for the following problem. Write a function called provenance that takes two string arguments and returns another string depending on the values of the arguments according to the table below. This function is based on the geologic practice of determining the distance of a sedimentary rock from the source of its component grains by grain size and smoothness. First Argument Value Second Argument Value Return Value "coarse" "rounded" "intermediate" "coarse"...
Write the VERILOG code for an arithmetic/logic unit (ALU) following , and can be tested in...
Write the VERILOG code for an arithmetic/logic unit (ALU) following , and can be tested in on nexys 4 board This is to be implement on : ISE Design Suite - Xilinx /* ALU Arithmetic and Logic Operations ---------------------------------------------------------------------- |ALU_Sel| ALU Operation ---------------------------------------------------------------------- | 0000 | ALU_Out = A + B; ---------------------------------------------------------------------- | 0001 | ALU_Out = A - B; ---------------------------------------------------------------------- | 0010 | ALU_Out = A * B; ---------------------------------------------------------------------- | 0011 | ALU_Out = A / B; ---------------------------------------------------------------------- |...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT