簡體   English   中英

Python斷裂了一定數量

[英]Python breaks for a certain amount

所有人,我不太會解釋,所以我會讓我的評論做到這一點!

#this script is to calculate some of the times table up to 24X24 and also miss some out
#Range of numbers to be calculated
numbers=range(1,25)
for i in numbers:
    for w in numbers:
        print(str(i)+"X"+str(w)+"="+str(i*w))
        #here i want to break randomly (skip some out) e.g. i could be doing the 12X1,12X2 and then 12X5 i have no limit of skips.

更新資料

抱歉,如果不清楚,我希望它從內循環中斷開一段時間

您可以使用random.random生成范圍為[ random.random的浮點數。

然后,僅當數字低於可定制的閾值時,才可以打印字符串。 例如,在下面的代碼中,我使用< 0.2 ,這意味着if部分將只執行20%的時間:

from random import random

for i in range(1, 25):
    for w in range(1, 25):
        if (random() < 0.2):
            print('%dX%d=%d' % (i, w, i * w))

您可以使用itertools.product簡化代碼,然后使用random.choice決定是否跳過每個方程式:

from itertools import product
import random

def random_equations(limit):
    for x, y in product(range(1, limit), repeat=2):
        if random.choice((True, False)):
            print("{0}x{1}={2}".format(x, y, x*y))

演示用法:

>>> random_equations(5)
1x1=1
1x2=2
1x3=3
2x2=4
3x1=3
4x2=8

這將跳過大約一半-您可以更改要從中選擇的元組(例如((True, True, False))將跳過大約三分之一),或采用類似Enrico的數值方法來更改比例。

暫無
暫無

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

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