Cấu trúc dữ liệu và giải thuật trong Python đáp án bài tập

Có một bộ sưu tập video tuyệt vời trên YouTube do Gerry Jenkins ghi lại để hỗ trợ tất cả các chương trong văn bản này

Sự nhìn nhận

Chúng tôi rất biết ơn Nhà xuất bản Franklin Beedle đã cho phép chúng tôi cung cấp miễn phí sách giáo khoa tương tác này. Phiên bản trực tuyến này được dành để tưởng nhớ biên tập viên đầu tiên của chúng tôi, Jim Leisy, người muốn chúng tôi “thay đổi thế giới. ”

Cấu trúc dữ liệu và thuật toán là một trong những khái niệm cơ bản nhất của Khoa học máy tính. Cho dù đó là vấn đề trong thế giới thực mà bạn đang cố gắng giải quyết hay câu hỏi mã hóa điển hình được hỏi trong một cuộc phỏng vấn, hầu hết mọi vấn đề đều yêu cầu bạn thể hiện sự hiểu biết sâu sắc về cấu trúc dữ liệu. Xem thêm

R-2. 5 Sử dụng các kỹ thuật của Phần 1. 7 để sửa đổi khoản phí và thực hiện các phương thức thanh toán của lớp CreditCard để đảm bảo rằng người gọi sẽ gửi một số dưới dạng tham số

class CreditCard:
  """A consumer credit card."""
  
  def __init__(self, customer, bank, acnt, limit):
    """Create a new credit card instance.

    The initial balance is zero.

    customer  the name of the customer (e.g., 'John Bowman')
    bank      the name of the bank (e.g., 'California Savings')
    acnt      the acount identifier (e.g., '5391 0375 9387 5309')
    limit     credit limit (measured in dollars)
    """
    self._customer = customer
    self._bank = bank
    self._account = acnt
    self._limit = limit
    self._balance = 0

  def get_customer(self):
    """Return name of the customer."""
    return self._customer
    
  def get_bank(self):
    """Return the bank's name."""
    return self._bank

  def get_account(self):
    """Return the card identifying number (typically stored as a string)."""
    return self._account

  def get_limit(self):
    """Return current credit limit."""
    return self._limit

  def get_balance(self):
    """Return current balance."""
    return self._balance

  def charge(self, price):
      
    """Charge given price to the card, assuming sufficient credit limit.

    Return True if charge was processed; False if charge was denied.
    """
    if not isinstance(price, (int, float)):
        raise TypeError('price must be numeric')
    if price + self._balance > self._limit:  # if charge would exceed limit,
      return False                           # cannot accept charge
    else:
      self._balance += price
      return True

  def make_payment(self, amount):
    """Process customer payment that reduces balance."""
    if not isinstance(amount, (int, float)):
        raise TypeError('amount must be numeric')
    self._balance -= amount

if __name__ == '__main__':
  wallet = []
  wallet.append(CreditCard('John Bowman', 'California Savings',
                           '5391 0375 9387 5309', 2500) )
  wallet.append(CreditCard('John Bowman', 'California Federal',
                           '3485 0399 3395 1954', 3500) )
  wallet.append(CreditCard('John Bowman', 'California Finance',
                           '5391 0375 9387 5309', 5000) )

  for val in range(1, 17):
    wallet[0].charge(val)
    wallet[1].charge(2*val)
    wallet[2].charge(3*val)

  for c in range(3):
    print('Customer =', wallet[c].get_customer())
    print('Bank =', wallet[c].get_bank())
    print('Account =', wallet[c].get_account())
    print('Limit =', wallet[c].get_limit())
    print('Balance =', wallet[c].get_balance())
    while wallet[c].get_balance() > 100:
      wallet[c].make_payment(100)
      print('New balance =', wallet[c].get_balance())
    print()

R-2. 6 Nếu tham số cho phương thức thanh toán của loại CreditCard là số âm, điều đó sẽ có tác dụng làm tăng số dư trên tài khoản. Sửa đổi việc triển khai để nó tăng ValueError nếu một giá trị âm được gửi

class CreditCard:
  """A consumer credit card."""
  
  def __init__(self, customer, bank, acnt, limit):
    """Create a new credit card instance.

    The initial balance is zero.

    customer  the name of the customer (e.g., 'John Bowman')
    bank      the name of the bank (e.g., 'California Savings')
    acnt      the acount identifier (e.g., '5391 0375 9387 5309')
    limit     credit limit (measured in dollars)
    """
    self._customer = customer
    self._bank = bank
    self._account = acnt
    self._limit = limit
    self._balance = 0

  def get_customer(self):
    """Return name of the customer."""
    return self._customer
    
  def get_bank(self):
    """Return the bank's name."""
    return self._bank

  def get_account(self):
    """Return the card identifying number (typically stored as a string)."""
    return self._account

  def get_limit(self):
    """Return current credit limit."""
    return self._limit

  def get_balance(self):
    """Return current balance."""
    return self._balance

  def charge(self, price):
      
    """Charge given price to the card, assuming sufficient credit limit.

    Return True if charge was processed; False if charge was denied.
    """
    if not isinstance(price, (int, float)):
        raise TypeError('price must be numeric')
    if price + self._balance > self._limit:  # if charge would exceed limit,
      return False                           # cannot accept charge
    else:
      self._balance += price
      return True

  def make_payment(self, amount):
    """Process customer payment that reduces balance."""
    if not isinstance(amount, (int, float)):
        raise TypeError('amount must be numeric')
    elif amount < 0:
        raise ValueError('amount cannot be negative')
    self._balance -= amount

if __name__ == '__main__':
  wallet = []
  wallet.append(CreditCard('John Bowman', 'California Savings',
                           '5391 0375 9387 5309', 2500) )
  wallet.append(CreditCard('John Bowman', 'California Federal',
                           '3485 0399 3395 1954', 3500) )
  wallet.append(CreditCard('John Bowman', 'California Finance',
                           '5391 0375 9387 5309', 5000) )

  for val in range(1, 17):
    wallet[0].charge(val)
    wallet[1].charge(2*val)
    wallet[2].charge(3*val)

  for c in range(3):
    print('Customer =', wallet[c].get_customer())
    print('Bank =', wallet[c].get_bank())
    print('Account =', wallet[c].get_account())
    print('Limit =', wallet[c].get_limit())
    print('Balance =', wallet[c].get_balance())
    while wallet[c].get_balance() > 100:
      wallet[c].make_payment(100)
      print('New balance =', wallet[c].get_balance())
    print()
R-2. 7 Loại thẻ tín dụng của Phần 2. 3 khởi tạo số dư của tài khoản mới về 0. Sửa đổi lớp đó để một tài khoản mới có thể được cấp số dư khác không bằng cách sử dụng tham số thứ năm tùy chọn cho hàm tạo. Cú pháp hàm tạo bốn tham số sẽ tiếp tục tạo tài khoản có số dư bằng không.
______2

R-2. 8 Sửa đổi phần khai báo của vòng lặp for đầu tiên trong các bài kiểm tra Thẻ tín dụng, từ Đoạn mã 2. 3, để cuối cùng nó sẽ khiến chính xác một trong ba thẻ tín dụng vượt quá giới hạn tín dụng của nó. Đó là thẻ tín dụng nào?

trả lời. Thẻ tín dụng thứ ba

