[Tutor] another better way to do this ?

Alan Gauld alan.gauld at btinternet.com
Sun Jan 12 01:45:11 CET 2014


On 11/01/14 21:24, Roelof Wobben wrote:

> I have two strings a and b
>
> Now I have to check if the characters of b are all in a.
> But they do have to be in the same order.

I'm not sure exactly what you mean? Can you give some examples of
data that pass and that fail the criteria?

Your algorithm below might meet one definition of the spec but
its not valid code since it uses return but is not a function.

> length = len(b)
> start = 1
> while start < length :
>        check = a.find (b[start])
>        if check == -1 :
>              return False
>        start = start + 1
> return True

Problems I see are:
1) you start testing at b[1] not b[0]
2) you don't check if the letters are in the same sequence in a as in b
3) you probably could tidy it up using a for loop over b rather than 
indexing

> But according to the site this can be solved in a one-liner.

That depends on the spec.
And have you covered regular expressions? That is probably one
way to do a one-liner...

But just because you can do it in one line doesn't mean you
should. It's better for code to be readable than short.


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list