[英]Can I make this algorithm more efficient?
这是大学的作业。 我必须模拟 10 个随机掷骰子(在 1 - 6 之间)并将它们放在一个列表中,然后创建另一个列表,该列表将保留每个值的滚动次数。 我的输出必须是这样的:
Your rolls: [6, 2, 3, 4, 5, 6, 3, 1, 5, 2]
Number of rolls:
1 -> 1
2 -> 2
3 -> 2
4 -> 1
5 -> 2
6 -> 2
这是我的代码结果:
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = []
print(f"Your rolls: {rolls}")
print("Number of rolls:")
rolls.sort()
for i in rolls:
# Puts the amount of times each number (1-6) rolled inside roll_count
roll_count.append(rolls.count(i))
# Removes the duplicates so that the count doesn't register again
while rolls.count(i) > 1:
rolls.remove(i)
for n in range(1, 7):
# Checks if the possible rolls (1-6) have been rolled, if not place the count as 0
# in the sorted index inside roll_count
if n not in rolls:
roll_count.insert(n - 1, 0)
print(f"{n} -> {roll_count[n - 1]}")
它工作正常,但我想知道我是否可以使它更高效甚至简化它。
这种任务的标准工具是来自标准库的collections.Counter
。 它专为这项任务而设计。
from collections import Counter
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = Counter(rolls)
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for n in range(1, 7):
print(f"{n} -> {roll_count[n]}")
Your rolls: [2, 5, 3, 3, 3, 2, 5, 5, 2, 6]
Number of rolls:
1 -> 0
2 -> 3
3 -> 3
4 -> 0
5 -> 3
6 -> 1
如果由于某种原因不允许您使用collections.Counter()
,那么您的实现就尽可能好,只有一个例外 - dict
是比滚动计数list
更好的数据结构(确实, collections.Counter
是dict
的子类)。 这使您可以使用setdefault()
和get(key, default)
,这减少了几行代码:
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = {}
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for i in rolls:
roll_count.setdefault(i, 0) # does nothing if element is already present
roll_count[i] += 1
for n in range(1, 7):
print(f"{n} -> {roll_count.get(n, 0)}")
from random import randint
rolls = []
roll_count = [0] * 6
for i in range(10):
r = randint(1,6)
rolls.append(r)
roll_count[r-1] = roll_count[r-1] + 1
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for n in range(1, 7):
print(f"{n} -> {roll_count[n - 1]}")
不是循环一次以形成滚动列表然后再次循环以计算每个列表,您可以通过这种方式循环一次并滚动以及在同一循环中计数。 而且您也不需要排序或检查计数是否存在。
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for i in range(1,7):
print(f"{i} -> {rolls.count(i)}")
由于您的值范围如此有限,因此无需使用任何花哨的集合来跟踪它们,当然也无需对输入进行排序。 一个简单的list
就可以了,初始化为全零。
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = [0] * 6
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for i in rolls:
# Puts the amount of times each number (1-6) rolled inside roll_count
roll_count[i - 1] += 1
for n in range(1, 7):
print(f"{n} -> {roll_count[n - 1]}")
Your rolls: [4, 1, 3, 3, 4, 3, 4, 5, 2, 2]
Number of rolls:
1 -> 1
2 -> 2
3 -> 3
4 -> 3
5 -> 1
6 -> 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.