2017-06-08 6 views
2

私はCodi​​lityで行うデモタスクを与えられました。私が間違っていることを理解するためにいくつかの問題を抱えています。タスク:Python 2.7の平衡指数

のPython 2.7環境

にN個の整数からなるゼロインデックス付き配列作業が与えられます。この配列の平衡指数は、0≦P < Nであり、下位指標の要素の合計が上位指標の要素の合計と等しい任意の整数Pである。すなわち、

A [0] + A [1] + A [P-1] = A [P + 1] + ... + A [N-2] + A [N-1]となる。

ゼロ要素の合計は0と見なされます。これは、P = 0またはP = N-1の場合に発生します。例えば

、検討N = 8つの要素からなる以下の配列:

A[0] = −1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7] 

P = 3である:

A[0] = -1 
A[1] = 3 
A[2] = -4 
A[3] = 5 
A[4] = 1 
A[5] = -6 
A[6] = 2 
A[7] = 1 

P = 1であるため、このアレイの均衡インデックスでありますこの配列の平衡インデックスため::P = 7があるため、また、平衡指標である

A[0] + A[1] + A[2] = −2 = A[4] + A[5] + A[6] + A[7] 
A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0 

及び7

それは条件0≤P < N.

書き込みAを満たさないので、P = 8は、平衡インデックスはないよりも大きいインデックスを持つ要素がありません関数:Nの整数からなるゼロインデックス配列を与え、

DEF溶液(A)

は、その平衡インデックスのいずれかを返します。平衡インデックスが存在しない場合、関数は-1を返すはずです。応答で

は、私は次のように書いた:私は、コードを遵守すると

def solution(A): 
    if len(A) == 0: #If we're working with an empty list, the method should give us an empty list message and terminate there 
     return "Empty list, no integers to work with" 
    else: 
     equi = [] 
     x = 0 
     length = len(A) 
     rightSum = [] 
     leftSum = [] 
     while x < length: 
      for i in A: 
       rightSum = A[1:i-1] 
       leftSum = A[i+1:length-2] 
       if sum(rightSum) == sum(leftSum): 
        equi.append(i) 
        return equi 
       else: 
        return -1 
      x += 1 
    pass 

solution([-1,3,-4,5,1,-6,2,1]) 

、私が取得保管-1テストリストのために、私はエクイ取得する必要があるにもかかわらず、[1,3,7]。

もう1つの質問ですが、なぜメソッドの最後に 'pass'キーワードが必要ですか?

私はPythonのコーディングとコーディングに一般的に非常に新しいです。 y'allが提供できるどんな助力も高く評価されます。

答えて

2

関数が返さなければならないデータの種類を考えてください。平衡指数のリストです。

これは、関数のすべてのreturnステートメントがリストを返す必要があることを意味します。決して数字ではなく、文字列ではありません。

空のリストの場合、平衡インデックスはありません。 return []

平衡インデックスが見つかったら、それを正確にはリストに追加します。となり、に進みます。 whileループ内のreturnを使用しないでください。最初のreturnステートメントは、関数の実行を終了します。

すべてのインデックスを調べてループが終了すると、equiリストには、ループが見つけたすべての平衡インデックスが含まれます。さて、ループの後、それは無駄なpassの代わりにreturn equiの時間です。

(ボーナスポイントの場合は、リストの合計を1回計算することができます。右側にインデックスを移動すると、左の合計に1つの要素が追加され、右の合計から同じ要素が減算されます。毎回sumにする必要があります;アルゴリズムのパフォーマンスは2次ではなく線形になります。)

+0

ありがとう9000、それはボーナスポイントについての本当に有益な提案でした。私は全体の合計からインデックス値を単に差し引くことについては考えていませんでした。将来の参照のために、線形と二次の違いがパフォーマンス、オーバーヘッドなどに及ぼす影響の程度はどれくらいでしょうか?私はまだそこにはいませんが、パフォーマンスの改善やオーバーヘッドの減少が歓迎されると思います。 – Ram

2

あなたのロジックは正常ですが、言語の構文の一部を実行しています。

私はそれをコメントしながら、あなたのコードを助けるために全力を試してみた:(enumerateを使用して、変数の命名規則)読みやすくするために改善することができるカップル、他のマイナーなものがあり

def solution(A): 
    if len(A) == 0: #If we're working with an empty list, the method should give us an empty list message and terminate there 
     return "Empty list, no integers to work with" 
    else: 
     equi = [] 
     x = 0 
     length = len(A) 
     rightSum = [] 
     leftSum = [] 
     # while x < length: (removed) 
     # When we do for i in A, we're already iterating over each element i of the list A. 
     # As such, there's no need for the while loop. 
     for i in A: 
      # You switched right and left sum; elements at the 'left' are at the beginning of the list 
      # I also switched the name of the lists to leftList and rightList, to be more descriptive 
      # (a list and a sum are different things) 
      # I switched the i that was in the indexes to x. i is the integer on the list we're iterating over; 
      # its position on the list, on the other hand, is being counted with x. 
      leftList = A[0:x] # Go from 0, since you want to count the first element. 
      # We could also ommit the first index and it would begin from the first element 
      rightList = A[x+1:] # If we ommit the second index, it'll go until the last element 
      if sum(leftList) == sum(rightList): 
       # I changed equi.append(i) to equi.append(x), because i is the value we're iterating over, while 
       # x is the counter (index) of the number being currently evaluated 
       equi.append(x) 
       # return equi (removed) 
       # We don't want to return here. When we call return, the function exits! 

      # What this would do is exit the function if the sum of the left list wasn't equal to the sum of the right. 
      # This isn't what we want, so we'll just remove this 
      # else: (removed) 
      #  return -1 (removed) 
      x += 1 

     # No pass needed; that's another thing entirely, just a nil instruction 

     # Now the loop is done, we have appended to equi all the equilibrium values. 
     # It's time to exit the function by returning the list of equi values. 
     # Since we must return -1 if no equilibrium indices exist, then we have to check for that as well 
     if len(equi) == 0: 
      return -1 
     else: 
      return equi 

sol = solution([-1, 3, -4, 5, 1, -6, 2, 1]) 
print(sol) # [1, 3, 7] 

が、用簡潔さと簡潔さのために、私はそれを動作させるものを含めました。

+0

コーディングのヒントをペドロにありがとうございます。うまくいけば、私がより良くなるにつれ、真のPython開発者のようにコード化することができます!列挙型()については、リスト、ダイス、タプルなどの値を単に出力するという印象を受けましたが、私はそれがどれほど有用であるかを確かに見ることができますが、このシナリオではどのように役立つかはわかりません、atm。 – Ram

+0

@Ram 'enumerate'は反復回数と並んで値をリストアップします。基本的にxカウンタと同じです。だから 'x 'を使うのではなく' for x、i in enumerate(A) 'を実行して' x = 0'と 'x + = 1'を取り除いても同じことができます。各ループの反復を自動的に宣言し、自動的にインクリメントします。 –