繁体   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