______3R-2. 9 Thực hiện phương thức con cho lớp Vector của Phần 2. 3. 3, sao cho biểu thức u−v trả về một thể hiện vectơ mới biểu thị hiệu giữa hai vectơ.
______4R-2. 10 Thực hiện phương thức phủ định cho lớp Vector của Phần 2. 3. 3, sao cho biểu thức −v trả về một thể hiện vectơ mới có tọa độ là tất cả các giá trị phủ định của tọa độ tương ứng của v.
______5R-2. 11 Trong Phần 2. 3. 3, chúng tôi lưu ý rằng lớp Vector của chúng tôi hỗ trợ một cú pháp như v = u + [5, 3, 10, −2, 1], trong đó tổng của một vectơ và danh sách trả về một vectơ mới. Tuy nhiên, cú pháp v = [5, 3, 10, −2, 1] + u là sai. Giải thích cách định nghĩa lớp Vector có thể được sửa đổi để cú pháp này tạo ra một vector mới.
______6R-2. 12 Thực hiện phương thức mul cho lớp Vector của Phần 2. 3. 3, sao cho biểu thức v 3 trả về một vectơ mới có tọa độ gấp 3 lần tọa độ tương ứng của v.
______7R-2. 13 Bài tập R-2. 12 yêu cầu triển khai mul , cho lớp Vector của Phần 2. 3. 3, để cung cấp hỗ trợ cho cú pháp v 3. Triển khai phương thức rmul, để cung cấp hỗ trợ bổ sung cho cú pháp 3 v.
  def __rmul__(self,factor):
    """Return copy of vector with all coordinates negated."""
    result = Vector(len(self))           # start with vector of zeros
    for j in range(len(self)):
      result[j] = factor*self[j]
    return result

R-2. 14 Thực hiện phương thức mul cho lớp Vector của Phần 2. 3. 3, sao cho biểu thức u v trả về một đại lượng vô hướng biểu thị tích vô hướng của các vectơ

  def __mul__(other1,other2):
    """Return copy of vector with all coordinates negated."""
    result = 0           # start with vector of zeros
    for j in range(len(other1)):
      result+= other1[j]*other2[j]
    return result

R-2.15 The Vector class of Section 2.3.3 provides a constructor that takes an integer d, and produces a d-dimensional vector with all coordinates equal to 0. Another convenient form for creating a new vector would be to send the constructor a parameter that is some iterable type representing a sequence of numbers, and to create a vector with dimension equal to the length of that sequence and coordinates equal to the sequence values. For example, Vector([4, 7, 5]) would produce a three-dimensional vector with coordinates <4, 7, 5>. Modify the constructor so that either of these forms is acceptable; that is, if a single integer is sent, it produces a vector of that dimension with all zeros, but if a sequence of numbers is provided, it produces a vector with coordinates based on that sequence.

____10R-2. 18 Cho một đoạn mã Python ngắn sử dụng các lớp cấp tiến từ Phần 2. 4. 2 để tìm giá trị thứ 8 của cấp số Fibonacci bắt đầu bằng 2 và 2 là hai giá trị đầu tiên của nó.
______11R-2. 22 Bộ sưu tập. Lớp cơ sở trừu tượng trình tự không cung cấp hỗ trợ để so sánh hai trình tự với nhau. Sửa đổi lớp Trình tự của chúng tôi từ Đoạn mã 2. 14 để bao gồm định nghĩa cho phương thức eq, sao cho biểu thức seq1 == seq2 sẽ trả về True một cách chính xác khi hai chuỗi tương đương với từng phần tử.
______12R-2. 23 Theo tinh thần tương tự như bài toán trước, hãy bổ sung lớp Sequence bằng phương thức lt , để hỗ trợ so sánh từ điển seq1 < seq2.
______13C-2. 25 Bài tập R-2. 12 sử dụng phương thức mul để hỗ trợ nhân một Vector với một số, trong khi Bài tập R-2. 14 sử dụng phương thức mul để hỗ trợ tính toán tích vô hướng của hai vectơ. Đưa ra một triển khai duy nhất của Vector. mul sử dụng kiểm tra loại thời gian chạy để hỗ trợ cả hai cú pháp u*v và u*k, trong đó u và v chỉ định các thể hiện vectơ và k đại diện cho

một số.

