-北京出租车的车费算法﹣基本算法
·收费方法如下:
。车价=起步价【13元】(里程数<3)
。车价=起步价『13元】+(里程数-起步里程数『3公里】)*每公里单价【2.3元】(里程数<10)
·车价=起步价【13元】+(远程里程标准【10公里】-起步里程数【3公里】)*每公里单价+(里程数-远程里程标准【10】)*远程每公里单价【3.2元】(里程数>10)
·燃油附加费标准调整为每运次1元。
要求
·1、可以通过文件读取完成必须的输入
2、对输入进行处理,并将结果输出显示
3、具备容错能力,可以接收错误的输入
4、可以保存输入的记录,并可以查询和显示
·5、使用函数完成具有一定复杂度的算法的实现
看这样合适不,
1.首先定义一个calculate_taxi_fare函数来计算车费,根据输入的里程数,按照题目给出的收费方法进行计算,并返回总费用。
2.然后,read_input_from_file函数用于从文件中读取输入,并将输入处理为浮点数的列表。
3.save_input_to_file函数用于将输入的里程数保存到文件中。
4.display_records函数用于显示保存的记录,计算并输出每条记录的车费。
5.main函数中,通过一个循环实现交互式的菜单选项,用户可以选择输入里程并计算车费,显示保存的记录,或退出程序。根据用户的选择,调用相应的函数完成相应的操作。
6.代码中假设输入的文件是一个CSV文件,每行一个里程数,以逗号分隔。你可以根据实际需求调整代码来适应不同的输入文件格式。记录文件的路径在代码中被硬编码为taxi_records.csv,你可以根据需要修改为适当的文件路径。
import csv
def calculate_taxi_fare(distance):
base_fare = 13.0
start_distance = 3.0
per_km_fare = 2.3
long_distance_start = 10.0
long_distance_per_km_fare = 3.2
fuel_surcharge = 1.0
if distance < start_distance:
total_fare = base_fare
elif distance < long_distance_start:
total_fare = base_fare + (distance - start_distance) * per_km_fare
else:
total_fare = base_fare + (long_distance_start - start_distance) * per_km_fare + \
(distance - long_distance_start) * long_distance_per_km_fare
total_fare += fuel_surcharge
return total_fare
def read_input_from_file(file_path):
try:
with open(file_path, 'r') as file:
reader = csv.reader(file)
inputs = []
for row in reader:
if len(row) > 0:
distance = float(row[0])
inputs.append(distance)
return inputs
except FileNotFoundError:
print("文件未找到")
except ValueError:
print("无效的输入")
def save_input_to_file(file_path, distance):
try:
with open(file_path, 'a') as file:
writer = csv.writer(file)
writer.writerow([distance])
print("记录已保存")
except FileNotFoundError:
print("文件未找到")
def display_records(file_path):
try:
with open(file_path, 'r') as file:
reader = csv.reader(file)
for row in reader:
if len(row) > 0:
distance = float(row[0])
fare = calculate_taxi_fare(distance)
print(f"里程:{distance}公里,费用:{fare}元")
except FileNotFoundError:
print("文件未找到")
def main():
file_path = "taxi_records.csv"
while True:
print("1. 输入里程并计算车费")
print("2. 显示保存的记录")
print("3. 退出")
choice = input("请选择操作:")
if choice == "1":
distance = float(input("请输入里程数(公里):"))
fare = calculate_taxi_fare(distance)
print(f"车费:{fare}元")
save_input_to_file(file_path, distance)
elif choice == "2":
display_records(file_path)
elif choice == "3":
break
else:
print("无效的选择")
if __name__ == "__main__":
main()
import datetime
def calculate_taxi_fare(distance):
base_fare = 13
start_distance = 3
per_km_fare = 2.3
long_distance_fare = 3.2
long_distance_threshold = 10
fuel_surcharge = 1
if distance < start_distance:
fare = base_fare
elif distance < long_distance_threshold:
fare = base_fare + (distance - start_distance) * per_km_fare
else:
fare = base_fare + (long_distance_threshold - start_distance) * per_km_fare + (distance - long_distance_threshold) * long_distance_fare
fare += fuel_surcharge
return fare
def save_record(distance, fare):
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
record = f"Distance: {distance} km, Fare: {fare} yuan, Timestamp: {timestamp}\n"
with open("taxi_records.txt", "a") as file:
file.write(record)
def display_records():
with open("taxi_records.txt", "r") as file:
records = file.read()
print(records)
distance = float(input("请输入里程数(公里):"))
if distance < 0:
print("错误的输入!里程数不能为负数。")
return
fare = calculate_taxi_fare(distance)
print(f"车费:{fare} 元")
save_record(distance, fare)
display_records()
import datetime
# 车费计算函数
def calculate_taxi_fee(distance):
start_distance = 3 # 起步里程
start_fee = 13 # 起步价
per_km_price = 2.3 # 每公里单价
long_distance_start = 10 # 远程起步里程
long_distance_per_km_price = 3.2 # 远程每公里单价
fuel_surcharge = 1 # 燃油附加费
if distance < start_distance:
taxi_fee = start_fee
elif distance < long_distance_start:
taxi_fee = start_fee + (distance - start_distance) * per_km_price
else:
taxi_fee = start_fee + (long_distance_start - start_distance) * per_km_price + (distance - long_distance_start) * long_distance_per_km_price
taxi_fee += fuel_surcharge
return taxi_fee
# 保存输入记录
def save_input_record(distance, taxi_fee):
current_time = datetime.datetime.now()
record = f"{current_time}: 里程数:{distance}公里,车费:{taxi_fee}元\n"
with open("input_records.txt", "a") as file:
file.write(record)
# 查询和显示输入记录
def display_input_records():
with open("input_records.txt", "r") as file:
records = file.readlines()
for record in records:
print(record)
# 从文件读取输入并进行处理
def process_input_from_file(file_path):
try:
with open(file_path, "r") as file:
lines = file.readlines()
for line in lines:
distance = float(line.strip())
taxi_fee = calculate_taxi_fee(distance)
print(f"里程数:{distance}公里,车费:{taxi_fee}元")
save_input_record(distance, taxi_fee)
except FileNotFoundError:
print("文件不存在!")
# 处理用户输入
def process_user_input():
while True:
distance_input = input("请输入里程数(公里),输入q退出:")
if distance_input.lower() == "q":
break
try:
distance = float(distance_input)
taxi_fee = calculate_taxi_fee(distance)
print(f"里程数:{distance}公里,车费:{taxi_fee}元")
save_input_record(distance, taxi_fee)
except ValueError:
print("输入无效!请重新输入。")
# 主函数
def main():
while True:
option = input("请选择操作:\n1. 从文件读取输入并进行处理\n2. 处理用户输入\n3. 查询和显示输入记录\n4. 退出\n")
if option == "1":
file_path = input("请输入文件路径:")
process_input_from_file(file_path)
elif option == "2":
process_user_input()
elif option == "3":
display_input_records()
elif option == "4":
break
else:
print("无效的选项!请重新输入。")
if __name__ == "__main__":
main()
参考实例:https://peakchen.blog.csdn.net/article/details/131538216?spm=1001.2014.3001.5502
py实现出租车导航及计费
import random as r
# 记录查询历史
class TextRecord(object):
def __init__(self):
self.filepath = '查询记录文本文件.txt'
# 记录查询记录
def record(self, text):
with open(self.filepath, 'a+', encoding='utf-8') as file:
file.write(text)
# 记录输出
def recordShow(self):
try:
with open(self.filepath, 'r', encoding='utf-8') as file:
text = file.read()
print(text)
except:
print("暂无查询记录!")
# 定义Path类
class Path(object):
def __init__(self, path, distancecost, timecost):
self.__path = path
self.__distancecost = distancecost
self.__timecost = timecost
# 路径上最后一个节点
def getLastNode(self):
return self.__path[-1]
# 判断node是否为路径上最后一个节点
def isLastNode(self, node):
return node == self.getLastNode()
# 增加加点和成本产生一个新的path对象
def addNode(self, node, dprice, tprice):
return Path(self.__path + [node], self.__distancecost + dprice, self.__timecost + tprice)
self.__timecost = self.__timecost + price
return Path(self.__path + [node], self.__distancecost, self.__timecost)
# 输出当前路径
def printPath(self):
for n in self.__path:
if self.isLastNode(n):
print(n)
else:
print(n, end="->")
print(f"最短路径距离{self.__distancecost:.2f}km")
print(f"红绿灯个数 {self.__timecost:.0f}个")
self.text = f"最短路径距离{self.__distancecost:.2f}km\n红绿灯个数 {self.__timecost:.0f}个\n"
@property
def dcost(self):
return self.__distancecost
@property
def tcost(self):
return self.__timecost
# 获取路径路径
@property
def path(self):
return self.__path
# 获取路径总成本的只读属性
@property
def travelCost(self):
return self.__distancecost
# 定义DirectedGraph类
class DirectedGraph(object):
def __init__(self, d):
if isinstance(d, dict):
self.__graph = d
self.recorder = TextRecord()
else:
self.__graph = dict()
print('数据读取错误!请查看数据格式是否正确。')
# 通过递归生成所有可能的路径
def __generatePath(self, graph, path, end, results, costIndex):
current = path.getLastNode()
if current == end:
results.append(path)
else:
for n in graph[current]:
if n not in path.path:
self.__generatePath(graph
, path.addNode(n, self.__graph[path.getLastNode()][n][0]
, self.__graph[path.getLastNode()][n][1])
, end
, results
, costIndex)
# 计算价格部分
def calculate_price(self, distance, trafic_lights_number, base_price=13, start_distance=3, long_distance=10,
long_distance_price=3.2,
short_distance_price=2.3, fuel_surcharge=1): # 根据距离计算车费
total_price = 0
dis_price = 0 # 里程收费
tim_price = 0 # 等待时间收费
wait_time = 0
for i in range(trafic_lights_number):
red_light = 1 * r.randint(0, 1)
wait_time += red_light * r.randint(1, 60)
self.timecost = wait_time / 60
wait_time = wait_time / 300 # 模拟红绿灯等待时间换算成等效里程
# 里程收费
if distance <= start_distance: # 短途车程
dis_price += base_price
elif start_distance < distance <= long_distance:
dis_price += base_price + (distance - start_distance) * short_distance_price # 常规车程
else:
dis_price += base_price + (long_distance - start_distance) * short_distance_price + (
distance - long_distance) * long_distance_price
# 红绿灯等待时间换算成等效里程收费
if 1 <= wait_time <= start_distance:
tim_price += base_price
elif start_distance < wait_time <= long_distance:
tim_price += base_price + (wait_time - start_distance) * short_distance_price # 常规车程
elif wait_time > long_distance:
tim_price += base_price + (long_distance - start_distance) * short_distance_price + (
wait_time - long_distance) * long_distance_price
# 加上燃油费
total_price += dis_price + tim_price + fuel_surcharge
return dis_price, tim_price, total_price
# 搜索start到end之间时间或空间最短的路径,并输出
def __searchPath(self, start, end, costIndex):
results = []
self.__generatePath(self.__graph, Path([start], 0, 0), end, results, costIndex)
if costIndex == 0:
results.sort(key=lambda p: p.dcost)
elif costIndex == 1:
results.sort(key=lambda p: p.tcost)
print(f'{"最短路径" if costIndex == 0 else "最短时间路径"}'
, start, '->', end, '为:', end="")
results[0].printPath()
dis_price, tim_price, total_price = self.calculate_price(results[0].dcost, results[0].tcost)
print(
f"等待时间为{self.timecost:.2f}min\n总消费为:{total_price:.2f}元\n分别为:\n里程收费{dis_price:.2f}元,等待时长收费{tim_price:.2f}元")
text = f'{"最短路径" if costIndex == 0 else "最短时间路径"}{start}->{end}为:\n' + results[
0].text + '\n' + f"等待时间为{self.timecost:.2f}min\n总消费为:{total_price:.2f}元\n分别为:\n里程收费{dis_price:.2f}元,等待时长收费{tim_price:.2f}元\n"
self.recorder.record(text)
# 调用__searchPath搜索start到end之间的空间最短的路径,并输出
def searchSpatialMinPath(self, start, end):
self.__searchPath(start, end, 0)
# 调用__searchPath搜索start到end之间的时间最短的路径,并输出
def searchTemporalMinPath(self, start, end):
self.__searchPath(start, end, 1)
# 线路查询模块
def pathQuery(self, fname, start_node, end_node):
strs = "_" * 20
# 文件读取,数据提取
with open(fname, 'r', encoding='utf-8') as f:
# (空间距离,时间距离)
graphy_dict = eval(f.read())
# 起始点列表
print(f"{strs}请输入起始点{strs}")
i = 0
try:
for start in start_node:
print(f"{i}-{start}")
i += 1
node0 = int(input(":请输入对应序号:"))
startnode = start_node[node0]
print(f"{strs}请输入终点{strs}")
k = 0
for end in end_node:
print(f"{k}-{end}")
k += 1
node1 = int(input(":请输入对应序号:"))
endnode = end_node[node1]
# 实例化对象
g1 = DirectedGraph(graphy_dict)
print(f"{strs}{startnode}->{endnode}{strs}")
g1.searchSpatialMinPath(startnode, endnode)
print(f"{strs}{strs}")
g1.searchTemporalMinPath(startnode, endnode)
except:
print("输入错误!请重新输入")
self.pathQuery(fname, start_node, end_node)
# 记录查询
def recordQuery(self):
self.recorder.recordShow()
# 模式选择
def modeSelect(self, fname, start_node, end_node):
select = int(input("0-最短路径计费查询模式\n1-查看查询历史:"))
if select == 0:
self.pathQuery(fname, start_node, end_node)
elif select == 1:
self.recordQuery()
else:
print("输入指令错误!请重新输入")
self.modeSelect(fname, start_node, end_node)
selsect2 = int(input("0-退出程序\n1-继续执行:"))
if selsect2 == 0:
return 0
elif selsect2 == 1:
self.modeSelect(fname, start_node, end_node)
# 脚本自调试
if __name__ == '__main__':
# 有向图数据文件路径
filename = 'try.txt'
# 起始点列表
start_node = ['交大东门', '交大西门', '交大南门']
end_node = ['中国农业科学院南门', '北理工北门', '海淀公园东门', '颐和园新建宫门', '北京南站进站口', '首都机场3号航站楼']
# 打开文件
with open(filename, 'r', encoding='utf-8') as f:
dicts = eval(f.read())
# 实例化对象
test = DirectedGraph(dicts)
# 模式选择
test.modeSelect(filename, start_node, end_node)
首先要处理的问题是亮度问题,因为拍摄时间不一致导致的亮度差异可以使用灰度均衡来处理,然后进行图像相减,观察图像差异,确定哪个窗户发生了变化。
根据问题描述,可以将问题分解为以下几个步骤来实现。
下面是这些步骤的具体实现。
首先,我们可以使用Python内置的open()
函数以及with
语句来读取文件中的输入参数。以下是一个示例代码:
def read_input(filename):
with open(filename, 'r') as f:
input_str = f.readline().strip() # 读取一行并去除首尾空白字符
return input_str
接下来,我们需要对输入参数进行容错处理,确保输入参数为有效数字。如果输入参数无效,则需要给出错误提示并要求重新输入。以下是一个示例代码:
def parse_input(input_str):
try:
distance = float(input_str) # 将输入参数转换为浮点数
if distance < 0:
raise ValueError # 距离不能为负数
return distance
except ValueError:
print('输入参数无效,请重新输入有效数字。')
return None
根据题目的车费计算方法,我们可以编写一个函数来计算车费。以下是一个示例代码:
def calculate_fare(distance):
base_fare = 13 # 起步价
extra_distance_rate = 2.3 # 超出3公里后每公里单价
long_distance_rate = 3.2 # 超出10公里后每公里单价
fuel_surcharge = 1 # 燃油附加费
if distance < 3:
return base_fare + fuel_surcharge
elif distance <= 10:
return base_fare + (distance - 3) * extra_distance_rate + fuel_surcharge
else:
return base_fare + (10 - 3) * extra_distance_rate + (distance - 10) * long_distance_rate + fuel_surcharge
将计算结果输出,并保存到文件中。同时,也可以把历史记录保存在一个列表中,以供查询和显示。
def save_result(filename, distance, fare):
with open(filename, 'a') as f:
f.write(f'里程数:{distance}公里,车费:{fare}元\n')
def display_history(filename):
with open(filename, 'r') as f:
history = f.read()
print(history)
综合以上步骤,我们可以编写一个主程序来实现对出租车车费的计算。以下是一个示例代码:
def main():
input_filename = 'input.txt' # 输入参数文件名
output_filename = 'output.txt' # 输出结果文件名
history_filename = 'history.txt' # 历史记录文件名
distance_str = read_input(input_filename)
if distance_str is not None:
distance = parse_input(distance_str)
if distance is not None:
fare = calculate_fare(distance)
print(f'车费:{fare}元')
save_result(output_filename, distance, fare)
display_history(history_filename)
if __name__ == '__main__':
main()
这样,我们就完成了一个根据北京出租车车费算法的程序。通过运行主程序,可以从输入文件中读取输入参数,计算车费并将结果保存到输出文件中,同时可以查询并显示历史记录。
注意: 以上代码仅仅是示例代码,实际应用中可能需要根据具体情况做一些调整和完善。
上图
# 2023年7月4日20:39:54
#导入需要的库
import pandas as pd #用于读写excel文件
import time #用于延时
#定义一些常量,表示出租车的收费标准
STARTING_FARE = 13.0 #起步价
STARTING_DISTANCE = 3.0 #起步里程
NORMAL_PRICE = 2.3 #每公里单价
LONG_DISTANCE = 10.0 #远程里程标准
LONG_PRICE = 3.2 #远程每公里单价
FUEL_SURCHARGE = 1.0 #燃油附加费
#定义一个函数,根据里程数计算车费
def calculate_fare(distance):
#判断里程数是否小于起步里程
if distance <= STARTING_DISTANCE:
#如果是,车费等于起步价加燃油附加费
fare = STARTING_FARE + FUEL_SURCHARGE
elif distance <= LONG_DISTANCE:
#如果不是,判断里程数是否小于远程里程标准
#如果是,车费等于起步价加超出部分的单价乘以距离,再加燃油附加费
fare = STARTING_FARE + (distance - STARTING_DISTANCE) * NORMAL_PRICE + FUEL_SURCHARGE
else:
#如果不是,车费等于起步价加远程里程标准到起步里程之间的单价乘以距离,再加超出部分的单价乘以距离,再加燃油附加费
fare = STARTING_FARE + (LONG_DISTANCE - STARTING_DISTANCE) * NORMAL_PRICE + (distance - LONG_DISTANCE) * LONG_PRICE + FUEL_SURCHARGE
#返回车费
return fare
#定义一个函数,从excel文件中读取输入数据,并返回一个列表
def read_input_from_excel(file_name):
#使用pandas库读取excel文件,并获取第一列的数据,转换为列表类型,并返回
return pd.read_excel(file_name, header=None)[0].tolist()
#定义一个函数,将计算结果写入到excel文件中,并显示在控制台上
def write_output_to_excel(distance_list, file_name):
#创建一个空列表,用于存放计算结果
fare_list = []
#循环遍历距离列表中的每一个元素,并计算对应的车费
for distance in distance_list:
#调用计算车费的函数,传入距离参数,得到车费结果,并保留两位小数
fare = round(calculate_fare(distance), 2)
#将车费结果添加到车费列表中
fare_list.append(fare)
#将距离和车费格式化为字符串,并用逗号分隔,显示在控制台上,并换行
print(str(distance) + "," + str(fare))
#使用pandas库创建一个数据框对象,传入距离列表和车费列表作为数据源,并指定列名为distance和fare
df = pd.DataFrame({"distance": distance_list, "fare": fare_list})
# 使用pandas.ExcelWriter类创建一个写入器对象,并指定文件名和模式为追加模式
writer = pd.ExcelWriter(file_name, mode="a")
# 使用pandas库将数据框对象写入到excel文件中,并指定不写入索引列和表头行,以及使用写入器对象
df.to_excel(writer, index=False, header=False, sheet_name="Sheet" + str(time.time()))
# 保存写入器对象的更改,并关闭它,释放资源
writer.close()
#定义一个函数,保存输入的记录到excel文件中,并返回一个列表
def save_input_to_excel(file_name):
#创建一个空列表,用于存放用户输入的数据
input_list = []
#创建一个文件对象,根据文件名参数,并以追加模式打开
file = open(file_name, "a")
#提示用户输入里程数,以空格分隔,以回车结束
print("请输入里程数,以空格分隔,以回车结束:")
#获取用户输入的一行数据,并去除首尾空格
input_line = input().strip()
#将用户输入的数据写入到文件中,并换行
file.write(input_line + "\n")
#关闭文件对象,释放资源
file.close()
#将用户输入的数据用空格分割成一个字符串列表,并循环遍历每一个元素
for input_str in input_line.split():
#尝试将字符串转换为浮点数,并添加到输入列表中
try:
input_num = float(input_str)
input_list.append(input_num)
#如果转换失败,说明输入不合法,打印错误信息,并跳过该元素
except ValueError:
print("输入不合法:" + input_str)
continue
#返回输入列表
return input_list
#定义主函数,用于测试程序
def main():
# 定义两个常量,表示输入和输出的文件名
INPUT_FILE = "input.xlsx"
OUTPUT_FILE = "output.xlsx"
# 定义一个变量,表示输入的次数
input_count = 0
# 定义一个常量,表示最大的输入次数
MAX_COUNT = 10
# 循环输入,直到达到最大次数或用户输入空行为止
while input_count < MAX_COUNT:
# 调用保存输入的函数,传入输入文件名参数,并得到返回的列表
distance_list = save_input_to_excel(INPUT_FILE)
# 判断返回的列表是否为空,如果是,说明用户输入了空行,退出循环
if not distance_list:
break
# 调用写入输出的函数,传入距离列表和输出文件名参数
write_output_to_excel(distance_list, OUTPUT_FILE)
# 将输入次数加一
input_count += 1
#如果当前模块是主模块,调用主函数
if __name__ == "__main__":
main()
问题点: 车费算法
车价=起步价【13元】(里程数<3)
车价=起步价『13元】+(里程数-起步里程数『3公里】)*每公里单价【2.3元】(里程数<10)
车价=起步价【13元】+(远程里程标准【10公里】-起步里程数【3公里】)*每公里单价+(里程数-远程里程标准【10】)*远程每公里单价【3.2元】(里程数>10)
·燃油附加费标准调整为每运次1元。
分析思路: 车费的相关影响因子为 起步价/里程数/远程里程/燃油附加费
代码如下:
import csv
# 车费计算-里程数
def calculate_taxi_fare(distance):
base_fare = 13.0
start_distance = 3.0
per_km_fare = 2.3
long_distance_start = 10.0
long_distance_per_km_fare = 3.2
fuel_surcharge = 1.0
if distance < start_distance:
total_fare = base_fare
elif distance < long_distance_start:
total_fare = base_fare + (distance - start_distance) * per_km_fare
else:
total_fare = base_fare + (long_distance_start - start_distance) * per_km_fare + \
(distance - long_distance_start) * long_distance_per_km_fare
total_fare += fuel_surcharge
return total_fare
# 文件读取-CSV类型文件
def read_input_from_file(file_path):
try:
with open(file_path, 'r') as file:
reader = csv.reader(file)
inputs = []
for row in reader:
if len(row) > 0:
distance = float(row[0])
inputs.append(distance)
return inputs
except FileNotFoundError:
print("文件未找到")
except ValueError:
print("无效的输入")
# 文件保存-CSV文件
def save_input_to_file(file_path, distance):
try:
with open(file_path, 'a') as file:
writer = csv.writer(file)
writer.writerow([distance])
print("记录已保存")
except FileNotFoundError:
print("文件未找到")
# 打印文件信息
def display_records(file_path):
try:
with open(file_path, 'r') as file:
reader = csv.reader(file)
for row in reader:
if len(row) > 0:
distance = float(row[0])
fare = calculate_taxi_fare(distance)
print(f"里程:{distance}公里,费用:{fare}元")
except FileNotFoundError:
print("文件未找到")
# 主函数
def main():
file_path = "taxi_records.csv"
while True:
print("1. 输入里程并计算车费")
print("2. 显示保存的记录")
print("3. 退出")
choice = input("请选择操作:")
if choice == "1":
distance = float(input("请输入里程数(公里):"))
fare = calculate_taxi_fare(distance)
print(f"车费:{fare}元")
save_input_to_file(file_path, distance)
elif choice == "2":
display_records(file_path)
elif choice == "3":
break
else:
print("无效的选择")
if __name__ == "__main__":
main()
****以下是基于给定算法的北京出租车车费计算的Python代码实现:
import os
def calculate_taxi_fare(distance):
base_fare = 13
start_distance = 3
per_km_fare = 2.3
long_distance_fare = 3.2
long_distance_threshold = 10
fuel_surcharge = 1
if distance < start_distance:
fare = base_fare
elif distance < long_distance_threshold:
fare = base_fare + per_km_fare * (distance - start_distance)
else:
fare = base_fare + per_km_fare * (long_distance_threshold - start_distance) + long_distance_fare * (distance - long_distance_threshold)
return fare + fuel_surcharge
def read_input_file(file_path):
if not os.path.exists(file_path):
print("File does not exist.")
return None
with open(file_path, 'r') as file:
lines = file.readlines()
distances = [float(line.strip()) for line in lines]
return distances
def save_records(file_path, records):
with open(file_path, 'w') as file:
for record in records:
file.write(str(record) + '\n')
def load_records(file_path):
if not os.path.exists(file_path):
print("Record file does not exist.")
return None
with open(file_path, 'r') as file:
lines = file.readlines()
records = [float(line.strip()) for line in lines]
return records
def display_records(records):
print("Taxi fare records:")
for i, record in enumerate(records):
print(f"Record {i+1}: {record} yuan")
def main():
input_file = "input.txt"
record_file = "records.txt"
distances = read_input_file(input_file)
if distances is None:
return
fares = [calculate_taxi_fare(distance) for distance in distances]
save_records(record_file, fares)
display_records(fares)
records = load_records(record_file)
if records is not None:
display_records(records)
if __name__ == "__main__":
main()
请将上述代码保存为一个Python文件(例如taxi_fare_calculator.py
),并将输入的距离数据保存在名为input.txt
的文件中(每行一个距离)。运行代码后,程序将计算并显示出租车费用,并将结果保存在名为records.txt
的文件中。程序还提供了查询和显示保存的记录的功能。