I would like to see if it is possible to run a list of functions in a function. The closest I could find was a loop through the entire module. I want to use only the pre-selected list of functions.
Here is my original problem:
- Given the string, check each letter to see if any of the 5 tests have been completed.
- If at least 1 letter passes the test, return True.
- If all letters in the string do not pass the test, return False.
- For each letter in the string, we will check these functions: isalnum (), isalpha (), isdigit (), islower (), isupper ()
- The result of each test should be printed on different lines.
Input example
qA2
Sample output (should print for individual lines, True, if at least one letter passes, or false - all letters do not pass each test):
True True True True True
I wrote this for one test. Of course, I could just write 5 different sets of code, but that seems ugly. Then I began to wonder if I could just skip all the tests they ask.
Code for only one test:
raw = 'asdfaa3fa' counter = 0 for i in xrange(len(raw)): if raw[i].isdigit() == True: ## This line is where I'd loop in diff func's counter = 1 print True break if counter == 0: print False
My unsuccessful attempt to start a loop with all the tests:
raw = 'asdfaa3fa' lst = [raw[i].isalnum(),raw[i].isalpha(),raw[i].isdigit(),raw[i].islower(),raw[i].isupper()] counter = 0 for f in range(0,5): for i in xrange(len(raw)): if lst[f] == True: ## loop through f, which then loops through i print lst[f] counter = 1 print True break if counter == 0: print False
So, how do I fix this code to follow all the rules there?
Using the information from all comments - this code complies with the above rules, also dynamically iterates over each method.
raw = 'ABC' functions = [str.isalnum, str.isalpha, str.isdigit, str.islower, str.isupper] for func in functions: print any(func(letter) for letter in raw)
getattr method (I think this is called the introspection method?)
raw = 'ABC' meths = ['isalnum', 'isalpha', 'isdigit', 'islower', 'isupper'] for m in meths: print any(getattr(c,m)() for c in raw)
List comprehension approach:
from __future__ import print_function