class CreditCard:
  """A consumer credit card."""
  
  def __init__(self, customer, bank, acnt, limit):
    """Create a new credit card instance.

    The initial balance is zero.

    customer  the name of the customer (e.g., 'John Bowman')
    bank      the name of the bank (e.g., 'California Savings')
    acnt      the acount identifier (e.g., '5391 0375 9387 5309')
    limit     credit limit (measured in dollars)
    """
    self._customer = customer
    self._bank = bank
    self._account = acnt
    self._limit = limit
    self._balance = 0

  def get_customer(self):
    """Return name of the customer."""
    return self._customer
    
  def get_bank(self):
    """Return the bank's name."""
    return self._bank

  def get_account(self):
    """Return the card identifying number (typically stored as a string)."""
    return self._account

  def get_limit(self):
    """Return current credit limit."""
    return self._limit

  def get_balance(self):
    """Return current balance."""
    return self._balance

  def charge(self, price):
      
    """Charge given price to the card, assuming sufficient credit limit.

    Return True if charge was processed; False if charge was denied.
    """
    if not isinstance(price, (int, float)):
        raise TypeError('price must be numeric')
    if price + self._balance > self._limit:  # if charge would exceed limit,
      return False                           # cannot accept charge
    else:
      self._balance += price
      return True

  def make_payment(self, amount):
    """Process customer payment that reduces balance."""
    if not isinstance(amount, (int, float)):
        raise TypeError('amount must be numeric')
    elif amount < 0:
        raise ValueError('amount cannot be negative')
    self._balance -= amount

if __name__ == '__main__':
  wallet = []
  wallet.append(CreditCard('John Bowman', 'California Savings',
                           '5391 0375 9387 5309', 2500) )
  wallet.append(CreditCard('John Bowman', 'California Federal',
                           '3485 0399 3395 1954', 3500) )
  wallet.append(CreditCard('John Bowman', 'California Finance',
                           '5391 0375 9387 5309', 5000) )

  for val in range(1, 17):
    wallet[0].charge(val)
    wallet[1].charge(2*val)
    wallet[2].charge(3*val)

  for c in range(3):
    print('Customer =', wallet[c].get_customer())
    print('Bank =', wallet[c].get_bank())
    print('Account =', wallet[c].get_account())
    print('Limit =', wallet[c].get_limit())
    print('Balance =', wallet[c].get_balance())
    while wallet[c].get_balance() > 100:
      wallet[c].make_payment(100)
      print('New balance =', wallet[c].get_balance())
    print()
4

C-2. 26 Lớp SequenceIterator của Phần 2. 3. 4 cung cấp cái được gọi là trình lặp chuyển tiếp. Triển khai một lớp có tên ReversedSequenceIterator phục vụ như một trình lặp đảo ngược cho bất kỳ loại trình tự Python nào. Lệnh gọi next đầu tiên sẽ trả về phần tử cuối cùng của chuỗi, lệnh gọi thứ hai tới next sẽ trả về phần tử thứ hai đến cuối cùng, v.v.

____15C-2. 32 Viết một lớp Python mở rộng lớp Cấp tiến sao cho mỗi giá trị trong cấp số là căn bậc hai của giá trị trước đó. (Lưu ý rằng bạn không còn có thể biểu thị từng giá trị bằng một số nguyên. ) Hàm tạo của bạn phải chấp nhận tham số tùy chọn chỉ định giá trị bắt đầu, sử dụng 65, 536 làm giá trị mặc định.
______16

P-2. 33 Viết chương trình Python nhập một đa thức theo ký hiệu đại số chuẩn và xuất đạo hàm bậc nhất của đa thức đó

class CreditCard:
  """A consumer credit card."""
  
  def __init__(self, customer, bank, acnt, limit):
    """Create a new credit card instance.

    The initial balance is zero.

    customer  the name of the customer (e.g., 'John Bowman')
    bank      the name of the bank (e.g., 'California Savings')
    acnt      the acount identifier (e.g., '5391 0375 9387 5309')
    limit     credit limit (measured in dollars)
    """
    self._customer = customer
    self._bank = bank
    self._account = acnt
    self._limit = limit
    self._balance = 0

  def get_customer(self):
    """Return name of the customer."""
    return self._customer
    
  def get_bank(self):
    """Return the bank's name."""
    return self._bank

  def get_account(self):
    """Return the card identifying number (typically stored as a string)."""
    return self._account

  def get_limit(self):
    """Return current credit limit."""
    return self._limit

  def get_balance(self):
    """Return current balance."""
    return self._balance

  def charge(self, price):
      
    """Charge given price to the card, assuming sufficient credit limit.

    Return True if charge was processed; False if charge was denied.
    """
    if not isinstance(price, (int, float)):
        raise TypeError('price must be numeric')
    if price + self._balance > self._limit:  # if charge would exceed limit,
      return False                           # cannot accept charge
    else:
      self._balance += price
      return True

  def make_payment(self, amount):
    """Process customer payment that reduces balance."""
    if not isinstance(amount, (int, float)):
        raise TypeError('amount must be numeric')
    elif amount < 0:
        raise ValueError('amount cannot be negative')
    self._balance -= amount

if __name__ == '__main__':
  wallet = []
  wallet.append(CreditCard('John Bowman', 'California Savings',
                           '5391 0375 9387 5309', 2500) )
  wallet.append(CreditCard('John Bowman', 'California Federal',
                           '3485 0399 3395 1954', 3500) )
  wallet.append(CreditCard('John Bowman', 'California Finance',
                           '5391 0375 9387 5309', 5000) )

  for val in range(1, 17):
    wallet[0].charge(val)
    wallet[1].charge(2*val)
    wallet[2].charge(3*val)

  for c in range(3):
    print('Customer =', wallet[c].get_customer())
    print('Bank =', wallet[c].get_bank())
    print('Account =', wallet[c].get_account())
    print('Limit =', wallet[c].get_limit())
    print('Balance =', wallet[c].get_balance())
    while wallet[c].get_balance() > 100:
      wallet[c].make_payment(100)
      print('New balance =', wallet[c].get_balance())
    print()
7

P-2. 34 Viết chương trình Python nhập vào một tài liệu và sau đó xuất ra biểu đồ thanh biểu đồ tần số của mỗi ký tự bảng chữ cái xuất hiện trong tài liệu đó

Tôi có thể thực hành cấu trúc dữ liệu và thuật toán trong Python ở đâu?

6 Khóa học tốt nhất để học cấu trúc dữ liệu và thuật toán với Python năm 2022 .
Python cho cấu trúc dữ liệu, thuật toán và phỏng vấn. .
Thuật toán và cấu trúc dữ liệu trong Python [Khóa học tốt nhất của Udemy].
LeetCode trong Python. 50 câu hỏi phỏng vấn viết mã thuật toán. .
Cấu trúc dữ liệu cho các cuộc phỏng vấn viết mã trong Python [Giáo dục]

Tôi có thể sử dụng Python cho Cấu trúc dữ liệu và thuật toán không?

Cấu trúc dữ liệu là nguyên tắc cơ bản của bất kỳ ngôn ngữ lập trình nào mà chương trình được xây dựng xung quanh đó. Python giúp tìm hiểu kiến ​​thức cơ bản của các cấu trúc dữ liệu này theo cách đơn giản hơn so với các ngôn ngữ lập trình khác .

Tôi có thể thực hành cấu trúc dữ liệu và giải thuật ở đâu?

7 trang web tốt nhất để chuẩn bị cho câu hỏi phỏng vấn về cấu trúc dữ liệu, thuật toán và mã hóa .
Udemy. Đây là một trong những trang web tốt nhất để tìm các khóa học chuẩn bị phỏng vấn lập trình với giá cả phải chăng. .
giáo dục. .
LeetCode. .
Xếp hạng tin tặc. .
CodeFights. .
bánh phỏng vấn. .
xe đẩy. .
5 cuốn sách và khóa học hay nhất cho các cuộc phỏng vấn viết mã

Các chủ đề trong cấu trúc dữ liệu và thuật toán trong Python là gì?

Có bốn loại cấu trúc dữ liệu dựng sẵn trong Python. danh sách, bộ dữ liệu, bộ và từ điển. .
Danh sách. Danh sách được xác định bằng cách sử dụng dấu ngoặc vuông và giữ dữ liệu được phân tách bằng dấu phẩy. .
Tuple. Một tuple là một thùng chứa khác. .
Bộ. Set là một tập hợp các phần tử duy nhất có thể thay đổi và không có thứ tự. .
Từ điển