Python计数器不工作。或者我忘了一年级的数学

2024-04-20 07:06:49 发布

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

你好啊, 我快疯了,如果有人帮忙我会很高兴的。 代码如下。输出没有给我正确的计数

import os, sys
from random import randint
from collections import Counter
import random

N = range(1,11)
print "N=" , N

#the stupid part below should take 10 random integers whose sum is equal to 10
def sum_to_ten(n):
    values = [1, 11] + [random.randint(2,n) for _ in range(n - 1)]
    values.sort()
    return [values[i+1] - values[i] for i in range(n)]
E = sum_to_ten(10)
print "E is: ", sum_to_ten(10)
N_E = dict(zip(N,E))
print N_E
#N_i should count the number of times an integer shows up, but does it? NO.
N_i = Counter(E)
print "N_i is:", N_i

输出如下:

N is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
E is:  [1, 0, 1, 2, 0, 1, 2, 0, 1, 2]
N_E : {1: 1, 2: 4, 3: 1, 4: 0, 5: 1, 6: 0, 7: 0, 8: 2, 9: 0, 10: 1}
N_i is: Counter({0: 4, 1: 4, 2: 1, 4: 1})


#See, N and E doesn't zip together to a dictionary correctly, and the counter doesn't count right.

Tags: thetofromimportforiscounterrange