Reputation:
I am having trouble figuring out how to calculate the percent of certain letters within an input using a "for loop". I want to calculate the amount of X's and Y's a string has, and have the output come out as a percent but I want to use a "for loop" for it.
This is what I was able to do so far:
def percent(string):
counter = 0
for stuff in string:
if "X" in string:
counter = counter + 1
if "Y" in string:
counter = counter + 1
XY_percent = (counter / len(string)) * 100
return "{}%".format(int(XY_percent))
I only want to use "for loops" for this.
Upvotes: 0
Views: 3805
Reputation: 60143
if "X" in string
is the problem... this is always True
as long as there's at least one "X"
in the string.
Instead, test each letter individually. (I renamed stuff
to letter
for clarity.)
def percent(text):
counter = 0
for letter in text:
if letter == "X" or letter == "Y":
counter += 1
return "{}%".format(int(counter / len(text) * 100))
print(percent("XYZZZ")) # 40%
EDIT
Using list comprehension and @wim's tip about formatting percentages:
def percent(text):
return "{:.0%}".format(sum(letter in "XY" for letter in text) / len(text))
Upvotes: 1
Reputation: 15071
This is what you need, note that indentation is important...
def percent(string):
counter = 0
for stuff in string:
if stuff == "X" or stuff == "Y":
counter += 1
XY_percent = (counter / len(string)) * 100
return "{}%".format(int(XY_percent))
You could also do it more concisely as
XY_percent = sum(c in 'XY' for c in string) / len(string)
Upvotes: 1