-1

このコードは最大ペアワイズ製品用です。テストしてきましたが、いくつかの問題に遭遇しました。

import sys
import random
while True:
    a=int(random.randrange(1,1000000,101))
    keys =[]     # keys is empety list
    i=0

    while i < a :
        keys.append(int(random.randrange(1,10000,8)))
        i=i+1

    keys.sort()
    print(keys[-1], keys[-2])
    x=keys[-1]*keys[-2]
    print( "the max is ",x)

ただし、何らかの理由で、コードの出力は常に同じです。

9993 9993
the max is  99860049
9993 9993
the max is  99860049
9993 9993
the max is  99860049
9993 9993
the max is  99860049

なぜこれが起こっているのか理解できません。説明をいただければ幸いです。

4

2 に答える 2

0

問題はあなたaです。ハードコードで 100 と言うと大きすぎます。

9945 9857
the max is  98027865
9905 9881
the max is  97871305
9969 9881
the max is  98503689
9977 9849
the max is  98263473
9977 9945
the max is  99221265
9713 9617
the max is  93409921
9993 9977
the max is  99700161
9929 9841
the max is  97711289
9881 9761
the max is  96448441
9953 9841

あなたはあなたのようにa選ぶ

>>> random.randrange(1,1000000,101)
18181
>>> random.randrange(1,1000000,101)
835069
>>> random.randrange(1,1000000,101)
729524
>>> 

あなたのキーは、唯一のプールから選択されます

>>> len(range(1, 10000, 8))
1250
>>> 

(多かれ少なかれ1つ)

1250 の異なる要素のみを使用して、それよりも多くの方法を取る場合 (18181 など) は、多くの場合、その範囲内のすべての可能な数値を取得する (数回) ため、常に同じ結果が得られます。その範囲の最大数(9993)を数回取得することがほぼ保証されていることを試してみてください。そのリストをソートすると、結果として何度も取得できます。

これはピジョンホールの原理として知られています


何をするかについては、代わりにサンプルを使用することを検討してください

for _ in range(5):
    a,b = random.sample(range(1,10000,8),2)
    print(a,b)
    print( "the max is ",a*b)

出力

2881 689
the max is  1985009
2329 6473
the max is  15075617
5953 7769
the max is  46248857
9905 3201
the max is  31705905
6897 4713
the max is  32505561
于 2017-02-12T20:29:05.867 に答える