上传文件至「/」

This commit is contained in:
2026-05-22 16:09:14 +08:00
parent e28face0b6
commit cf648f6bf9
3 changed files with 470 additions and 223 deletions
+208 -140
View File
@@ -1,140 +1,208 @@
from house.db_operation import read_houses, write_houses
def get_next_house_id():
"""
生成下一个房源ID(保证ID唯一)
时间复杂度:O(n)(遍历所有房源找最大ID)
return: 下一个可用的ID(整数)
"""
houses = read_houses()
if not houses:
return 1 # 无房源时,第一个ID为1
# 找到最大ID,加1作为新ID
max_id = max(house["id"] for house in houses)
return max_id + 1
def add_house(address, price, area, house_type):
"""
新增房源(线性表的尾部插入操作)
时间复杂度:O(n)read/write各O(n),整体O(n)
空间复杂度:O(n)(存储所有房源数据)
param address: 房源地址(字符串)
param price: 租金(整数/浮点数)
param area: 面积(整数/浮点数)
param house_type: 户型(字符串,如"一居室"
return: 新增成功返回True,失败返回False
"""
# 基础数据校验(非空+数值合法性)
if not address or not house_type:
print("错误:地址和户型不能为空!")
return False
if not isinstance(price, (int, float)) or price <= 0:
print("错误:租金必须是正数!")
return False
if not isinstance(area, (int, float)) or area <= 0:
print("错误:面积必须是正数!")
return False
# 构建新房源字典(线性表的元素)
new_house = {
"id": get_next_house_id(),
"address": address,
"price": price,
"area": area,
"house_type": house_type
}
# 读取现有房源(线性表),新增元素(尾部插入)
houses = read_houses()
houses.append(new_house) # 线性表append操作,时间复杂度O(1)
# 写入文件
write_houses(houses)
print(f"房源新增成功!房源ID{new_house['id']}")
return True
def delete_house(house_id):
"""
删除房源(线性表的指定位置删除操作)
时间复杂度:O(n)(遍历找ID+写入文件,整体O(n))
空间复杂度:O(n)(存储所有房源数据)
param house_id: 要删除的房源ID(整数)
return: 删除成功返回True,失败返回False
"""
houses = read_houses()
# 遍历线性表,找到对应ID的房源
for index, house in enumerate(houses):
if house["id"] == house_id:
del houses[index] # 线性表删除操作,时间复杂度O(n)(后续元素前移)
write_houses(houses)
print(f"房源ID {house_id} 删除成功!")
return True
print(f"错误:未找到房源ID {house_id}")
return False
def update_house(house_id, new_info):
"""
修改房源信息(线性表的指定元素更新操作)
时间复杂度:O(n)(遍历找ID+写入文件,整体O(n))
空间复杂度:O(n)(存储所有房源数据)
param house_id: 要修改的房源ID(整数)
param new_info: 要修改的字段字典(如{"price": 5500, "area": 85}
return: 修改成功返回True,失败返回False
"""
houses = read_houses()
# 遍历线性表,找到对应ID的房源
for house in houses:
if house["id"] == house_id:
# 仅更新传入的有效字段
for key, value in new_info.items():
if key in ["address", "price", "area", "house_type"]:
# 校验数值字段合法性
if key in ["price", "area"]:
if not isinstance(value, (int, float)) or value <= 0:
print(f"错误:{key}必须是正数!")
return False
house[key] = value
write_houses(houses)
print(f"房源ID {house_id} 修改成功!")
return True
print(f"错误:未找到房源ID {house_id}")
return False
def query_house(condition_type, condition_value):
"""
查询房源(线性表的遍历筛选操作)
时间复杂度:O(n)(遍历所有房源,n为房源数)
空间复杂度:O(k)(k为符合条件的房源数,最坏O(n))
param condition_type: 查询条件类型("id"/"address"/"price"/"house_type"
param condition_value: 查询条件值
return: 符合条件的房源列表
"""
houses = read_houses()
result = []
# 按条件遍历筛选
for house in houses:
# 处理ID查询(整数匹配)
if condition_type == "id":
if house["id"] == int(condition_value):
result.append(house)
# 处理地址查询(模糊匹配)
elif condition_type == "address":
if condition_value in house["address"]:
result.append(house)
# 处理户型查询(精确匹配)
elif condition_type == "house_type":
if house["house_type"] == condition_value:
result.append(house)
# 处理租金查询(数值匹配,示例:查询等于该价格的房源)
elif condition_type == "price":
if house["price"] == float(condition_value):
result.append(house)
else:
print("错误:不支持的查询条件类型!")
return []
return result
from house_operation import *
from datetime import datetime
def get_next_house_id():
houses = read_houses()
if not houses:
return 1
max_id = max(house["id"] for house in houses)
return max_id + 1
def add_house(address, price, area, house_type):
if not address or not house_type:
print("错误:地址和户型不能为空!")
return False
if not isinstance(price, (int, float)) or price <= 0:
print("错误:租金必须是正数!")
return False
if not isinstance(area, (int, float)) or area <= 0:
print("错误:面积必须是正数!")
return False
new_house = {
"id": get_next_house_id(),
"address": address,
"price": price,
"area": area,
"house_type": house_type
}
houses = read_houses()
houses.append(new_house)
write_houses(houses)
print(f"房源新增成功!房源ID{new_house['id']}")
return True
def delete_house(house_id):
houses = read_houses()
for index, house in enumerate(houses):
if house["id"] == house_id:
del houses[index]
write_houses(houses)
print(f"房源ID {house_id} 删除成功!")
return True
print(f"错误:未找到房源ID {house_id}")
return False
def update_house(house_id, new_info):
houses = read_houses()
for house in houses:
if house["id"] == house_id:
for key, value in new_info.items():
if key in ["address", "price", "area", "house_type"]:
if key in ["price", "area"]:
if not isinstance(value, (int, float)) or value <= 0:
print(f"错误:{key}必须是正数!")
return False
house[key] = value
write_houses(houses)
print(f"房源ID {house_id} 修改成功!")
return True
print(f"错误:未找到房源ID {house_id}")
return False
def query_house(condition_type, condition_value):
houses = read_houses()
result = []
for house in houses:
if condition_type == "id":
if house["id"] == int(condition_value):
result.append(house)
elif condition_type == "address":
if condition_value in house["address"]:
result.append(house)
elif condition_type == "house_type":
if house["house_type"] == condition_value:
result.append(house)
elif condition_type == "price":
if house["price"] == float(condition_value):
result.append(house)
else:
print("错误:不支持的查询条件类型!")
return []
return result
MAX_STACK_LENGTH = 100
def push_operation_stack(operation_info):
time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
full_info = f"[{time_str}] {operation_info}"
stack = read_stack("operation")
stack.append(full_info)
if len(stack) > MAX_STACK_LENGTH:
stack.pop(0)
write_stack("operation", stack)
def push_browse_stack(house_id):
stack = read_stack("browse")
if stack and stack[-1] == house_id:
return
stack.append(house_id)
if len(stack) > MAX_STACK_LENGTH:
stack.pop(0)
write_stack("browse", stack)
def pop_operation_stack():
stack = read_stack("operation")
if not stack:
return None
latest_op = stack.pop()
write_stack("operation", stack)
return latest_op
def pop_browse_stack():
stack = read_stack("browse")
if not stack:
return None
latest_hid = stack.pop()
write_stack("browse", stack)
return latest_hid
def get_recent_records(stack_type, limit=10):
stack = read_stack(stack_type)
return stack[-limit:][::-1]
def clear_stack(stack_type):
write_stack(stack_type, [])
print(f"{stack_type}记录已清空!")
def parse_address_string(full_address):
# 字符串分割(串操作核心)
parts = full_address.split("")
province_city = parts[0] + "" if "" in full_address else parts[0]
if "" in province_city:
province, city = province_city.split("")
province += ""
city += ""
else:
province = "未知省份"
city = province_city
# 继续拆分区县
if len(parts) > 1:
district_part = parts[1]
if "" in district_part or "" in district_part:
district, community = district_part.split("") if "" in district_part else district_part.split("")
district += "" if "" in district_part else ""
else:
district = "未知区县"
community = district_part
else:
district = "未知区县"
community = "未知小区"
return {
"province": province,
"city": city,
"district": district,
"community": community
}
def fuzzy_query_by_district(keyword):
houses = read_houses()
result = []
for house in houses:
addr_info = parse_address_string(house["address"])
# 字符串包含匹配
if keyword in addr_info["district"] or keyword in addr_info["community"]:
result.append(house)
return result
def init_community_matrix(community_name_list):
"""
【V3.0新增 二维数组知识点:邻接矩阵初始化】
根据小区列表生成距离邻接矩阵,初始化距离为无穷大,自己到自己为0
时间复杂度:O(N²),N为小区数量
空间复杂度:O(N²)
"""
INF = float("inf")
n = len(community_name_list)
# 二维数组初始化(邻接矩阵)
distance_matrix = [[INF]*n for _ in range(n)]
for i in range(n):
distance_matrix[i][i] = 0 # 自己到自己距离为0
# 保存到数据文件
matrix_data = {
"community_list": community_name_list,
"distance_matrix": distance_matrix
}
write_matrix_data(matrix_data)
print("邻接矩阵初始化完成!")
def update_matrix_distance(community_a, community_b, distance):
matrix_data = read_matrix_data()
community_list = matrix_data["community_list"]
distance_matrix = matrix_data["distance_matrix"]
try:
idx_a = community_list.index(community_a)
idx_b = community_list.index(community_b)
distance_matrix[idx_a][idx_b] = distance
distance_matrix[idx_b][idx_a] = distance
write_matrix_data(matrix_data)
print(f"{community_a} <-> {community_b} 距离更新成功!")
except ValueError:
print("小区名称不存在!")