Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

StaticArray is a very simple class that simulates the behavior of a fixed-size array. It has only four methods, and contains code to support bracketed

Write a function that receives a StaticArray of integers and returns a new StaticArray object with the 

StaticArray is a very simple class that simulates the behavior of a fixed-size array. It has only four methods, and contains code to support bracketed indexing ([]): 1) init() - Creates a new static array that will store a fixed number of elements. Once the StaticArray is created, its size cannot be changed. 2) set() - Changes the value of any element using its index. 3) get() - Reads the value of any element using its index. 4) length() - Queries the number of elements in the array. 

Please review the code and comments in the StaticArray class to better understand the available methods, their use, and input/output parameters. Note that since StaticArray is intentionally a very simple class, it does not possess the many capabilities typically associated with Python solutions using only the available StaticArray functionality, as described above. 

RESTRICTIONS: You are NOT allowed to use ANY built-in Python data structures and/or their methods in any of your solutions. This includes built-in Python lists, dictionaries, or anything else. Variables for holding a single value, or a tuple holding two/three values, are allowed. It is also OK to use built-in Python generator functions like range(). You are NOT allowed to directly access any variables of the StaticArray class (e.g. self._size or self._data). Access to StaticArray variables must be done by using the StaticArray class methods.

class StaticArrayException(Exception):
    """
    Custom exception for Static Array class.
    Any changes to this class are forbidden.
    """
    pass
class StaticArray:
    """
    Implementation of Static Array Data Structure.
    Implemented methods: get(), set(), length()
    Any changes to this class are forbidden.
    Even if you make changes to your StaticArray file and upload to Gradescope
    along with your assignment, it will have no effect. Gradescope uses its
    own StaticArray file (a replica of this one) and any extra submission of
    a StaticArray file is ignored.
    """
    def __init__(self, size: int = 10) -> None:
        """
        Create array of given size.
        Initialize all elements with values of None.
        If requested size is not a positive number,
        raise StaticArray Exception.
        """
        if size             raise StaticArrayException('Array size must be a positive integer')
        # The underscore denotes this as a private variable and
        # private variables should not be accessed directly.
        # Use the length() method to get the size of a StaticArray.
        self._size = size
        # Remember, this is a built-in list and is used here
        # because Python doesn't have a fixed-size array type.
        # Don't initialize variables like this in your assignments!
        self._data = [None] * size
    def __iter__(self) -> None:
        """
        Disable iterator capability for StaticArray class.
        This means loops and aggregate functions like
        those shown below won't work:
        arr = StaticArray()
        for value in arr:     # will not work
        min(arr)              # will not work
        max(arr)              # will not work
        sort(arr)             # will not work
        """
        return None
    def __str__(self) -> str:
        """Override string method to provide more readable output."""
        return f"STAT_ARR Size: {self._size} {self._data}"
    def get(self, index: int):
        """
        Return value from given index position.
        Invalid index raises StaticArrayException.
        """
        if index = self.length():
            raise StaticArrayException('Index out of bounds')
        return self._data[index]
    def set(self, index: int, value) -> None:
        """
        Store value at given index in the array.
        Invalid index raises StaticArrayException.
        """
        if index = self.length():
            raise StaticArrayException('Index out of bounds')
        self._data[index] = value
    def __getitem__(self, index: int):
        """Enable bracketed indexing."""
        return self.get(index)
    def __setitem__(self, index: int, value: object) -> None:
        """Enable bracketed indexing."""
        self.set(index, value)
    def length(self) -> int:
        """Return length of the array (number of elements)."""
        return self._size
if __name__ == "__main__":
    # Using the Static Array #
    # Can use either the get/set methods or [] (bracketed indexing)         #
    # Both are public methods; using the [] calls the corresponding get/set #
    arr = StaticArray()
    # These two statements are equivalent
    arr.set(0, 'hello')
    arr[0] = 'hello'
    # These two statements are equivalent
    print(arr.get(0))
    print(arr[0])
    # Print the number of elements stored in the array
    print(arr.length())
    arr = StaticArray(5)
    # Set the value of each element equal to its index multiplied by 10
    for index in range(arr.length()):
        arr[index] = index * 10
    # Print the values of all elements in reverse order
    for index in range(arr.length() - 1, -1, -1):
        print(arr[index])
    # Special consideration below #
    # Don't do this! This creates a built-in Python list and if you use
    # one you'll lose points.
    forbidden_list = [None] * 10
    print(type(arr))
    print(type(forbidden_list))
 

Write a function that receives a StaticArray of integers and returns a new StaticArray object with the content of the original array, modified as follows: 1) If the number in the original array is divisible by 3, the corresponding element in the new array will be the string 'fizz'. 2) If the number in the original array is divisible by 5, the corresponding element in the new array will be the string 'buzz'. 3) If the number in the original array is both a multiple of 3 and a multiple of 5, the corresponding element in the new array will be the string 'fizzbuzz'. 4) In all other cases, the element in the new array will have the same value as in the original array. The content of the input array must not be changed. You may assume that the input array will contain only integers, and will have at least one element. You do not need to check for these conditions. For full credit, the function must be implemented with O(N) complexity. Example #1: source= [for in range (-5, 20, 4)] arr StaticArray (len (source)) for i, value in enumerate (source): arr[i] = value print (fizz_buzz (arr)) print (arr) Output: STAT_ARR Size: 7 ['buzz', -1, 'fizz', 7, 11, 'fizzbuzz', 19] STAT_ARR Size: 7 [-5, -1, 3, 7, 11, 15, 19]

Step by Step Solution

3.51 Rating (144 Votes )

There are 3 Steps involved in it

Step: 1

To achieve the desired functionality you can implement the fizzbuzz function as follows Code def fizzbuzzinputarray Modify the input array based on the FizzBuzz rules param inputarray StaticArray of i... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Java An Introduction To Problem Solving And Programming

Authors: Walter Savitch

8th Edition

0134462033, 978-0134462035

More Books

Students also viewed these Programming questions

Question

Solve this system of equations -3x-y 5 -3x - 4y 83 || y = 1 11

Answered: 1 week ago

Question

=+9. Explain the steps needed to formulate a social media strategy

Answered: 1 week ago