[Tutor] Python strings example
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Apr 27 04:36:42 EDT 2021
On 27/04/2021 03:49, Manprit Singh wrote:
> If you look at Peter's solution, you can see it is using two generator
> expressions(I mean to say there is a utilization of two for loops that
> increases complexity) what practices should be adopted in such cases ? the
> one done by Peter or the one done by me ?
The complexity is not much different since your function
has 4 assignments, one for-loop and two boolean expressions.
Peter's has 2 generator expressions and one boolean expression.
Peter's also has a more direct statement of the logic
which makes it easier to read and understand. It is
also (probably) more efficient for large strings
since any() will stop at the first occurrence
whereas your loop tests every character.
We can avoid that in your function but only by adding
yet another test:
def str_chk(word_tochk):
dig = False
alpha = False
for ele in word_tochk:
dig = dig or ele.isdigit()
alpha = alpha or ele.isalpha()
if dig and alpha: return True
return False
But that then adds more complexity.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list