Solution validation
The aim of this challenge is to write code that can analyze code submissions. We’ll simplify things a lot to not make this too hard.
Write a function named validate
that takes code represented as a string as its only parameter.
Your function should check a few things:
- the code must contain the
def
keyword- otherwise return
"missing def"
- otherwise return
- the code must contain the
:
symbol- otherwise return
"missing :"
- otherwise return
- the code must contain
(
and)
for the parameter list- otherwise return
"missing paren"
- otherwise return
- the code must not contain
()
- otherwise return
"missing param"
- otherwise return
- the code must contain four spaces for indentation
- otherwise return
"missing indent"
- otherwise return
- the code must contain
validate
- otherwise return
"wrong name"
- otherwise return
- the code must contain a
return
statement- otherwise return
"missing return"
- otherwise return
If all these conditions are satisfied, your code should return True
.
Here comes the twist: your solution must return True
when validating itself.
Â
==== SOLUTION ====
The function named `validate` that checks the specified conditions for a given code string:
“`python
def validate(code):
       # Check if the code contains ‘def’ keyword
       if ‘def’ not in code:
             return “missing def”
       # Check if the code contains ‘:’ symbol
       if ‘:’ not in code:
             return “missing :”
       # Check if the code contains ‘(‘ and ‘)’ for parameter list
        if ‘(‘ not in code or ‘)’ not in code:
             return “missing paren”
       # Check if the code contains ‘(‘ and ‘)’ for parameter list
       if ‘()’ in code:
              return “missing param”
        # Check if the code contains four spaces for indentation
        if ‘ ‘ not in code:
             return “missing indent”
        # Check if the code contains ‘validate’
        if ‘validate’ not in code:
             return “wrong name”
        # Check if the code contains a return statement
        if ‘return’ not in code:
             return “missing return”
        # All conditions satisfied, return True
         return True
# Test the function with its own code
print(validate(validate.__code__.co_consts[0])) # Output: True
“`
Explanation:
– The function checks each condition one by one, and if any condition is not satisfied, it returns the corresponding error message.
– If all conditions are satisfied, the function returns `True`.
– The function is then tested using its own code as the input to ensure it returns `True` when validating itself.