数据结构与算法python语言实现-第五章答案

数据结构与算法python语言实现-第五章答案

5.2

import sys

try:
    n = int(sys.argv[1])#接收命令行参数
except:
    n = 100

import sys                              # provides getsizeof function
data = []
for k in range(n):                      # NOTE: must fix choice of n
  a = len(data)                         # number of elements
  b = sys.getsizeof(data)               # actual size in bytes
  if not b-8*a-64:
      print('Length: {0:3d}; Size in bytes: {1:4d}'.format(a, b))
  data.append(None)                     # increase length by one

5.4

 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  # count actual elements
       self._capacity = 1  # default array capacity
       self._A = self._make_array(self._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."""
       if -1*self._n < k < 0:
           return self._A[self._n +k]  # retrieve from array
       elif 0 <= k < self._n:
           return self._A[k]  # retrieve from array
       else:
           raise IndexError('invalid index')

   def append(self, obj):
       """Add object to end of the array."""
       if self._n == self._capacity:  # not enough room
           self._resize(2 * self._capacity)  # so double capacity
       self._A[self._n] = obj
       self._n += 1

   def _resize(self, c):  # nonpublic utitity
       """Resize internal array to capacity c."""
       B = self._make_array(c)  # new (bigger) array
       for k in range(self._n):  # for each existing value
           B[k] = self._A[k]
       self._A = B  # use the bigger array
       self._capacity = c

   def _make_array(self, c):  # nonpublic utitity
       """Return new array with capacity c."""
       return (c * ctypes.py_object)()  # see ctypes documentation

   def insert(self, k, value):
       """Insert value at index k, shifting subsequent values rightward."""
       # (for simplicity, we assume 0 <= k <= n in this verion)
       if self._n == self._capacity:  # not enough room
           self._resize(2 * self._capacity)  # so double capacity
       for j in range(self._n, k, -1):  # shift rightmost first
           self._A[j] = self._A[j - 1]
       self._A[k] = value  # store newest element
       self._n += 1

   def remove(self, value):
       """Remove first occurrence of value (or raise ValueError)."""
       # note: we do not consider shrinking the dynamic array in this version
       for k in range(self._n):
           if self._A[k] == value:  # found a match!
               for j in range(k, self._n - 1):  # shift others to fill gap
                   self._A[j] = self._A[j + 1]
               self._A[self._n - 1] = None  # help garbage collection
               self._n -= 1  # we have one less item
               return  # exit immediately
       raise ValueError('value not found')  # only reached if no match


A = DynamicArray()
for j in range(6):
   A.append(j)
for j in range(6):
   print(A[j])
print('\n',A[-2])

5.5
从k扩大到2k需3k,开销还包括从k/2到k的历次append,为k/2。
硬币应该在k/2到k的阶段收取完毕
开销为3k+k/2
收费次数为k-k/2=k/2
每次收费为(3k+k/2)/(k/2)=7
后半部分到扩大为一个周期。

5.6

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  # count actual elements
        self._capacity = 1  # default array capacity
        self._A = self._make_array(self._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."""
        if -1 * self._n < k < 0:
            return self._A[self._n + k]  # retrieve from array
        elif 0 <= k < self._n:
            return self._A[k]  # retrieve from array
        else:
            raise IndexError('invalid index')

    def append(self, obj):
        """Add object to end of the array."""
        if self._n == self._capacity:  # not enough room
            self._resize(2 * self._capacity)  # so double capacity
        self._A[self._n] = obj
        self._n += 1

    def _resize(self, c):  # nonpublic utitity
        """Resize internal array to capacity c."""
        B = self._make_array(c)  # new (bigger) array
        for k in range(self._n):  # for each existing value
            B[k] = self._A[k]
        self._A = B  # use the bigger array
        self._capacity = c

    def _make_array(self, c):  # nonpublic utitity
        """Return new array with capacity c."""
        return (c * ctypes.py_object)()  # see ctypes documentation

    def insert(self, k, value):
        """Insert value at index k, shifting subsequent values rightward."""
        # (for simplicity, we assume 0 <= k <= n in this verion)
        if self._n == self._capacity:  # not enough room
            B = self._A[0:k]
            B.append(value)
            for j in range(k, self._n):
                B.append(self._A[j])
            self._A = B
            self._n += 1
        else:
            for j in range(self._n, k, -1):  # shift rightmost first
                self._A[j] = self._A[j - 1]
            self._A[k] = value  # store newest element
            self._n += 1

    def remove(self, value):
        """Remove first occurrence of value (or raise ValueError)."""
        # note: we do not consider shrinking the dynamic array in this version
        for k in range(self._n):
            if self._A[k] == value:  # found a match!
                for j in range(k, self._n - 1):  # shift others to fill gap
                    self._A[j] = self._A[j + 1]
                self._A[self._n - 1] = None  # help garbage collection
                self._n -= 1  # we have one less item
                return  # exit immediately
        raise ValueError('value not found')  # only reached if no match


A = DynamicArray()
for j in range(4):
    A.append(j)
A.insert(2, 6)
for j in range(5):
    print(A[j])

5.7

def find(A,n):
    return sum(A)-sum(range(n))

A=(1,2,3,4,4,5,6)
print(find(A,7))

5.8

from time import time
N=10000
list = [j for j in range(N)]
start = time()
while list:
    list.pop(0)
end = time()
print((end - start) / N)


list = [j for j in range(N)]
start = time()
while list:
    list.pop(len(list) // 2)
end = time()
print((end - start) / N)

list = [j for j in range(N)]
start = time()
while list:
    list.pop(len(list)-1)
end = time()
print((end - start) / N)

5.26

def find_repetition(seq):
    seq=sorted(seq)
    a=[]
    for i in range(len(seq)-1):
        if seq[i]== seq[i+1]:
            a.append(seq[i])
    return a

def sorted(seq):
    for i in range(len(seq) - 1):
        for j in range(len(seq) - i-1):
            if seq[j] > seq[j + 1]:
                seq[j], seq[j + 1] = seq[j + 1], seq[j]
    return seq


seq=[0,2,2,3,5,6,4,8,6,6,4,4,3,41]
print(find_repetition(seq))

5.27

def find(seq,n):
    for i in range(len(seq)):
        if n==seq[i]:
            return False
        return True

def construct_seq(seq):
    for i in range(len(seq)):
        seq[i]=bin(seq[i])
    return seq
def bin(data):
    result=''
    if data :
        result=bin(data//2)
        return result+str(data%2)
    else:
        return result


a=[2,35,14,23,33,55]
a=construct_seq(a)
print(a)
print(find(a,'00'))

附栈实现进制转换

def bin2(data):
    result=[]
    while data :
        result.append(data%2)
        data=data//2
    result.reverse()
    return result

a=56
print(bin2(a))

递归实现进制转换

def bin(data):
    result=''
    if data :
        result=bin(data//2)
        return result+str(data%2)
    else:
        return result

你可能感兴趣的:(数据结构与算法python语言实现-第五章答案)