Đ Án Python

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Bài 1: Viết chương trình để chuyển đổi giữa 2 hệ cơ số:

a) Cơ số 10 và cơ số 2
b) Cơ số 10 và cơ số 16

a) Chuyển đổi giữa cơ số 10 và cơ số 2:


def decimal_to_binary(decimal):
binary = bin(decimal)
return binary[2:]
def binary_to_decimal(binary):
decimal = int(binary, 2)
return decimal
choice = input("Chọn chuyển đổi:\n1. Cơ số 10 sang cơ số 2\n2. Cơ số 2 sang cơ số 10\n")
if choice == '1':
decimal_number = int(input("Nhập số cơ số 10: "))
binary_number = decimal_to_binary(decimal_number)
print(f"Cơ số 2: {binary_number}")
elif choice == '2':
binary_number = input("Nhập số cơ số 2: ")
decimal_number = binary_to_decimal(binary_number)
print(f"Cơ số 10: {decimal_number}")
else:
print("Lựa chọn không hợp lệ.")

b) Chuyển đổi giữa cơ số 10 và cơ số 16:


def decimal_to_hexadecimal(decimal):
hexadecimal = hex(decimal)
return hexadecimal[2:]
def hexadecimal_to_decimal(hexadecimal):
decimal = int(hexadecimal, 16)
return decimal
choice = input("Chọn chuyển đổi:\n1. Cơ số 10 sang cơ số 16\n2. Cơ số 16 sang cơ số 10\
n")
if choice == '1':
decimal_number = int(input("Nhập số cơ số 10: "))
hexadecimal_number = decimal_to_hexadecimal(decimal_number)
print(f"Cơ số 16: {hexadecimal_number.upper()}")
elif choice == '2':
hexadecimal_number = input("Nhập số cơ số 16: ")
decimal_number = hexadecimal_to_decimal(hexadecimal_number)
print(f"Cơ số 10: {decimal_number}")
else:
print("Lựa chọn không hợp lệ.")
Bài 2: Viết chương trình tìm tất cả các cặp dấu ngoặc tương ứng trong một chương trình
viết bằng ngôn ngữ lập trình Python.
Cho xâu S chỉ gồm ký tự “(“ và “)”. Kiểm tra xem S có phải là dãy ngoặc đúng không.
Nếu S là dãy ngoặc đúng, với mỗi vị trí trong S, in ra vị trí của dấu ngoặc tương ứng.
Định nghĩa:
• Xâu rỗng là dãy ngoặc đúng.
• Nếu xâu A là dãy ngoặc đúng thì (A) cũng là dãy ngoặc đúng. Khi đó, cặp dấu ngoặc
quanh xâu A này là cặp dấu ngoặc tương ứng.
• Nếu xâu A và B đều là dãy ngoặc đúng thì xâu A+B cũng là dãy ngoặc đúng
Hình ảnh minh họa cho một dãy ngoặc đúng. Các cặp dấu ngoặc tương ứng được tô cùng
màu:

def find_matching_parentheses(s):
stack = []
matching_pairs = {}
open_brackets = '({['
close_brackets = ')}]'
for i, char in enumerate(s):
if char in open_brackets:
stack.append((char, i))
elif char in close_brackets:
if not stack:
return "Dãy ngoặc không đúng"
top, index = stack.pop()
if char == ')' and top != '(' or char == '}' and top != '{' or char == ']' and top != '[':
return "Dãy ngoặc không đúng"
matching_pairs[index] = i
if stack:
return "Dãy ngoặc không đúng"
return matching_pairs
def check_valid_parentheses(s):
matching_pairs = find_matching_parentheses(s)
if isinstance(matching_pairs, str):
return matching_pairs
else:
sorted_pairs = sorted(matching_pairs.items())
return "Dãy ngoặc đúng, các cặp dấu ngoặc tương ứng là:", sorted_pairs
input_string = input("Nhập chuỗi chứa dấu ngoặc: ")
result = check_valid_parentheses(input_string)
print(result)
3. Quản lý Băng đĩa của tiệm cho thuê dĩa:
Đĩa: Tiêu đề (chuỗi)
Loại đĩa (chuỗi)
Giá cho thuê (được tính theo ngày)
Số ngày cho thuê
a/ Nhập xuất
b/ Tìm kiếm đĩa theo:
+ Tên đĩa
+ Số ngày cho thuê (những đĩa thuê hơn 1 tháng, trong vòng bao nhiêu ngày)
+ Kiểm tra giá tiền thuê dĩa X số ngày
c/ Sắp xếp: số ngày cho thuê, giá tiền thuê đĩa
d/ Chèn – Xóa

