Joe - 1 year ago 56

Python Question

I am trying to calculate student statistics using Python. Everything seems to be working fine except for the standard deviation part at the end. I thought I Interpreted the formula right but clearly it's not. I keep getting 6.63 instead of the actual 7.48. Help will be highly appreciated. UPDATE: I did the math. Turns out the summation should actually be 279 while my code generates Summation= 220. Maybe that'll help some of you, including me, to try and find the issue.

`nums=[]`

total= 0

count= 0

x = int(input("Enter a number (enter -1 to terminate): "))

while x >= 0:

if x <= 100:

total = total + x

count+=1

nums.append(x)

if x>100:

print("Invalid entry.")

x = int(input("Enter a number (enter -1 to terminate): "))

print(nums)

print("Number of scores: ", count)

idx=0

while idx < count:

newIndex = idx+1

maximum = nums[idx]

while newIndex < count:

if(nums[newIndex] < maximum):

maximum = nums[newIndex]

newIndex+=1

if maximum < nums[idx]:

temp = nums[idx]

nums[idx] = maximum

nums[newIndex-1] = temp

idx+=1

print("Maximum score: ", maximum)

idx= 0

while idx< count:

newIndex= idx+1

minimum= nums[idx]

while newIndex < count:

if (nums[newIndex]> minimum):

minimum= nums[newIndex]

newIndex+=1

if minimum> nums[idx]:

temp= nums[idx]

nums[idx]= minimum

nums[newIndex-1]= temp

idx+=1

print("Minimum score: ", minimum)

average=total/count

print ("Average score: ", average)

summation=0

idx=0

while idx< count:

value= nums[idx]

if idx<count:

summation += ((value-average)**2)

idx+=1

print("Standard Deviation: ", int(summation/count)**0.5)

Answer

You have a mistake in

```
if(nums[newIndex] < maximum):
maximum = nums[newIndex]
```

the comparison should be `>`

not `<`

.

**Edit:** the block

```
if maximum < nums[idx]:
temp = nums[idx]
nums[idx] = maximum
nums[newIndex-1] = temp
```

pooches your `nums`

... if you set `nums = [50, 40, 30, 20, 10]`

and run through the first `while idx < count:`

loop, you get back `nums = [10, 20, 20, 20, 30]`

. *Finding maximum* should not change the underlying data! (And why do you have a loop in a loop to find maximum? It should only take one pass!)

In fact, you can find maximum and minimum in a single pass, like so:

```
maximum = minimum = nums[0] # initialize to the first value
idx = 1 # start comparisons against the second value
while idx < count:
if maximum < nums[idx]:
maximum = nums[idx]
if minimum > nums[idx]:
minimum = nums[idx]
idx += 1
print("Maximum score: ", maximum)
print("Minimum score: ", minimum)
```