Midterm Exam 2 Review Fall 2003: Count 'em up
Answers? Comments? Questions on Answers? Questions on Comments?
(Back to Fall2003 Midterm Review 2)
def countAs(string):
count=0
for letter in string:
if letter = = 'a":
count= count+1
print count
In programs for pictures, for example, we would say
"for p in getPixels(picture)"; we didn't say "for p in picture"; I think this program needs something like that, but I don't know what the equivilent of a pixel is in a string. What is each individual component called?
I don't know about that, because it said "for i in hello" and it printed fine...so maybe having "for letter in string" is ok too??
It seems like it should work, they're just different variables. If the program works in JES I assume it's right, or at least there's no huge errors like that.
| letter in string is just fine. Note, though, that I made this problem larger on the review... Mark Guzdial |
So, something like this for part b?
def countABC(string):
countA=0
countB=0
countC=0
for letter in string
if letter=="a":
countA=countA+1
if letter=="b":
countB=countB+1
if letter=="c":
countC==countC+1
print "Number of A's was",countA
print "Number of B's was",countB
print "Number of C's was",countC
Isn't there a java import module that finds text within a string without having to use a for loop array-style?
how about the followings
def countAs(string)
print string.count("a")
i thought that the count(something) function only worked for lists, not strings. is putting string as input making it a list?
Ok, so then part b would be this:
def countABC(string):
print "Number of A's is",string.count("a")
print "Number of B's is",string.count("b")
print "Number of C's is",string.count("c")
def countAs(string):
count = 0
for letter in string:
print letter
if letter == "a"
count = count + 1
print "I saw", count, "a's"
| Turns out that count is a method for strings, too. Mark Guzdial |
>>> string="abcabc"
>>> string.count("a")
2
So, on the exam, do we need to provide both programs (string.count() and the long one) or just one of them? I mean, for each part of the question.
>>So, on the exam, do we need to provide both programs (string.count() and the long one) or just one of them? I mean, for each part of the question.
WHAT THE HELL DO YOU THINK?
| Well, if the problem does end up on the test, you may want to be familiar with both parts. Lauren Biddle | |
Link to this Page