class Disk:
def __init__(self, title, genre, rental_price, rental_days):
self.title = title
self.genre = genre
self.rental_price = rental_price
self.rental_days = rental_days
class DiskStore:
def __init__(self):
self.disks = []
def add_disk(self, disk):
self.disks.append(disk)
def remove_disk(self, title):
self.disks = [disk for disk in self.disks if disk.title != title]
def find_disk_by_title(self, title):
return [disk for disk in self.disks if disk.title == title]
def find_disks_by_rental_days(self, days):
return [disk for disk in self.disks if disk.rental_days > days]
def calculate_rental_cost(self, title, days):
disk = self.find_disk_by_title(title)
if disk:
return disk[0].rental_price * days
else:
return None
def sort_disks_by_rental_days(self):
self.disks.sort(key=lambda x: x.rental_days)
def sort_disks_by_rental_price(self):
self.disks.sort(key=lambda x: x.rental_price)
disk_store = DiskStore()
disk1 = Disk("Đĩa 1", "Hành động", 2.5, 3)
disk2 = Disk("Đĩa 2", "Khoa học viễn tưởng", 3.0, 5)
disk3 = Disk("Đĩa 3", "Hài hước", 2.0, 7)
disk_store.add_disk(disk1)
disk_store.add_disk(disk2)
disk_store.add_disk(disk3)
print("Tìm kiếm theo tên 'Đĩa 1':", disk_store.find_disk_by_title("Đĩa 1")[0].title)
print("Tìm kiếm theo số ngày cho thuê > 4:", [disk.title for disk in
disk_store.find_disks_by_rental_days(4)])
rental_cost = disk_store.calculate_rental_cost("Đĩa 2", 7)
if rental_cost is not None:
print("Giá thuê Đĩa 2 trong 7 ngày:", rental_cost)
else:
print("Đĩa không tồn tại")
disk_store.sort_disks_by_rental_days()
print("Sắp xếp theo số ngày cho thuê:", [disk.rental_days for disk in disk_store.disks])
disk_store.sort_disks_by_rental_price()
print("Sắp xếp theo giá tiền thuê:", [disk.rental_price for disk in disk_store.disks])
disk_store.remove_disk("Đĩa 3")
print("Danh sách sau khi xóa 'Đĩa 3':", [disk.title for disk in disk_store.disks])

4. Robot hút bụi


Hãy thiết kế robot hút bụi với các tính năng sau:
- Tên thương hiệu
- Mã số sản phẩm
- Hướng di chuyển (hiện hành): Bắc, Nam, Đông, Tây
- Tiến lên n bước
- Lùi lại n bước
- Xoay trái 90 độ
- Xoay phải 90 độ
- Xoay 180 độ
- Tự động di chuyển về phía trước, nếu có chướng ngại vật thì rẽ sang bên phải, nếu bên
phải có chướng ngại vật thì rẽ sang bên trái, nếu cả hai phía phải và trái đều có chướng
ngại vật thì lùi lại một bước và tìm hướng có thể di chuyển theo nguyên tắc trên. Không
ràng buộc lộ trình di chuyển của robot hút bụi.
- Hút bụi trên lộ trình di chuyển.
Robot hút bụi có chế độ tự kiểm tra nguồn điện còn bao nhiêu %. Robot sẽ di chuyển cho
đến khi gần hết nguồn điện thì phát tín hiệu thông báo (khi nguồn điện còn 15%, 10%,
5%).
Sau mỗi bước, in ra sơ đồ phòng và vị trí hiện hành của robot (không bắt buộc thiết kế
giao diên đồ họa). ↑ : Robot (hướng Bắc)

import random
class RobotHutBui:
def __init__(self, brand, product_code):
self.brand = brand
self.product_code = product_code
self.x = 0
self.y = 0 # Tọa độ y hiện hành
self.direction = "Bắc"
self.battery_percentage = 100
def move_forward(self, steps):
if self.direction == "Bắc":
self.y += steps
elif self.direction == "Nam":
self.y -= steps
elif self.direction == "Đông":
self.x += steps
elif self.direction == "Tây":
self.x -= steps
def move_backward(self, steps):
if self.direction == "Bắc":
self.y -= steps
elif self.direction == "Nam":
self.y += steps
elif self.direction == "Đông":
self.x -= steps
elif self.direction == "Tây":
self.x += steps
def turn_left(self):
if self.direction == "Bắc":
self.direction = "Tây"
elif self.direction == "Nam":
self.direction = "Đông"
elif self.direction == "Đông":
self.direction = "Bắc"
elif self.direction == "Tây":
self.direction = "Nam"
def turn_right(self):
if self.direction == "Bắc":
self.direction = "Đông"
elif self.direction == "Nam":
self.direction = "Tây"
elif self.direction == "Đông":
self.direction = "Nam"
elif self.direction == "Tây":
self.direction = "Bắc"
def turn_around(self):
self.turn_left()
self.turn_left()
def auto_move(self):
# Tự động di chuyển về phía trước
if random.random() < 0.9: # Không có chướng ngại vật
self.move_forward(1)
elif random.random() < 0.5: # Bên phải có chướng ngại vật
self.turn_right()
self.move_forward(1)
else: # Bên trái có chướng ngại vật
self.turn_left()
self.move_forward(1)
self.battery_percentage -= 1
if self.battery_percentage <= 15 and self.battery_percentage > 5:
print("Cảnh báo: Nguồn điện còn 15%")
elif self.battery_percentage <= 5:
print("Cảnh báo: Nguồn điện còn 5%, cần sạc nguồn điện.")
def print_room_map(self):
# Mô phỏng in ra sơ đồ phòng và vị trí hiện hành của robot
print("Sơ đồ phòng:")
for i in range(5):
for j in range(5):
if i == self.x and j == self.y:
print("↑", end=" ")
else:
print(".", end=" ")
print()
print(f"Vị trí hiện hành: ({self.x}, {self.y}), Hướng: {self.direction}")
robot = RobotHutBui("BrandX", "12345")
for _ in range(10):
robot.auto_move()
robot.print_room_map()
print("Hoàn thành.")

You might also like