Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

OurDynamicArrayclass,asgiveninCodeFragment5.3,doesnotsupport use of negative indices with getitem . Update that method to better match the semantics of a Python list. import ctypes # provides low-level

OurDynamicArrayclass,asgiveninCodeFragment5.3,doesnotsupport use of negative indices with getitem . Update that method to better match the semantics of a Python list.

import ctypes # provides low-level arrays class DynamicArray:

A dynamic array class akin to a simplified Python list.

def init (self): Create an empty array. self. n = 0 self. capacity = 1 self. A = self. make array(self. capacity)

# count actual elements # default array capacity # low-level array

def len (self): Return number of elements stored in the array. return self. n

def getitem (self, k): Return element at index k. ifnot0<=k

raise IndexError( invalid index ) return self. A[k]

def append(self, obj): Add object to end of the array. if self. n == self. capacity:

self. resize(2 self. capacity) self. A[self. n] = obj self. n += 1

def resize(self, c): Resize internal array to capacity c. B = self. make array(c) for k in range(self. n):

B[k] = self. A[k] self. A = B self. capacity = c

def make array(self, c): Return new array with capacity c. return (c ctypes.py object)( )

# retrieve from array

# not enough room # so double capacity

# nonpublic utitity

# new (bigger) array # for each existing value

# use the bigger array

# nonpublic utitity # see ctypes documentation

Code Fragment 5.3: An implementation of a DynamicArray class, using a raw array from the ctypes module as storage.

By python

Step by Step Solution

There are 3 Steps involved in it

Step: 1

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

Seven NoSQL Databases In A Week Get Up And Running With The Fundamentals And Functionalities Of Seven Of The Most Popular NoSQL Databases

Authors: Aaron Ploetz ,Devram Kandhare ,Sudarshan Kadambi ,Xun Wu

1st Edition

1787288862, 978-1787288867

More Books

Students also viewed these Databases questions