Let's learn from each other!

博主尝试将记事本中的文字剪切并粘贴到博客中保存,但在操作过程中不慎用其他内容覆盖了剪切板里的原始信息。本文探讨了如何找回被覆盖的剪切板内容。
  本来从记事本中剪切了一段文字,想放到博客中保存下来,这是上周六写的一点心得体会。
  登录到csdn博客,发现有四位网友申请加我为好友。有朋自网络来,不亦乐乎!当然是要通过申请了。回复一句什么话好呢,首先想到的是:互相学习,以前都是这句,但中文似乎太没有新意,至少得用英文吧。可是,我的英文比较烂,当初就是因为这才没有考上清华北大,以至于流落到IT业混饭,这行的就业门槛比较低啊!还好有互联网,很容易就找到了这句:Let's learn from each other。急不可耐地复制下来,也好显摆一下。一般没文化的人都喜欢说自己又读了什么书,不会英文的人总爱摆弄几句单词。
  可是,马上我就后悔了。那我刚才剪切(非复制)的那段文字跑到哪儿去了呢?那可是我的灵光一现,丢了可就没有了。
  我欲哭无泪,只好在这里求助:如何找到剪切板中被覆盖的信息呢?
  Let's learn from each other!
根据原作 https://pan.quark.cn/s/459657bcfd45 的源码改编 Classic-ML-Methods-Algo 引言 建立这个项目,是为了梳理和总结传统机器学习(Machine Learning)方法(methods)或者算法(algo),和各位同仁相互学习交流. 现在的深度学习本质上来自于传统的神经网络模型,很大程度上是传统机器学习的延续,同时也在不少时候需要结合传统方法来实现. 任何机器学习方法基本的流程结构都是通用的;使用的评价方法也基本通用;使用的一些数学知识也是通用的. 本文在梳理传统机器学习方法算法的同时也会顺便补充这些流程,数学上的知识以供参考. 机器学习 机器学习是人工智能(Artificial Intelligence)的一个分支,也是实现人工智能最重要的手段.区别于传统的基于规则(rule-based)的算法,机器学习可以从数据中获取知识,从而实现规定的任务[Ian Goodfellow and Yoshua Bengio and Aaron Courville的Deep Learning].这些知识可以分为四种: 总结(summarization) 预测(prediction) 估计(estimation) 假想验证(hypothesis testing) 机器学习主要关心的是预测[Varian在Big Data : New Tricks for Econometrics],预测的可以是连续性的输出变量,分类,聚类或者物品之间的有趣关联. 机器学习分类 根据数据配置(setting,是否有标签,可以是连续的也可以是离散的)和任务目标,我们可以将机器学习方法分为四种: 无监督(unsupervised) 训练数据没有给定...
Task 3: Simulate Election (4 marks) To select the winner of the election, instant-runoff voting (IRV) is used. This method selects a winner over the course of a number of rounds. The following procedure is repeated until there is only one candidate left: Assign each ballot to the candidate who is ranked highest on that ballot and who has not yet been eliminated. Eliminate the candidate(s) with the lowest number of assigned ballots in that round, so they are not counted in future rounds. For this task, you must run a simulated IRV for an election given a list of valid positional ballots. Write a function simulate_election(ballots, parties) You need to write a function that returns the full history of elimination rounds for the given election. Arguments: ballots: a list of valid positional ballots. parties: the ordered list of parties contesting the election. Returns: a list of elimination round history, where each round consists of a tuple with: A dictionary mapping each remaining candidate to their vote total A set of candidates to be eliminated after that round. Details: If two candidates are tied for the lowest vote total in a round, they are both eliminated simultaneously If there is no unique winner, your program should raise a TiedElectionError as defined at the top of the provided code. As a reminder, you can raise an error using the built in Python statement raise TiedElectionError. This is a custom Exception type that we have defined for you. You can use it like any other Exception , and there is no need to understand how we have defined it. Interested students can learn more about custom object and classes in this optional worksheet. Example Calls:
10-17
```python def simulate_election(ballots, parties): """ Simulates an Instant-Runoff Voting (IRV) election and returns the history of elimination rounds. Arguments: ballots: List of valid positional ballots. Each ballot is a list of party indices representing the voter's ranking (from highest to lowest preference). parties: Ordered list of parties (candidates) in the election. Used to map indices to names. Returns: A list of tuples. Each tuple contains: - A dictionary mapping each remaining candidate (by name) to their vote total - A set of candidates (by name) to be eliminated in that round Raises: TiedElectionError: If at the end of the process there is more than one candidate remaining and they are tied (i.e., no unique winner). """ # Make a copy of remaining candidates (by name), so we can eliminate them over time remaining = set(parties) # This will store the full history of rounds history = [] # Keep going until one or zero candidates remain while len(remaining) > 1: # Dictionary to count votes for each remaining candidate vote_count = {candidate: 0 for candidate in remaining} # Assign each ballot to the highest-ranked candidate still in the race for ballot in ballots: for rank in ballot: candidate = parties[rank] # Map index back to party name if candidate in remaining: vote_count[candidate] += 1 break # Found top-preferred active candidate; stop checking this ballot # Find the minimum number of votes received min_votes = min(vote_count.values()) # Identify all candidates with the minimum vote count (to be eliminated) to_eliminate = {cand for cand, votes in vote_count.items() if votes == min_votes} # Record this round's state before elimination history.append((dict(vote_count), set(to_eliminate))) # Eliminate the bottom candidates remaining -= to_eliminate # After loop: either 0 or 1 candidate remains if len(remaining) == 0: # No candidate left → tie among last ones eliminated raise TiedElectionError("Election resulted in a tie.") # Now only one candidate should remain — but we must check final condition # According to problem: if no *unique* winner exists, raise error # The only way this happens here is if the last two were tied and both eliminated, # which leaves `remaining` empty. But what if two remain and have equal votes? # Actually, our loop stops when len(remaining) <= 1. # So suppose two candidates are tied for last, both get eliminated — fine. # But if two candidates are left and both have same votes? They would NOT be eliminated # unless they are the lowest — but they're the only ones! So both would be eliminated # **only** if both have the same (lowest) value — which they do. # Therefore, if two final candidates are tied, they are BOTH eliminated → remaining becomes empty # So we already catch that via the above check. # However, let’s ensure correctness: if the last round eliminates all remaining candidates # because they’re tied for lowest, then we end up with no winner → must raise error. # Our current logic already does that: after the loop, if `remaining` is empty → raise error. return history ``` ### Explanation: The function simulates **Instant-Runoff Voting (IRV)** where voters rank candidates by preference (via indices). In each round: 1. **Votes are reassigned**: Every ballot goes to the highest-ranked candidate on that ballot who hasn't been eliminated yet. 2. **Count votes**: For all currently remaining candidates, tally how many ballots assign them as top choice. 3. **Eliminate weakest**: All candidates with the fewest votes (minimum count) are marked for elimination — even if multiple tie for lowest, they are all removed **in the same round**. 4. **Record round**: Append a tuple containing: - A dictionary of `{candidate: vote_total}` - A set of candidates to eliminate 5. **Repeat** until one or zero candidates remain. If **zero** candidates remain at the end (e.g., final two were tied and both eliminated), it means there’s no unique winner → raise `TiedElectionError`. > Note: The key insight is that ties in the **lowest** vote totals cause simultaneous eliminations. Only when exactly **one** candidate remains do we accept them as the unique winner. --- ### Example Usage: ```python # Suppose: parties = ["Liberal", "Labor", "Greens", "National"] ballots = [ [0, 1, 2, 3], # prefers Liberal > Labor > Greens > National [1, 2, 0, 3], # prefers Labor > Greens > Liberal > National [2, 1, 0, 3], # prefers Greens > Labor > Liberal > National ] # Call: history = simulate_election(ballots, parties) for i, (votes, elim) in enumerate(history): print(f"Round {i+1}: Votes={votes}, Eliminated={elim}") ``` This would output something like: ``` Round 1: Votes={'Liberal': 1, 'Labor': 1, 'Greens': 1, 'National': 0}, Eliminated={'National'} Round 2: Votes={'Liberal': 1, 'Labor': 2, 'Greens': 1}, Eliminated={'Liberal', 'Greens'} ... ``` And if only `Labor` remains → success. If next round tries to eliminate both final two due to tie → raises `TiedElectionError`. ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值