第一个Python程序,"乐透预测"

时间:2014-06-23 02:37:22

标签: python

我是python的新手,并试图通过搞乱来快速学习它。所以我决定做一个乐透计划。它的选择3,数字0-9,从0-0-0到9-9-9选择三个数字。我想将过去调用的所有数字添加到变量或元组中。在打印结果之前检查此变量或元组。这就是我到目前为止所做的。

    import random
    items = range (10)
    random.sample([items]), 3
    [4, 0, 2]    # result

如何设置一个变量,其中包含过去绘制的数字结果和基于最常调用的打印结果?

任何帮助都将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:2)

获得5个统一号码

import random

items = range(10)

results = []

while len(results) < 5:
    number = random.sample(items, 3)
    if number not in results:
        results.append(number)

print results

[[2, 6, 3], [8, 0, 4], [0, 3, 4], [7, 8, 6], [2, 6, 9]]

获得1000个不是唯一的数字并获得3个最常见的结果

import random
import collections

items = range(10)

results = collections.Counter()

for __ in range(1000):
    number = random.sample(items, 3)
    results.update([tuple(number)])

print results.most_common(3)

[((2, 0, 6), 6), ((5, 4, 9), 6), ((1, 0, 3), 5)]

我得到了:

(2,0,6) - 6次,
(5,4,9) - 6次,
(1,0,3) - 5次,


修改

使用数字000111222并按照绘制的数量进行分组。

import random
import collections

results = collections.Counter()

for __ in range(50):
    digit1 = random.randint(0,9)
    digit2 = random.randint(0,9)
    digit3 = random.randint(0,9)
#    results.update([(digit1,digit2,digit3)])
    results.update([ '%d%d%d' % (digit1,digit2,digit3) ])

#print results

print
print '3 most common numbers:', results.most_common(3)

print
print '3 most common numbers:'
for x in results.most_common(3):
    print '%s - %d times' % x

grouped_results = {}

for number, times in results.items():
    if times not in grouped_results:
        grouped_results[times] = []
    grouped_results[times].append(number)

print
print 'grouped results:', grouped_results


for times, numbers in grouped_results.items():
    print
    print 'drawn %d time(s):' % times
    print numbers

结果:

3 most common numbers: [('152', 2), ('799', 2), ('088', 2)]

3 most common numbers:
152 - 2 times
799 - 2 times
088 - 2 times

grouped results: {1: ['458', '603', '335', '660', '012', '750', '396', '177', '176', '399', '497', '231', '254', '641', '694', '956', '322', '938', '918', '917', '586', '587', '584', '140', '069', '082', '299', '779', '617', '462', '025', '267', '169', '226', '084', '840', '909', '537', '929', '350', '824', '513'], 2: ['152', '799', '088', '261']}

drawn 1 time(s):
['458', '603', '335', '660', '012', '750', '396', '177', '176', '399', '497', '231', '254', '641', '694', '956', '322', '938', '918', '917', '586', '587', '584', '140', '069', '082', '299', '779', '617', '462', '025', '267', '169', '226', '084', '840', '909', '537', '929', '350', '824', '513']

drawn 2 time(s):
['152', '799', '088', '261']