saxon7/Coder_Coding
0
1import streamlit as st2 3def check_code(code, test_cases):4 """5 Executes the given code and checks it against the provided test cases.6 7 Args:8 code: The code to execute as a string.9 test_cases: A list of dictionaries, where each dictionary has the keys:10 "input": The input to the function.11 "expected_output": The expected output of the function.12 13 Returns:14 A list of booleans indicating whether each test case passed.15 """16 results = []17 # Define the scope for the user's code to prevent variable name conflicts18 exec_scope = {}19 try:20 # Execute the user's code21 exec(code, exec_scope)22 # Get the function from the executed code23 user_function = exec_scope.get('solution') # Assuming the function is named 'solution'24 if not user_function:25 raise ValueError("No function named 'solution' found in the code.")26 27 for test_case in test_cases:28 try:29 # Run the user's function with the test case input30 output = user_function(test_case["input"])31 # Compare the output to the expected output32 results.append(output == test_case["expected_output"])33 except Exception as e:34 print(f"Error during test case execution: {e}")35 results.append(False)36 except Exception as e:37 print(f"Error during code execution: {e}")38 st.error(f"Error in your code:\n{e}")39 return [False] * len(test_cases) # All tests fail if there's an error40 41 return results42 43def main():44 st.title("Basic Coding Challenge -1")45 46 # Programming question47 st.write("**Question:** Write a function to find the sum of all even numbers in a list.")48 49 # Code area50 code = st.text_area("Write your code here:", value="""51def solution(numbers):52 # Your code here53 pass54""")55 56 # Run and check buttons57 if st.button("Run"):58 # Test cases59 test_cases = [60 {"input": [1, 2, 3, 4, 5], "expected_output": 6},61 {"input": [2, 4, 6, 8], "expected_output": 20},62 {"input": [1, 3, 5, 7], "expected_output": 0},63 ]64 results = check_code(code, test_cases)65 66 # Display results67 st.subheader("Test Case Results:")68 for i, result in enumerate(results):69 if result:70 st.success(f"Test case {i+1}: Passed")71 else:72 st.error(f"Test case {i+1}: Failed")73if __name__=="__main__":74 main()75 76 