Samh625
Samh625

Reputation: 19

How to find the percentage in my python list

So i am doing an assignment, i need to find the percentage of occupied spaces in a car park, i have got my list and the calulation for pencentage. when i run the program i get 0%.

I assume i am doing something wrong as the list is not being picked up.

Just looking for some hints and tips not a full on answer :)

#Find the percentage of occupied car spaces.

#Input: Cars in spaces
occupied_spaces = [1, 1, 1, 1, 1, 1, 0, 0, 0 ,0, 0] 

#Output: of spaces occupied
spaces = 0
cars = 1


#calualtion to find percentage
percentage = (spaces/(cars)*100)

print (percentage,'% of spaces are occupied')

Upvotes: 0

Views: 255

Answers (5)

Sahith Kurapati
Sahith Kurapati

Reputation: 1715

This one line to calculate percentage occupied should be enough:

percentage = (sum(occupied_spaces)/len(occupied_spaces)) * 100

Since, you told you cannot use the sum function, you can do it in one line like so:

percentage = (occupied_spaces.count(1)/len(occupied_spaces)) * 100

Upvotes: 1

Hasibul Islam Polok
Hasibul Islam Polok

Reputation: 105

Simply count the number o 1's in the occupied_spaces list. Then divide the count number by the length of the occupied_spaces list and multiply with 100. for getting length of occupied_spaces use len(occupied_spaces)

Upvotes: 0

Vasilis G.
Vasilis G.

Reputation: 7844

As you can see in your code, you have two variables named spaces and cars, each of them given the values of 0 and 1 respectively. When you try to find the percentage of occupied spaces in your list, you divide spaces which is 0 with cars. This will always give you 0 as a result because you're not getting the actual number of cars in your list. To do that, you could do:

percentage = (occupied_spaces.count(1) / len(occupied_spaces)) * 100

Upvotes: 0

mushishi
mushishi

Reputation: 151

Another option is using the Python statistics module:

from statistics import mean 
print(mean(occupied_spaces)*100)

Upvotes: 0

Pavel Botsman
Pavel Botsman

Reputation: 863

You can calculate occupied spaces like so:

occupied_spaces = [1, 1, 1, 1, 1, 1, 0, 0, 0 ,0, 0] 
cars = occupied_spaces.count(1)
spaces = occupied_spaces.count(0)  # this variable is not used, so you can safely remove it
percentage = cars/len(occupied_spaces)

Upvotes: 0

Related Questions