检测数字中的重复项(Python)

2024-04-30 01:53:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在从事一个小项目,该项目涉及分析选票,并根据选票数量确定获胜候选人。投票制度非同寻常。例如,如果有四名候选人,投票结果可能如下:2341(第一名候选人2名,第二名候选人3名,以此类推)。但是,如果投票结果是这样的:2334无效,同一数字不能在投票中使用两次。 我想知道是否有一种方法可以检查一个数字中是否有重复的数字。我已经有了一个解决方案,但是它并不适用于我所有的测试用例

当前代码:

voteListString = ['2314', '4432', '4312', '1243', '1234', '2431'] # 4432 should get removed (it doesn't)
for i, voteString in enumerate(voteListString):
        newI = i+1
        duplicateCheck = voteString.count(f"{newI}")
        if duplicateCheck > 1:
            voteInt = int(voteString)
            voteList.remove(f"{voteInt}")
            spoiltBallots += 1
        else:
            validVoteList.append(voteString)

上面的代码是一个for循环,它在已转换为字符串的投票列表中循环。然后计算“i”在投票中出现的次数,如果出现不止一次,它会将其从列表中删除。这只适用于我的一个测试用例。如果有更好的方法,我会非常感谢你的帮助。 提前谢谢


Tags: 项目方法代码列表for测试用例数字投票
3条回答

如果我正确理解了您的问题,您可以像这样使用set

   def check_duplicates(voteString):
      if len(set(voteString)) != len(voteString):
          print(f"there is (are) duplicate(s) in {voteString }")
      else:
          print(f"there is (are) no duplicate(s) in {voteString }")

检查:

check_duplicates('2341')
check_duplicates('2334')

there is (are) no duplicate(s) in 2341

there is (are) duplicate(s) in 2334

使用set

def is_valid(vote):
    return len(set(vote)) == len(vote)

print(is_valid('4432')) # False
print(is_valid('1234')) # True

voteListString = ['2314', '4432', '4312', '1243', '1234', '2431']

new_vote_list_string = list(filter(is_valid, voteListString))

print(new_vote_list_string)
['2314', '4312', '1243', '1234', '2431']

使用集合如何:

voteListString = ['2314', '4432', '4312', '1243', '1234', '2431'] 
spoiltBallots = 0
validVoteList = []
for v in voteListString:
    s = set(v)
    if (len(s)<4):
        spoiltBallots += 1
    else:
        validVoteList.append(v)

相关问题 更多 >