2017-03-11 10 views
0

7-11問題を解決するプログラムを書く必要があります(これが何であるかわからない場合は、Googleが説明します)。$ 7.11を作るために加算して乗算する値を見つける代わりに、 a、b、c dのすべてのユニークな値が加算されて、$ x.yzが$ 1.00〜$ 9.99になるように増やす必要があります。一般化7-11数学

これは、a、b、c、dがnを作るために掛けるかどうかをチェックするif文になりますが、決して真ではありません。

def factors(n): 
    #Finds all the factors of n and adds them to an array 
    factors_of_n = [] 
    for i in range(1, n): 
     if(n % i == 0): 
      factors_of_n.append(i) 

    #Runs through the array and checks if they add and multiply to 
    #equal n 
    for a in factors_of_n: 
     for b in factors_of_n: 
      for c in factors_of_n: 
       for d in factors_of_n: 
        if(a < b and b < c and c < d): 
         if(a + b + c + d == n): 
          if(a * b * c * d == n * 1000000): 
           #It never gets into this loop 
           print "please" 
           return True     
def g711(): 
    min = 100 
    max = 999 
    count = 0 

    for n in range(min, max): 
     if factors(n): 
      print "yay" 

私はそれをチェックして私が間違っている場所を見ているよりも、数学では少し上手い人が必要です。

+0

あなたは答えが 'N'の因子であることが持っていると仮定しますなぜ? 「7.11」の解は「3.16,1.25,1.50,1.20」であり、そのうち「7.11」の因子はない。 – AChampion

+0

私はそれが繰り返しなければならない繰り返し数を制限すると考えましたが、実際にあなたが正しいと考えるようになった今、私はばかだと感じます。 – Kalmonipa

+0

したがって、nの係数を制約として使用する代わりに、プログラムが実行する反復回数をどのように制限できますか?それ以外の場合は、100から999までのあらゆる数字に対して、1からnまでのすべての置換を実行する必要があります。 – Kalmonipa

答えて

0

これはitertools.combinations_with_replacementを使用して単純化することができます。

from itertools import combinations_with_replacement as cwr 

def factors(n): 
    ... 

r = {} 
for n in range(100, 999): 
    for a, b, c, d in cwr([f for f in factors(n*1000000) if f < n], r=4): 
     if a+b+c+d == n and a*b*c*d == n*1000000: 
      r.setdefault(n, []).append((a,b,c,d)) 

結果:

{644: [(125, 160, 175, 184)], 
651: [(125, 140, 186, 200)], 
660: [(110, 150, 200, 200)], 
... 
711: [(120, 125, 150, 316)], 
... 
992: [(32, 250, 310, 400)] 
}