'How can I verify the percentage? [closed]
cars = ('coupe', 'coupe', 'coupe', 'carbiolet', 'sedan')
x = cars.count("coupe")
y = len(cars)
Q: If the number of times the coupe element appears in the tuple cars is more than 45%, print "Too many." to the terminal. If not, print "You are set."
that means if x/y > 45%; I will have to print "Too many" else "You are set".
But I can't run it in the python program. Can anybody please help?
Solution 1:[1]
45% is the same as 45/100, that is, 0.45. So you could write:
>>> cars = ('coupe', 'coupe', 'coupe', 'carbiolet', 'sedan')
>>> x = cars.count("coupe")
>>> y = len(cars)
>>> x
3
>>> y
5
>>> threshold = 0.45 # 45% or you could also write 'threshold = 45/100'
>>> if x/y > threshold:
... print("Too many")
... else:
... print("You are set")
...
Too many
Solution 2:[2]
You already close to find out, just use if statement to check percentage.
You can do that as follows:
cars = ('coupe', 'coupe', 'coupe', 'carbiolet', 'sedan')
x = cars.count("coupe")
y = len(cars)
stat = 0.45 # %45
if x/y > stat:
print("Too many")
else:
print("You are set")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Eduardo Gomes |
Solution 2 | Furkan Ozalp |