【问题标题】:Saving a value, removing it and then running again with the rest of a list保存一个值,删除它,然后使用列表的其余部分再次运行
【发布时间】:2021-04-12 06:09:01
【问题描述】:

问题描述

我首先有一个值列表,例如:

(1,2,3,1,3,2,2,2,1)

我想要实现的是:

  1. 找到最常见的一个(工作)。
  2. 从列表中删除它(工作)。
  3. 对列表中的其余值重复相同的操作。

例如

采用这个元组:

(1,2,3,1,3,2,2,2,1) 

存储 2 是最常见的 int,然后

(1,3,3,1,1,)

存储 1 是 second 最常见的 int,然后

(3,3) 

存储 2 是 第三个最常见的 int,然后


我的源代码

请注意,self.final_votes 将是 (1,2,3,1,3,2,2,2,1)

def erase_common(self):
        possitions = []
        counter = 0
        common = self.final_votes[0] 
      
        
        for i in self.final_votes:
            cand_freq = self.final_votes.count(i) 
            if(cand_freq> counter): 
                counter = cand_freq
                common = i
        
         possitions.append(common)
         while common in self.final_votes:
         self.final_votes.remove(common)    

这是整个代码

class voting_system:
    def __init__(self):
        #self.tutor_group = self.get_tutor_group()
        self.stud_num = self.get_stud_num()
        self.cand_num = self.get_cand_num()
        self.cand_name = self.get_cand_name()
        self.final_votes = self.ind_votes()
        self.erase_common()
        
#     def get_tutor_group(self):
#         tutor_groups = ("7A","7B","7C","7D","7E","7F","8A","8B","8C","8D","8E","8F","9A","9B","9C","9D","9E","9E",
#                     "9F","10A","10B","10C","10D","10E","10F","11A","11B","11C","11D","11E","11F")
# 
#         flag = True
#         while flag == True:
#             try:
#                 self.tutor_group = input("please enter the tutor group: ")
#                 if self.tutor_group not in tutor_groups:
#                     raise ValueError("Tutor group entred doesn't exist")
#             except ValueError as error:
#                 print(error)
#                 flag = True
#                     
#             else:
#                 flag = False
        
#        return self.tutor_group
        
    def get_stud_num(self):
#         flag = True
#         while flag == True:
#             try:
#                 self.stud_num = int(input("Please enter number of students: "))
#                 if self.stud_num<0 or self.stud_num>35:
#                     raise ValueError("NUMBER OF STUDENTS INVALID")
#             except ValueError as error:
#                 print(error)
#                 flag = True
#                 
#             else:
#                 flag = False
        self.stud_num = 7
        return self.stud_num
        
            
    def get_cand_num(self):
#         flag = True
#         while flag == True:
#             try:
#                 self.cand_num = int(input("Please enter number of candidates: "))
#                 if self.cand_num>4:
#                     raise ValueError("NUMBER OF CANDIDATES INVALID")
#             except ValueError as error:
#                 print(error)
#                 flag = True
#                 
#             else:
#                 flag = False
        self.cand_num = 3
        return self.cand_num
        
    
    def get_cand_name(self):
        self.cand_name = []
        for i in range(self.cand_num):
            candidate = input("Enter candidate name: ")
            self.cand_name.append(candidate)
        return self.cand_name
    
    def print_cands(self):
        for i in range(len(self.cand_name)):
            print(i+1, " : ", self.cand_name[i])
            
            
    def ind_votes(self):
        self.final_votes = []
        self.print_cands()
        abs_vote = 0
        
        flag = True
        while flag == True:
            try:
                for i in range(self.stud_num): 
                    vote = input("To vote type 'V' and the candidates number, to abstent type 'A': ")
                    if vote.isalpha() == True:
                        abs_vote +=1
                    else:
                        self.final_votes.append(vote[1])
            
                    if vote[1] > str(self.cand_num):
                        raise ValueError("VOTED CANDIDATE NONEXISTENT")
            except ValueError as error:
                print(error)
                flag = True
            else:
                flag = False
               
                
        return self.final_votes
        return abs_vote

    def erase_common(self):
        possitions = []
        counter = 0
        common = self.final_votes[0] 
      
        
        for i in self.final_votes:
            cand_freq = self.final_votes.count(i) 
            if(cand_freq> counter): 
                counter = cand_freq
                common = i
        
         possitions.append(common)
         while common in self.final_votes:
         self.final_votes.remove(common)            
        
        
                    
run = voting_system()

任何建议将不胜感激:)

【问题讨论】:

  • 您的邮政编码不完整-似乎您写了class-self.final_votes 猜测?你能发布完整的代码吗?重复检查的ending condition 是什么 - 例如。直到最后一个数字是n count?
  • 一旦列表中没有更多元素,该功能应该停止,我将发布代码:)。
  • 如果是这样 - 那么这个程序的目标是什么?只是锻炼? No more elements in the list == empty list?错过这里的重点......
  • 这是一个考试作业,它的basicallz负责决定一个班级投票的获胜者,这部分用候选人的名字找到最大的票数,删除它,再为其他人做一次跨度>
  • 因为候选人的数量是可变的,我不能硬编码它

标签: python-3.x algorithm sorting tuples


【解决方案1】:

更简单,可能是最好的:

集合中的用户 Python 计数器。

from collections import Counter


final_votes = [1, 2, 3, 1, 3, 2, 2, 2, 1]

def erase_common(votes):
    count_votes = Counter(votes)
    return count_votes.most_common()

print(erase_common(final_votes)) # [(2, 4), (1, 3), (3, 2)]
votes = erase_common(final_votes)
for idx, votes in enumerate(votes):
    print(f'{idx+1}) Vote {votes[0]} Total = {votes[1]}')

输出

1) Vote 2 Total = 4
2) Vote 1 Total = 3
3) Vote 3 Total = 2

使用 groupby

​​>

@AlexMartelli 对于查找列表中最常见的元素有一个非常好的答案 --> Find the most common element in a list

所以你可以这样做:

from itertools import groupby


final_votes = [1, 2, 3, 1, 3, 2, 2, 2, 1]

def most_common_oneliner(L):
    grupped = groupby(sorted(L))
    result = {group: len([*scores]) for group, scores in grupped}
    final_sorted_votes = []
    while result:
        max = [(0, 0)]
        for score, res in result.items():
            if max[0][1] < res:
                max[0] = (score, res)
        del result[max[0][0]]
        final_sorted_votes += max

    return final_sorted_votes


result = most_common_oneliner(final_votes)

for idx, votes in enumerate(result):
    print(f'{idx+1}) Vote {votes[0]} Total = {votes[1]}')

文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 2013-11-04
    • 2019-03-15
    相关资源
    最近更新 更多