GeminiFan207 commited on
Commit
cff74af
·
verified ·
1 Parent(s): 7a92675

Create code_generate.py

Browse files
Files changed (1) hide show
  1. code_generate.py +106 -0
code_generate.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Optional
2
+ import random
3
+
4
+ class CodeGenerator:
5
+ """A class to generate function code in multiple programming languages."""
6
+
7
+ # Supported languages and their templates with proper indentation
8
+ TEMPLATES: Dict[str, str] = {
9
+ "python": "def {func_name}({params}):\n {body}",
10
+ "javascript": "function {func_name}({params}) {{\n {body}\n}}",
11
+ "cpp": "{ret_type} {func_name}({params}) {{\n {body}\n}}",
12
+ "java": "public class Main {{\n public static {ret_type} {func_name}({params}) {{\n {body}\n }}\n}}",
13
+ "csharp": "public class Program {{\n public static {ret_type} {func_name}({params}) {{\n {body}\n }}\n}}"
14
+ }
15
+
16
+ # Configuration data
17
+ FUNCTION_NAMES: List[str] = ["calculate", "processData", "computeValue", "generateOutput"]
18
+ DEFAULT_PARAMS: Dict[str, str] = {
19
+ "python": "x: int, y: int",
20
+ "javascript": "x, y",
21
+ "cpp": "int x, int y",
22
+ "java": "int x, int y",
23
+ "csharp": "int x, int y"
24
+ }
25
+ RETURN_TYPES: Dict[str, str] = {
26
+ "cpp": "int",
27
+ "java": "int",
28
+ "csharp": "int",
29
+ "python": " -> int", # Type hint for Python
30
+ "javascript": "" # No explicit return type
31
+ }
32
+ DEFAULT_BODY: str = "return x + y;"
33
+
34
+ def __init__(self, seed: Optional[int] = None):
35
+ """Initialize generator with optional random seed."""
36
+ if seed is not None:
37
+ random.seed(seed)
38
+
39
+ def get_supported_languages(self) -> List[str]:
40
+ """Return list of supported languages."""
41
+ return list(self.TEMPLATES.keys())
42
+
43
+ def generate_code(
44
+ self,
45
+ language: str,
46
+ func_name: Optional[str] = None,
47
+ params: Optional[str] = None,
48
+ body: Optional[str] = None,
49
+ ret_type: Optional[str] = None
50
+ ) -> Optional[str]:
51
+ """
52
+ Generate code for the specified language with customizable components.
53
+
54
+ Args:
55
+ language: Target programming language
56
+ func_name: Optional custom function name
57
+ params: Optional custom parameters
58
+ body: Optional custom function body
59
+ ret_type: Optional custom return type
60
+
61
+ Returns:
62
+ Generated code string or None if language is unsupported
63
+ """
64
+ if language not in self.TEMPLATES:
65
+ return None
66
+
67
+ # Use provided values or defaults
68
+ selected_func_name = func_name or random.choice(self.FUNCTION_NAMES)
69
+ selected_params = params or self.DEFAULT_PARAMS.get(language, "")
70
+ selected_body = self._normalize_body(body or self.DEFAULT_BODY, language)
71
+ selected_ret_type = ret_type or self.RETURN_TYPES.get(language, "")
72
+
73
+ try:
74
+ return self.TEMPLATES[language].format(
75
+ func_name=selected_func_name,
76
+ params=selected_params,
77
+ body=selected_body,
78
+ ret_type=selected_ret_type
79
+ )
80
+ except KeyError as e:
81
+ raise ValueError(f"Missing template component: {str(e)}")
82
+ except Exception as e:
83
+ raise RuntimeError(f"Code generation failed: {str(e)}")
84
+
85
+ def _normalize_body(self, body: str, language: str) -> str:
86
+ """Normalize function body based on language requirements."""
87
+ body = body.strip()
88
+ if language in {"cpp", "java", "csharp"} and not body.endswith(";"):
89
+ return body + ";"
90
+ if language == "python":
91
+ return body.replace(";", "") # Python doesn't use semicolons
92
+ return body
93
+
94
+ def main():
95
+ """Demonstrate code generation for all supported languages."""
96
+ generator = CodeGenerator(seed=42) # Fixed seed for reproducibility
97
+
98
+ print("Supported languages:", generator.get_supported_languages())
99
+ print("\nGenerated code examples:")
100
+
101
+ for lang in generator.get_supported_languages():
102
+ code = generator.generate_code(lang)
103
+ print(f"\n{lang.upper()}:\n{code}")
104
+
105
+ if __name__ == "__main__":
106
+ main()