2016-12-01 28 views
1

リストxsの数値の2乗の合計を計算するsum_of_squares(xs)関数を記述しようとしています。例えば、sum_of_squares([2、3、4])は29である4 + 9 + 16を返す必要があります:リストの数値の二乗和を計算する関数

ここに私が試したものです:

import random 

xs = [] 

#create three random numbers between 0 and 50 

for i in range(3): 
    xs.append(random.randint(0,50)) 

def sum_of_squares(xs): 

#square the numbers in the list 

    squared = i ** i 

#add together the squared numbers 

    sum_of_squares = squared + squared + squared 

    return sum_of_squares 

print (sum_of_squares(xs)) 

今、これは常に

12 
を印刷します

整数の値とは対照的に、リストの整数の数と同じようにiをとっているからです。二乗された値を取得するために、整数の値がリストに含まれているため、「整数の値で値を乗算する」とはどうすればよいですか?その質問をお願い

は、このしようとする私を導い:

import random 

xs = [] 

#create three random numbers between 0 and 50 

for i in range(3): 
    xs.append(random.randint(0,50)) 

def sum_of_squares(xs): 

#square the numbers in the list 

    for i in (xs): 
     squared = i ** i 

#add together the squared numbers 

     sum_of_squares = squared + squared + squared 

    return sum_of_squares 

print (sum_of_squares(xs)) 

をしかし、それは正しく整数の値を二乗していないようです - 私はそれをやっているかわからないんだけど。このスクリーンショットを参照してくださいVisualize PythonウォークスルーのSee Screenshot

+1

'= I ** i'が間違っているの二乗。あなたは 'i * i'または' i ** 2'のいずれかを意味します。 ---そして、私はその機能の中から目に見えることになっていますか?それはグローバルな整数です。 – byxor

答えて

3

あなたは愚かな間違いをしています。最初の紙の上で右

import random 
xs = [] 
for i in range(3): 
    xs.append(random.randint(0,50)) 

def sum_of_squares(xs): 
    sum_of_squares=0 #mistake 1 : initialize sum first. you are making new sum variable in loop everytime. 
    for i in (xs): 
     squared = i * i #mistake 2 : ** is exponent and not multiply. 
     sum_of_squares += squared #mistake 3 
    return sum_of_squares 

print (sum_of_squares(xs)) 
+0

sumを初期化するのになぜsum_of_squares = 0を使用するのですか? 2番目の間違いは理にかなっており、簡単に修正できます。ありがとう。 – Sean

+1

あなたがやっていたことはループ内でsum_of_squaresを宣言しているので、各反復で新しく計算すると宣言していましたが、必要なものは最後の反復だけでなく総和です。プラスミス#3は間違い#2の下に追加のフォーミュラでした。 –

+0

もし私たちに[13,31,20]があれば、sum_of_squaresを400として返すでしょうか?間違い#3は理にかなっています。 – Sean

4
def sum_of_squares(xs): 
    return sum(x * x for x in xs) 
+3

このソリューションはかなりいいです。私は、質問者が理解することは難しいだろうと思う。 – byxor

+0

はブランドンに同意します。それがより良いアプローチである理由をあなたの答えに説明することを検討してください。 –

1

コンセプト:これを試してみてください。

  1. あなたは数字のリストを持っています。
  2. リストを解析し、正方形を実行して変数に保存する必要があります。

    import random 
    
    xs = [] 
    
    #create three random numbers between 0 and 50 
    
    for i in range(3): 
        xs.append(random.randint(0,50)) 
    
    def sum_of_squares(xs): 
        result = 0 
        for i in xs: 
         result += i*i 
    
        return result 
    
関連する問題