编写程序模拟投票选举,选举规则如下:
一个最多自由选举三个候选人(假设每个人的姓名不同),候选人没有限定范围。
要求使用线性表记录所有候选人的得票信息,自己定义每一个选民如何投票,如何投票结束,投票结束后输出所有候选人名单及得票个数。
程序设计要求:
首先定义适合要求的抽象数据类型——线性表
然后使用基于抽象数据类型线性表写出模拟程序的算法
最后使用某种编程语言实现程序。
使用线性表(List)来记录选民的投票信息和候选人的得票数。以下是一个Python语言的实现示例:
class LinearList:
def __init__(self):
self.elements = []
def add(self, item):
self.elements.append(item)
def remove(self, item):
self.elements.remove(item)
def count(self, item):
return self.elements.count(item)
def show_all(self):
for item in self.elements:
print(item)
def main():
candidates = LinearList() # 候选人线性表
candidates.add("候选人A") # 添加候选人A
candidates.add("候选人B") # 添加候选人B
candidates.add("候选人C") # 添加候选人C
voters = LinearList() # 选民线性表
voters.add("选民1") # 添加选民1
voters.add("选民2") # 添加选民2
voters.add("选民3") # 添加选民3
votes = LinearList() # 投票结果线性表
while True:
print("请输入选民的投票信息(输入 q 结束投票):")
voter_name = input("选民姓名:")
if voter_name == "q":
break
candidate_name = input("候选人姓名:")
if candidate_name not in candidates.elements:
print("候选人不存在,请重新输入。")
continue
vote_info = (voter_name, candidate_name)
votes.add(vote_info)
print("投票结束,所有候选人名单及得票个数如下:")
for candidate in candidates.elements:
vote_count = votes.count(candidate)
print("候选人:{},得票数:{}".format(candidate, vote_count))
if __name__ == "__main__":
main()
使用上述代码,您可以模拟投票选举过程。首先,您需要定义一个适合存储候选人和选民信息的线性表,这里我们定义了LinearList类。然后,在主函数main()中创建候选人线性表、选民线性表和投票结果线性表。接下来,通过一个循环让选民输入投票信息,直到选民输入"q"结束投票。最后,输出所有候选人的得票情况。