Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can't understand the code
#1
The following code is a solution for a string-related problem:

for method in [str.isalnum, str.isalpha, str.isdigit, str.islower, str.isupper]:
    print any(method(c) for c in s)
Here, "s" is a string.
I'm not familiar with third brackets in for loop, nor how class methods are being called here and how "c" is being passed as a parameter to "method".

The same code can be written in the following way:

t = type(s)
for method in [t.isalnum, t.isalpha, t.isdigit, t.islower, t.isupper]:
    print any(method(c) for c in s)
Can anyone kindly tell me what's happening in these codes?

NB: The problem corresponding to the codes is from HackerRank
Reply
#2
you iterate over methods of class str
so in first iteration method is actually str.isalnum, i.e. method(с) is same as str.isalnum(с)

any() will return True if at least one of the elements in the argument (which is (method( c ) for c in s))is True
Reply
#3
Thanks for explaining!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unable to understand the meaning of the line of code. jahuja73 0 309 Jan-23-2024, 05:09 AM
Last Post: jahuja73
  Unable to understand how given code takes a fixed input value, without inputting. jahuja73 4 2,713 Jan-28-2021, 05:22 PM
Last Post: snippsat
  Don't understand example code from a textbook lil_fentanyl 1 1,844 Jan-25-2021, 07:02 PM
Last Post: nilamo
  Unable to understand a statement in an existing code ateestructural 1 2,236 Aug-01-2020, 09:38 PM
Last Post: deanhystad
  Trying to understand the python code spalisetty 2 1,879 Mar-16-2020, 08:11 AM
Last Post: javiertzr01
  I couldn't understand the output of the below code ravich129 1 1,934 Dec-12-2019, 06:24 AM
Last Post: sandeep_ganga
  can you understand why this code prints None? arcbal 2 2,768 Mar-13-2019, 02:57 AM
Last Post: arcbal
  Can someone help me please understand this code? Jayboii478 2 3,372 Mar-02-2019, 07:26 PM
Last Post: seco
  Don't understand why this quicksort code works lupoalberto 6 4,014 Mar-27-2018, 10:01 AM
Last Post: lupoalberto
  code to understand the script execution Skaperen 2 3,359 Jan-06-2018, 05:25 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020