Python Forum

Full Version: finding percentage in a list.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone, i very new to python, for my uni course they have tasked us on finding a percentage in a list of 1's and 0's. for example
occupied_spaces [1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0] 
We have been told we are not aloud to use the "sum" command.

This is my code below
#Car Park Q2

#List of occupied spaces
occupied_spaces = [1, 0, 1, 1, 0, 0 , 0, 1, 1, 1, 0]


#Length of list
length = 0
for parked in occupied_spaces:
    length = length + 1

#Variables
parked = (1)
empty = (0)

#Percentage
percentage = int(parked/len(occupied_spaces))*100

print(percentage, '% of spaces are occupied')
i only seem to get 0% back. is there something i am missing? looking for some hints, i probs just missing one small thing.
A few things to consider:
  1. You are calculating list length in lines 7 through 10, but then using the len() function in line 17. You never use your calculation and presumably don't need it if you are allowed to use len().
  2. You define variables parked and empty, but you don't use empty at all. You define parked with a value of 1 and don't modify it anywhere, so it is essentially just a constant.
  3. Most importantly, your calculation on line 17 will always be 0 since parked will always be 1 here. You are getting the value of int(1/11), which evaluates to 0, and then multiplying it by 100. Even if this were coming out the way you intended, it would not be the right answer since parked is equal to 1 and not actually equal to the number of occurrences of 1 in your list.

Instead of calculating list length when iterating through the list in lines 7 - 10, try finding a way to increment a variable only for occupied spaces (count the 1s). Then you'll have the total number of occupied spaces, and can use that with a modified version of your line 17 to get the correct percentage.
The strange thing is, because "occupied_spaces" is defined as ones and zeros,
You need only one more line to print the result: rule of three (if you were allowed to use sum).
Now it's 4 lines.
(With perhaps 2 decimals in the %)
Paul
Hi!

Thank you for the comments i have finally been able to get the correct code
#Car Park Q2
#List of occupied spaces
car_park = [1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0]

#variables
cars = car_park.count(1)


#Percentage
percentage = cars/len(car_park)*100



print(round (percentage), '% of spaces are occupied')
This has made my day! thank you!