Midterm Exam 2 Review Spring 2006: Count 'em up 2
is this close to one of the answers:
def count(string):
c=0
for i in string:
if i =="a":
c = c +1
print c
| It should count the As and return and not print the amount. But otherwise, yes. -poof #10 |
so if this is close to the answer to (a) or (b) what would be a close answer to (c). how would you avoid writing if statement 26 times?
| B needs another counter, but it uses the same principle. For part C, the answer is similar to what someone posted for part A. It should print out each count for every letter. Think about a way to compare the string with the alphabet. -poof #10 |
if you did want to print the number of As in the string, do you line up the print c with "for" or write it inside the for and if statements? I know that if you put it inside the for and if statement, then it will return
1
2
3
(assuming that there are 3 A's in the string)
And that if you put it in the same indentation as "for" then it will only print out 3.
def countAs(string):
c=0
for i in string:
if i =="a":
c = c +1
print c #or put it here
print c
(b)def countAs(string):
c=0
e=0
for i in string:
if i=="a":
c=c+1
if i=="e":
e=e+1
print c
print e
this one seems like it is working for (c)
def count(string):
c=0
for i in string:
string.count(i)
c = c + 1
print c
None of these posted functions take capital A's and E's into account, shouldn't that be a concern?
for i in string
if i == "a" or i == "A":
Here is what I did for part c, is that correct? It works for me.
def alpha(string):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for i in alphabet:
c = 0
potato = string.count(str(i))
c = c + potato
print "There are " + str(c) + " " + str(i) + "'s"
After looking at my code the first definition of c is unecessary, make the second definition of c "c = 0 + potato" instead.
even quicker
def countAs(foo):
alpha = "abcdefghijklmnopqrstuvwxyz"
for i in alpha:
a = foo.count(i)
print "there are " + str(a) + " " + str(i) + "'s"
Part A
def countAs(string):
x = string.count('a')
y = string.count('A')
print x+y
Part B
def countAE(string):
x = string.count('a')
y = string.count('A')
print x+y
z = string.count('b')
w = string.count('B')
print z+w
Would these two work. I don't see why you need an if statement on some of the things posted above.
Link to this Page