Midterm Exam 2 Review Spring 2003: Count 'em up
Comments? Concerns? Answers? Questions? Questions about Answers?
Back to Sp2003 Midterm Review 2
Did we learn this????
| You have done counts before (sourceIndex = sourceIndex + 1). You know IFs. From the example, you know how to use a FOR loop to go through the characters of a string. Yes, you can do this. Mark Guzdial |
FYI, here's the code we did in class this morning:
def countemup(string):
count = 0
for letter in string:
# print letter
if letter == "a":
count = count + 1
print "I saw",count,"a's"
def countemup2(alist):
count = 0
for number in alist:
print "I'm now adding",number,"to",count
count = count + number
print count
| Notice that neither of these, in itself, is the solution to any of these problems. But they're a start toward several. Mark Guzdial |
The 1st one seems to be correct. Is it incorrect because the program name is wromg?
def countAs(string):
count = 0
for letter in string:
print letter
if letter == "a":
count = count + 1
print "I saw",count,"a's"
Is this right? I'm guessing that the first one was wrong due to the name and the pound sign. If there's something else I'm missing, let me know. The function could have as input really any letters. So, I'm not sure if there's supposed to be something that excludes any other letters or says that it can't process the information given because it contains other letters. Otherwise, the program above works.
Rebecca Phillips
Oh, are we supposed to assume that the user knows to put the input (string) in quotes before hitting enter in JES? The program won't work without the quotes.
Rebecca Phillips
| My apologies – I forgot my own problem! I thought that I'd asked you to count the a's, b's, and c's – not just the a's. You're right – both mine and Rebecca's versions solve the problem. Mark Guzdial |
| You should know this for the final! Can you do this with map, reduce, or filter? Mark Guzdial |
Links to this Page