
穆罕默德·S·安瓦尔 (Mohammad S. Anwar) 每周都会发布“每周挑战”,提供机会让大家为每周两次的任务编写解决方案。我的解决方案先用 Python 编写,再转换为 Perl。这是一个很好的练习编码方式。
挑战与我的解决方案
给定一个包含三个或更多正整数的列表 @ints。
编写一个脚本,返回所有可以使用给定列表中的整数组成的三位偶数。
幸运的是,Perl 和 Python 都有模块可以计算列表中三位整数的所有排列。我调用该函数,然后过滤掉以 0 开头或以奇数结尾的数字。
在 Python 中,我使用集合来存储唯一的整数。由于 Perl 没有集合,我使用哈希来实现相同的功能。
<code class="python">from itertools import permutations
from collections import Counter
def three_digits_even(ints: list) -> list:
solution = set()
for p in permutations(ints, 3):
if p[-1] % 2 != 0 or p[0] == 0:
continue
number = int("".join(map(str, p)))
solution.add(number)
return sorted(list(solution))</code><code class="bash">$ ./ch-1.py 2 1 3 0 [102, 120, 130, 132, 210, 230, 302, 310, 312, 320] $ ./ch-1.py 2 2 8 8 2 [222, 228, 282, 288, 822, 828, 882]</code>
给定一个整数数组 @ints。
编写一个脚本,返回通过多次应用以下操作可以获得的最大分数:
ints[i] 并将其删除以获得 ints[i] 分。ints[i] - 1 和 ints[i] + 1 的元素。对于此任务,我将整数列表转换为每个整数的频率字典。然后我调用递归函数 score 来查找最大分数。
<code class="python">from collections import Counter
def delete_and_earn(ints: list) -> int:
freq = Counter(ints)
return score(freq)
def score(freq: Counter) -> int:
max_points = None
for i in freq:
points = i
new_freq = freq.copy()
if i - 1 in new_freq:
del new_freq[i - 1]
if i + 1 in new_freq:
del new_freq[i + 1]
new_freq[i] -= 1
if new_freq[i] == 0:
del new_freq[i]
if new_freq:
points += score(new_freq)
if max_points is None or points > max_points:
max_points = points
return max_points if max_points is not None else 0
</code><code class="bash">$ ./ch-2.py 3 4 2 6 $ ./ch-2.py 2 2 3 3 3 4 9</code>
以上就是用 igt 赚钱的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号