簡體   English   中英

使用 random.randint() 生成一系列等於輸入的數字

[英]Using random.randint() to generate series of numbers that equals an input

我正在嘗試使用以下 function:

random.randint()

生成一系列應該等於 input() integer 的數字。 這里唯一的問題是,我嘗試通過“while if”循環來做到這一點。 其中循環不斷生成數字,直到隨機組合等於 n = int(input())。 但是,這種方法非常耗時,有時 pycharm 需要一整分鍾才能找到正確的組合。 Any1 知道是否已經有解決此問題的功能?

編輯:將按照 ppl 的要求添加代碼,但是是的,代碼是變量的巨大 bcuz。 范圍來自 (1, a) 的原因是因為 (0, a) 的范圍會導致隨機模塊出錯。 如果您有興趣,請注意,我嘗試了相同的代碼塊,但使用其他變量來生成不同的東西,例如范圍為 (0, a) 的損益表,它工作得很好,我不知道為什么范圍 ( 0, a) 有時有效,有時無效。


# Cash
ca = 0
# Marketable securities
ms = 0
# Accounts receivable
ar = 0
# Inventories
i = 0
# Total current assets
tca = 0
# Land and buildings
lab = 0
# Machinery and equipment
mae = 0
# Furniture and fixtures
faf = 0
# Vehicles
v = 0
# Other (includes financial leases)
ot = 0
# Total gross fixed assets
tgfa = 0
# Less: Accumulated depreciation
ad = 0
# Net fixed assets
nfa = 0
# Total assets
ta = 0

# Accounts payable
ap = 0
# Notes payable
npp = 0
# Accruals
acc = 0
# Total current liabilities
tcl = 0
# Long-term debt (includes financial leases)
ltd = 0
# Total liabilities
tl = 0
# Preferred stock
ps = 0
# Common stock
cs = 0
# Paid-in capital in excess of par on common stock
pic = 0
# Retained earnings
re = 0
# Total stockholders’ equity
tse = 0
# Total liabilities and stockholders’ equity
tlase = 0

while ta <= 0 and 0 >= tlase:
    ca += random.randint(1,a)
    ms += secrets.randbelow(ca)
    ar += secrets.randbelow(ca)
    i += secrets.randbelow(ca)
    lab += random.randint(1,a)
    mae += random.randint(1,a)
    faf += secrets.randbelow(ca)
    v += secrets.randbelow(ca)
    ot += secrets.randbelow(ca)
    ad += secrets.randbelow(ca)
    ap += secrets.randbelow(ca)
    npp += secrets.randbelow(ca)
    acc += secrets.randbelow(ca)
    ltd += random.randint(1,a)
    ps += secrets.randbelow(ca)
    cs += secrets.randbelow(ca)
    pic += secrets.randbelow(ca)
    re += random.randint(1,a)
    tca += ca + ms + ar + i
    tgfa += lab + mae + faf + v + ot
    nfa += tgfa - ad
    ta += tgfa - (ad + ca + ms + ar + i)
    tcl += ap + npp + acc
    tl += tcl + ltd
    tse += ps + cs + pic + re
    tlase += ps + cs + pic + re + tcl + ltd

    if 0 >= ta and tlase <= 0:
        ca *= 0
        ms *= 0
        ar *= 0
        i *= 0
        lab *= 0
        mae *= 0
        faf *= 0
        v *= 0
        ot *= 0
        ad *= 0
        ap *= 0
        npp *= 0
        acc *= 0
        ltd *= 0
        ps *= 0
        cs *= 0
        pic *= 0
        re *= 0
        tca *= 0
        tgfa *= 0
        nfa *= 0
        ta *= 0
        tcl *= 0
        tl *= 0
        tse *= 0
        tlase *= 0

    elif ta != tlase:
        ca *= 0
        ms *= 0
        ar *= 0
        i *= 0
        lab *= 0
        mae *= 0
        faf *= 0
        v *= 0
        ot *= 0
        ad *= 0
        ap *= 0
        npp *= 0
        acc *= 0
        ltd *= 0
        ps *= 0
        cs *= 0
        pic *= 0
        re *= 0
        tca *= 0
        tgfa *= 0
        nfa *= 0
        ta *= 0
        tcl *= 0
        tl *= 0
        tse *= 0
        tlase *= 0
    else:
        print("true")

如果我理解敘述和評論,您的程序將提示輸入 integer 值,並嘗試找到固定數量的整數,當它們相加時將等於輸入的數字。 有了這個,這里有一個可能會刺激你的代碼片段。

import random

while True:

    response = input("Enter a number or enter 'Q' to quit: ")
    
    if response.upper() == "Q":
       break
       
    num     = int(input("Enter the number of integers that need to add up to your value: "))
    summary = int(response)
    tries   = 0
    
    while True:
        work = 0
        x    = []
        y    = 0
        for i in range (0, num):
            y = random.randint(1, summary)
            x.append(y)
            work  += y
            tries += 1
        if (work == summary):
            break
        
    print ("The selected random values are:", x, "after", tries, "tries")

我扔了一個計數器,說明程序嘗試了多少次整數組合來求和輸入的值。

以下是在我的終端上運行的測試。

@Una:~/Python_Programs/RandomSum$ python3 RandomSum.py 
Enter a number or enter 'Q' to quit: 442
Enter the number of integers that need to add up to your value: 4
The selected random values are: [38, 119, 124, 161] after 6476 tries
Enter a number or enter 'Q' to quit: 100
Enter the number of integers that need to add up to your value: 3
The selected random values are: [10, 46, 44] after 1392 tries
Enter a number or enter 'Q' to quit: 442
Enter the number of integers that need to add up to your value: 6
The selected random values are: [39, 236, 8, 30, 65, 64] after 49632 tries
Enter a number or enter 'Q' to quit: Q

試試看。

import random

def constrained_sum_sample_pos(n, total):
    """Return a randomly chosen list of n positive integers summing to total.
    Each such list is equally likely to occur."""

    dividers = sorted(random.sample(range(1, total), n - 1))
    return [a - b for a, b in zip(dividers + [total], [0] + dividers)]

這段代碼對我來說很好用,它不是我真正想要的,但它可以完成工作。 唯一的區別在於此代碼中,您輸入最大值,生成的數字總和等於您輸入的最大值。 但是,對於我的代碼,我試圖讓代碼本身從范圍中生成一個隨機最大值,並且其他生成的數字的總和應該仍然等於它。 因此,唯一的區別是我希望使最大值與它的變量一起隨機生成,以使生成的 output 完全隨機,盡管每次都輸入相同的輸入。

對於那些仍然沒有明白我的意思的人:提供的代碼是這樣的:A:你輸入這個值 B + C + D(隨機生成)= A

對於我的代碼:您的輸入 = 輸入() A:python 從范圍(1,您的輸入)B + C + D(也是隨機生成)= A 即使您使用相同的輸入,每次隨機生成的數字的總和將等於從范圍中隨機生成的輸入

我希望我沒有過度解釋

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM