欢迎访问宙启技术站
智能推送

用Python编写一个简单的投票系统

发布时间:2023-12-04 09:22:49

以下是一个简单的投票系统的Python代码:

class Candidate:
    def __init__(self, name):
        self.name = name
        self.votes = 0

    def add_vote(self):
        self.votes += 1

class VotingSystem:
    def __init__(self):
        self.candidates = []

    def add_candidate(self, name):
        candidate = Candidate(name)
        self.candidates.append(candidate)

    def vote(self, candidate_name):
        for candidate in self.candidates:
            if candidate.name == candidate_name:
                candidate.add_vote()
                return
        print("Candidate not found!")

    def get_results(self):
        self.candidates.sort(key=lambda x: x.votes, reverse=True)
        for candidate in self.candidates:
            print(f"{candidate.name}: {candidate.votes} votes")

# 使用例子
voting_system = VotingSystem()
voting_system.add_candidate("John")
voting_system.add_candidate("Emily")
voting_system.add_candidate("Michael")

voting_system.vote("John")
voting_system.vote("John")
voting_system.vote("Emily")
voting_system.vote("Michael")
voting_system.vote("Emily")
voting_system.vote("Michael")

voting_system.get_results()

在这个投票系统中,我们有两个类:Candidate(候选人)和VotingSystem(投票系统)。Candidate类表示一个候选人,它有一个名称和一个表示已获取选票数的变量。VotingSystem类是一个管理所有候选人和投票过程的类。

一个投票系统可以通过添加候选人来进行初始化。每次有人投票给某个候选人时,我们通过vote方法将选票添加给候选人。如果候选人不存在,会显示错误信息。get_results方法将打印出所有候选人的得票结果,按照得票数排序。

在使用例子中,我们首先创建了一个投票系统,然后添加了三个候选人(John,Emily,Michael)。接着进行了一系列的投票,最后打印出了结果。

这个投票系统是简单的,只适用于少量候选人和用户,基本满足小规模投票需求。如果需要更复杂的功能,如防止重复投票、用户身份验证等,可以进行改进。