Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@xavierskip
Created January 22, 2019 03:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xavierskip/b8151b94ccd0e3eff6fad1aa9e55cd98 to your computer and use it in GitHub Desktop.
Save xavierskip/b8151b94ccd0e3eff6fad1aa9e55cd98 to your computer and use it in GitHub Desktop.
在某个数值范围内生成给定数目的数字, 且这些数字之和等于则个数值
import random
def randsums(nrange, count):
l = []
for i in range(count):
# print(nrange)
if i == count-1:
l.append(nrange[-1])
else:
r = random.randrange(*nrange)
# print(r)
l.append(r)
a,b = nrange
b -= l[-1]
nrange = [a,b]
return l
if __name__ == '__main__':
n = 100
k = 10
for i in range(100000):
result = randsums([0,n], k)
if sum(result) == n:
pass
else:
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment