I’m taking a programming course and the final is tomorrow. I’m taking a practice final and I’m stuck on this question:
Given the following function heading
def firstOccur(ch, s):
Write a method that returns the first occurrence of the character stored in ch in the string s. If the character is found in the string, your function should return it’s position. Thus if s = ‘abcdefg’ and the value of ch is ‘d’, your program would return 3. If the character is not found in the string, your program should return -1.
I gave it a try, but no luck. This is where I’m at:
def firstOccur(ch, s):
b = len(s)
n = 0
for c in range(b):
d = ch[0]
e = s[c]
if d != e:
return(-1)
else:
while d != e:
n = n+1
return(n)
def main():
a = firstOccur('d', 'abcdefg')
print(a)
main()
The main function is just to test the firstOccur function. I have no idea where to go from here, or if I’m even on the right path. Help?
Okay, let’s break this down. You’re given a list of characters, aka a string. So the task is to iterate (=loop) over this list until you hit the first occurance of your search key within the list. Once you hit the occurance, return the position of it, which also breaks the loop. If you finish the loop without finding the search key, return
-1(BTW;Nonewould make more sense in Python).Python offers you a builtin function called
enumeratethat takes a list and returns a list of tuples with element index and the element itself. i.e.or
“abcd”
becomes
This is a nobrainer.
If you’re not allowed to use enumerate, well there’s the “long” road as well: