Help for Basket Players code project. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Help for Basket Players code project.

#Task : The given code includes a list of heights for various basketball players. #You need to calculate and output how many players are in the range of one standard deviation from the mean. #MyCode: import math as mt import numpy as np a = np.array([180, 172, 178, 185, 190, 195, 192, 200, 210, 190]) mean = np.sum(a) / a.size variance = np.sum((a-mean)**2)/a.size std_deviation = mt.sqrt(variance) result = 0 for x in a : if x in range (int(mean-std_deviation),int(mean+std_deviation+1)) : result+=1 print(result) print(variance) print(std_deviation ) #There's one case , it's hidden , where's the problem here ?

8th Jan 2023, 8:54 AM
Ben Hamida Mohamed Amine
Ben Hamida Mohamed Amine - avatar
3 Answers
+ 3
Ben Hamida Mohamed Amine In the range() funtion, using int() on the calculated min value (mean - std) of 178.63 truncates it to the integer 178. This ends up making the range include the 178 value from the array, which is incorrect. I don't think range() can be used here, since it only accepts integers and your actual range values are floats. Try using simple relational operations instead. Something like this: if (x >= mean-std) and (x <= mean+std): ... Also, you can compute the mean and std dev directly in numpy: a.mean() a.std() To further shorten the code, you can make use of numpy's boolean masking instead of a loop: a = np.array([...]) mask = (a>=a.mean()-a.std()) & (a<=a.mean()+a.std()) print(np.sum(mask))
8th Jan 2023, 1:09 PM
Mozzy
Mozzy - avatar
+ 2
Ben Hamida Mohamed Amine remember to mark Mozzy's answer as best to give XP credit. This is my replacement for range to fix your code: if abs(x - mean)<=std_deviation:
8th Jan 2023, 7:37 PM
Brian
Brian - avatar
+ 1
Thanks i solved it
8th Jan 2023, 1:10 PM
Ben Hamida Mohamed Amine
Ben Hamida Mohamed Amine - avatar