Attribute Functions exercise - My Solution vs. Given Solution

Hey all,

While going through the Attribute Functions exercise in Python3, I came up with the following solution that passed the test:

how_many_s = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]

for i in how_many_s:
  except AttributeError:

As I read the FAQ, it seemed like maybe others had done it a different way, so I checked the “Give me solution” answer which is:

for element in how_many_s:
  if hasattr(element, "count"):

Both of them work, so I was just curious about which method would be better to use in a real world scenario. Maybe I’m biased, but the way I did it seems a little cleaner and more straightforward? Any insight you all have is much appreciated. Thanks in advance!

There is the lesson and narrative to consider. Is the lesson explicitly about the hasattr() function? Then that would be what to use, for the sake of the lesson. That you explored the problem further and arrived at a different solution is no surprise. Many learners are curious, even precocious to point of exhausting all avenues.

Which solution is better? Sorry, no valuable insight to offer there. They both do what they set out to do. I think the second one is less brute force, though.

1 Like

Ah you’re right, I came back to this exercise after a break and neglected to read through it again. The point was to use hasattr().

And you’re absolutely right again, I’m constantly guilty of over-searching/thinking solution to a problem where the answer is usually much more straightforward than I’m expecting. Thanks for the quick response!

1 Like