Udacity while loop question - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Udacity while loop question (/thread-4077.html) |
Udacity while loop question - liquidmetalrob - Jul-21-2017 Hi! I'm doing the Intro to Computer Science course on Udacity and I'm trying to: #Define a procedure, find_last, that takes as input # two strings, a search string and a target string, # and returns the last position in the search string # where the target string appears, or -1 if there # are no occurrences. # # Example: find_last('aaaa', 'a') returns 3 # Make sure your procedure has a return statement. This is my attempt, but it won't work. Can anyone explain what I did wrong? def find_last(text,s): x = -1 b = text[x] while b != s: x = x-1 return x RE: Udacity while loop question - Larz60+ - Jul-21-2017 the following line is not valid code b = text[x]what is this supposed to do? RE: Udacity while loop question - liquidmetalrob - Jul-21-2017 b = text[x] This is supposed to assign to b the letter of the string at position x, which is assigned to -1 at the top. I've tested it and it works though. text = 'abcabcabcabc' x = -1 b = text[x] print bThe result that is printed is 'c'. RE: Udacity while loop question - buran - Jul-21-2017 (Jul-21-2017, 01:00 PM)Larz60+ Wrote: the following line is not valid code Actually it is :-) >>> text = 'sometext' >>> x=-1 >>> b=text[x] >>> b 't' >>> RE: Udacity while loop question - ichabod801 - Jul-21-2017 The point is that when you change x, b is not changed. So you are always testing the last letter of the string (b). You want to test directly on text[x]. However, that is only going to work for single character search strings. If you have a two character search string, like find_last('aababcabcd', 'ab'), it will never match. You might want to look at the startswith method of strings. RE: Udacity while loop question - sparkz_alot - Jul-21-2017 And stop using single letter variables. RE: Udacity while loop question - nilamo - Jul-21-2017 Luckily, that's actually already built into python. >>> find_last = lambda haystack, needle: haystack.rfind(needle) >>> find_last("ababababspam", "ab") 6 >>> find_last("ababababspam", "cat") -1 >>> help(str.rfind) Help on method_descriptor: rfind(...) S.rfind(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. |