pyvra 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyvra/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """pyvra: a small CLI for listing, displaying, and copying Python programs."""
2
+
3
+ __version__ = "1.0.0"
pyvra/cli.py ADDED
@@ -0,0 +1,142 @@
1
+
2
+ """Command-line interface for pyvra."""
3
+
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import pyperclip
8
+
9
+
10
+ PROGRAMS_DIR = Path(__file__).resolve().parent / "programs"
11
+
12
+
13
+ def discover_programs():
14
+ """Discover all Python programs recursively and assign numbers."""
15
+
16
+ if not PROGRAMS_DIR.exists():
17
+ return {}
18
+
19
+ files = sorted(
20
+ (
21
+ path
22
+ for path in PROGRAMS_DIR.rglob("*.py")
23
+ if path.is_file() and path.name != "__init__.py"
24
+ ),
25
+ key=lambda path: str(path.relative_to(PROGRAMS_DIR)).lower(),
26
+ )
27
+
28
+ return {
29
+ str(index): path
30
+ for index, path in enumerate(files, start=1)
31
+ }
32
+
33
+
34
+ def list_programs(programs):
35
+ """Display all available programs."""
36
+
37
+ if not programs:
38
+ print("\nNo Python programs found.")
39
+ print(f"Add .py files to: {PROGRAMS_DIR}\n")
40
+ return
41
+
42
+ print("\nAvailable Python Programs:\n")
43
+
44
+ for number, path in programs.items():
45
+ print(f"[{number}] {path.name}")
46
+
47
+ print()
48
+
49
+
50
+ def get_program(programs, choice):
51
+ """Retrieve a program using its assigned number."""
52
+
53
+ path = programs.get(choice)
54
+
55
+ if path is None:
56
+ print(
57
+ f"Program '{choice}' not found. "
58
+ "Run 'pyvra list' to see available programs."
59
+ )
60
+
61
+ return path
62
+
63
+
64
+ def show_program(programs, choice):
65
+ """Display the source code of a program."""
66
+
67
+ path = get_program(programs, choice)
68
+
69
+ if path is None:
70
+ return
71
+
72
+ try:
73
+ code = path.read_text(encoding="utf-8")
74
+
75
+ print(f"\n========== {path.name} ==========\n")
76
+ print(code, end="" if code.endswith("\n") else "\n")
77
+
78
+ except OSError as error:
79
+ print(f"Could not read {path.name}: {error}")
80
+
81
+
82
+ def copy_program(programs, choice):
83
+ """Copy a program's source code to the clipboard."""
84
+
85
+ path = get_program(programs, choice)
86
+
87
+ if path is None:
88
+ return
89
+
90
+ try:
91
+ code = path.read_text(encoding="utf-8")
92
+ pyperclip.copy(code)
93
+
94
+ print(f"\nCopied {path.name} to clipboard.\n")
95
+
96
+ except OSError as error:
97
+ print(f"Could not read {path.name}: {error}")
98
+
99
+ except pyperclip.PyperclipException as error:
100
+ print(f"Could not access the clipboard: {error}")
101
+ print("On Linux, install a clipboard utility such as xclip or xsel.")
102
+
103
+
104
+ def print_help():
105
+ """Display CLI usage instructions."""
106
+
107
+ print(
108
+ "\nUsage:\n"
109
+ " pyvra list List all Python programs\n"
110
+ " pyvra 1 Display program number 1\n"
111
+ " pyvra copy 1 Copy program number 1 to clipboard\n"
112
+ " pyvra help Show this help message\n"
113
+ )
114
+
115
+
116
+ def main():
117
+ """CLI entry point."""
118
+
119
+ args = sys.argv[1:]
120
+
121
+ if not args or args[0] in {"help", "--help", "-h"}:
122
+ print_help()
123
+ return
124
+
125
+ programs = discover_programs()
126
+
127
+ if args[0] == "list":
128
+ list_programs(programs)
129
+
130
+ elif args[0] == "copy":
131
+ if len(args) < 2:
132
+ print("Please provide a program number. Example: pyvra copy 1")
133
+ return
134
+
135
+ copy_program(programs, args[1])
136
+
137
+ else:
138
+ show_program(programs, args[0])
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
@@ -0,0 +1,255 @@
1
+ # Assignment 8
2
+
3
+ """
4
+ AI Code Generator & Code Reviewer
5
+ ---------------------------------
6
+ A Streamlit dashboard that uses the OpenAI or Google Gemini API to:
7
+ * Generate source code from a plain-English requirement
8
+ * Review existing code (bugs, security, performance, style, best practices)
9
+ * Do both in one go: generate code, then automatically review it
10
+
11
+ Run: streamlit run code_assistant.py
12
+ """
13
+
14
+ import os
15
+ import re
16
+ from datetime import datetime
17
+
18
+ import streamlit as st
19
+
20
+ # --------------------------------------------------------------------------
21
+ # Prompts
22
+ # --------------------------------------------------------------------------
23
+ GEN_SYSTEM = (
24
+ "You are an expert software engineer. Write clean, correct, well-commented, "
25
+ "production-quality code that follows the idioms and best practices of the "
26
+ "requested language. Include input validation and error handling where sensible."
27
+ )
28
+
29
+ REVIEW_SYSTEM = (
30
+ "You are a strict but constructive senior code reviewer. Review code for "
31
+ "correctness, security, performance, readability and maintainability. "
32
+ "Be specific: quote the problematic line or function and explain the fix."
33
+ )
34
+
35
+ LANGUAGES = ["Python", "JavaScript", "TypeScript", "Java", "C++", "C", "C#", "Go", "Rust", "SQL"]
36
+
37
+ MODELS = {
38
+ "OpenAI": ["gpt-4o-mini", "gpt-4o", "gpt-4.1-mini"],
39
+ "Gemini": ["gemini-2.5-flash", "gemini-2.0-flash", "gemini-2.5-pro"],
40
+ }
41
+
42
+ REVIEW_FORMAT = """
43
+ Review the following {language} code and respond in Markdown with exactly these sections:
44
+
45
+ ## Summary
46
+ One short paragraph on what the code does and its overall quality.
47
+
48
+ ## Score
49
+ An overall quality score out of 10 with a one-line justification.
50
+
51
+ ## Bugs & Logic Errors
52
+ Bullet list (write "None found" if clean). Include severity: High / Medium / Low.
53
+
54
+ ## Security Issues
55
+ Bullet list (write "None found" if clean).
56
+
57
+ ## Performance
58
+ Bullet list of inefficiencies and how to improve them.
59
+
60
+ ## Readability & Style
61
+ Naming, structure, comments, and language conventions.
62
+
63
+ ## Best-Practice Suggestions
64
+ Design, testing, error handling, documentation.
65
+
66
+ ## Improved Code
67
+ A single fenced code block with the corrected/improved version of the code.
68
+
69
+ CODE TO REVIEW:
70
+ ```{lang_tag}
71
+ {code}
72
+ ```
73
+ """.strip()
74
+
75
+
76
+ def gen_prompt(language, requirement, extras):
77
+ return f"""
78
+ Write {language} code for the following requirement.
79
+
80
+ Requirement:
81
+ {requirement}
82
+
83
+ Additional instructions: {extras or "None"}
84
+
85
+ Rules:
86
+ - Return the complete code in ONE fenced code block.
87
+ - After the code block, add a short "How it works" explanation and a usage example.
88
+ """.strip()
89
+
90
+
91
+ # --------------------------------------------------------------------------
92
+ # LLM calls
93
+ # --------------------------------------------------------------------------
94
+ def call_openai(api_key, model, system, prompt, temperature):
95
+ from openai import OpenAI
96
+
97
+ client = OpenAI(api_key=api_key)
98
+ resp = client.chat.completions.create(
99
+ model=model,
100
+ temperature=temperature,
101
+ messages=[
102
+ {"role": "system", "content": system},
103
+ {"role": "user", "content": prompt},
104
+ ],
105
+ )
106
+ return resp.choices[0].message.content
107
+
108
+
109
+ def call_gemini(api_key, model, system, prompt, temperature):
110
+ from google import genai
111
+ from google.genai import types
112
+
113
+ client = genai.Client(api_key=api_key)
114
+ resp = client.models.generate_content(
115
+ model=model,
116
+ contents=prompt,
117
+ config=types.GenerateContentConfig(system_instruction=system, temperature=temperature),
118
+ )
119
+ return resp.text
120
+
121
+
122
+ def ask(provider, api_key, model, system, prompt, temperature):
123
+ fn = call_openai if provider == "OpenAI" else call_gemini
124
+ return fn(api_key, model, system, prompt, temperature)
125
+
126
+
127
+ def extract_code(markdown_text):
128
+ """Return the first fenced code block's contents (or the whole text if none)."""
129
+ match = re.search(r"```[\w+#-]*\n(.*?)```", markdown_text, re.DOTALL)
130
+ return match.group(1).strip() if match else markdown_text.strip()
131
+
132
+
133
+ def review_code(provider, api_key, model, language, code, temperature):
134
+ prompt = REVIEW_FORMAT.format(language=language, lang_tag=language.lower(), code=code)
135
+ return ask(provider, api_key, model, REVIEW_SYSTEM, prompt, temperature)
136
+
137
+
138
+ # --------------------------------------------------------------------------
139
+ # UI
140
+ # --------------------------------------------------------------------------
141
+ st.set_page_config(page_title="AI Code Generator & Reviewer", page_icon="🧑‍💻", layout="wide")
142
+
143
+ for key in ("generated", "review", "history"):
144
+ if key not in st.session_state:
145
+ st.session_state[key] = [] if key == "history" else ""
146
+
147
+ with st.sidebar:
148
+ st.header("⚙️ Settings")
149
+ provider = st.selectbox("AI Provider", list(MODELS.keys()))
150
+ model = st.selectbox("Model", MODELS[provider])
151
+ env_var = "OPENAI_API_KEY" if provider == "OpenAI" else "GEMINI_API_KEY"
152
+ api_key = st.text_input(
153
+ f"{provider} API Key",
154
+ type="password",
155
+ value=os.getenv(env_var, ""),
156
+ help=f"Or set the {env_var} environment variable.",
157
+ )
158
+ temperature = st.slider("Creativity (temperature)", 0.0, 1.0, 0.2, 0.1)
159
+
160
+ st.divider()
161
+ st.subheader("🕘 History")
162
+ if st.session_state.history:
163
+ for i, h in enumerate(reversed(st.session_state.history)):
164
+ if st.button(f"{h['time']} · {h['mode']}", key=f"h{i}"):
165
+ st.session_state.generated = h["generated"]
166
+ st.session_state.review = h["review"]
167
+ else:
168
+ st.caption("Your runs will appear here.")
169
+
170
+ st.title("🧑‍💻 AI Code Generator & Code Reviewer")
171
+ st.caption("Generate code from a requirement, review existing code, or do both in one step.")
172
+
173
+ mode = st.radio(
174
+ "Mode",
175
+ ["Generate Code", "Review Code", "Generate + Review"],
176
+ horizontal=True,
177
+ )
178
+
179
+ language = st.selectbox("Language", LANGUAGES)
180
+ left, right = st.columns([1, 1.3], gap="large")
181
+
182
+ with left:
183
+ st.subheader("Input")
184
+ requirement, extras, code_input = "", "", ""
185
+
186
+ if mode in ("Generate Code", "Generate + Review"):
187
+ requirement = st.text_area(
188
+ "What should the code do?",
189
+ height=170,
190
+ placeholder="e.g. A function that validates an email address and a CLI to test it",
191
+ )
192
+ extras = st.text_input("Extra instructions (optional)", placeholder="e.g. use OOP, add type hints")
193
+
194
+ if mode == "Review Code":
195
+ uploaded = st.file_uploader("Upload a source file (optional)", type=None)
196
+ default_text = uploaded.read().decode("utf-8", errors="ignore") if uploaded else ""
197
+ code_input = st.text_area("Paste code to review", value=default_text, height=320)
198
+
199
+ run = st.button("🚀 Run", type="primary", use_container_width=True)
200
+
201
+ with right:
202
+ st.subheader("Output")
203
+
204
+ if run:
205
+ if not api_key:
206
+ st.error("Please enter your API key in the sidebar.")
207
+ elif mode != "Review Code" and not requirement.strip():
208
+ st.warning("Please describe the code you want.")
209
+ elif mode == "Review Code" and not code_input.strip():
210
+ st.warning("Please paste or upload some code to review.")
211
+ else:
212
+ try:
213
+ generated, review = "", ""
214
+ if mode in ("Generate Code", "Generate + Review"):
215
+ with st.spinner("Generating code..."):
216
+ generated = ask(provider, api_key, model, GEN_SYSTEM,
217
+ gen_prompt(language, requirement, extras), temperature)
218
+ if mode == "Generate + Review":
219
+ with st.spinner("Reviewing generated code..."):
220
+ review = review_code(provider, api_key, model, language,
221
+ extract_code(generated), temperature)
222
+ if mode == "Review Code":
223
+ with st.spinner("Reviewing code..."):
224
+ review = review_code(provider, api_key, model, language,
225
+ code_input, temperature)
226
+
227
+ st.session_state.generated, st.session_state.review = generated, review
228
+ st.session_state.history.append({
229
+ "time": datetime.now().strftime("%H:%M:%S"),
230
+ "mode": mode,
231
+ "generated": generated,
232
+ "review": review,
233
+ })
234
+ except Exception as e:
235
+ st.error(f"API error: {e}")
236
+
237
+ gen, rev = st.session_state.generated, st.session_state.review
238
+ if gen or rev:
239
+ tabs = st.tabs([t for t, v in (("💻 Generated Code", gen), ("🔍 Code Review", rev)) if v])
240
+ idx = 0
241
+ if gen:
242
+ with tabs[idx]:
243
+ st.markdown(gen)
244
+ ext = {"Python": "py", "JavaScript": "js", "TypeScript": "ts", "Java": "java",
245
+ "C++": "cpp", "C": "c", "C#": "cs", "Go": "go", "Rust": "rs", "SQL": "sql"}[language]
246
+ st.download_button("⬇️ Download code", extract_code(gen),
247
+ file_name=f"generated_code.{ext}", use_container_width=True)
248
+ idx += 1
249
+ if rev:
250
+ with tabs[idx]:
251
+ st.markdown(rev)
252
+ st.download_button("⬇️ Download review (.md)", rev,
253
+ file_name="code_review.md", use_container_width=True)
254
+ else:
255
+ st.info("Choose a mode, fill in the input and click **Run**.")
@@ -0,0 +1,229 @@
1
+ # Assignment 7
2
+
3
+ """
4
+ AI Software Documentation Generator
5
+ -----------------------------------
6
+ A Streamlit dashboard that uses the OpenAI or Google Gemini API to generate:
7
+ * Software Requirement Specification (SRS, IEEE 830 style)
8
+ * User Stories with acceptance criteria
9
+ * Software / Technical Documentation
10
+
11
+ Run: streamlit run app.py
12
+ """
13
+
14
+ import os
15
+ from datetime import datetime
16
+
17
+ import streamlit as st
18
+
19
+ # --------------------------------------------------------------------------
20
+ # Prompt templates
21
+ # --------------------------------------------------------------------------
22
+ SYSTEM_PROMPT = (
23
+ "You are a senior software analyst and technical writer. "
24
+ "You produce clear, well-structured, professional documents in Markdown. "
25
+ "Be specific and realistic. Do not invent facts about the client; "
26
+ "where information is missing, make sensible, clearly stated assumptions."
27
+ )
28
+
29
+ DOC_TEMPLATES = {
30
+ "SRS (Software Requirement Specification)": """
31
+ Write a complete Software Requirement Specification (IEEE 830 style) with these sections:
32
+ 1. Introduction (Purpose, Scope, Definitions/Acronyms, References, Overview)
33
+ 2. Overall Description (Product Perspective, Product Functions, User Classes,
34
+ Operating Environment, Constraints, Assumptions and Dependencies)
35
+ 3. Specific Requirements
36
+ 3.1 Functional Requirements (numbered, e.g. FR-1, FR-2, each testable)
37
+ 3.2 Non-Functional Requirements (Performance, Security, Usability,
38
+ Reliability, Scalability, Maintainability)
39
+ 3.3 External Interface Requirements (User, Hardware, Software, Communication)
40
+ 4. System Models (use-case list and a data-flow description)
41
+ 5. Appendix (Open issues / Future enhancements)
42
+ """,
43
+ "User Stories": """
44
+ Write a set of user stories grouped by epic/feature.
45
+ For each story use the format:
46
+ **US-<n>: <title>**
47
+ As a <role>, I want <goal>, so that <benefit>.
48
+ - Priority: High / Medium / Low (MoSCoW)
49
+ - Story points: (Fibonacci estimate)
50
+ - Acceptance Criteria: 3-5 bullets in Given/When/Then style
51
+ Finish with a short table summarising all stories (ID, Title, Priority, Points).
52
+ """,
53
+ "Software Documentation": """
54
+ Write technical software documentation with these sections:
55
+ 1. Overview and Objectives
56
+ 2. System Architecture (components, tech stack, and a Mermaid diagram)
57
+ 3. Module / Component Description
58
+ 4. Data Design (main entities and relationships)
59
+ 5. API / Interface Description (sample endpoints with request/response)
60
+ 6. Installation and Setup Guide
61
+ 7. User Guide (main workflows)
62
+ 8. Testing Strategy
63
+ 9. Deployment and Maintenance Notes
64
+ 10. Future Scope
65
+ """,
66
+ }
67
+
68
+ MODELS = {
69
+ "OpenAI": ["gpt-4o-mini", "gpt-4o", "gpt-4.1-mini"],
70
+ "Gemini": ["gemini-2.5-flash", "gemini-2.0-flash", "gemini-2.5-pro"],
71
+ }
72
+
73
+
74
+ def build_prompt(doc_type, name, description, users, features, tech, detail):
75
+ return f"""
76
+ Project name: {name}
77
+
78
+ Project description:
79
+ {description}
80
+
81
+ Target users: {users or "Not specified"}
82
+ Key features: {features or "Not specified"}
83
+ Preferred technology / constraints: {tech or "Not specified"}
84
+ Level of detail: {detail}
85
+
86
+ TASK:
87
+ {DOC_TEMPLATES[doc_type]}
88
+
89
+ Return only the document in clean Markdown.
90
+ """.strip()
91
+
92
+
93
+ # --------------------------------------------------------------------------
94
+ # LLM calls
95
+ # --------------------------------------------------------------------------
96
+ def call_openai(api_key, model, prompt, temperature):
97
+ from openai import OpenAI
98
+
99
+ client = OpenAI(api_key=api_key)
100
+ resp = client.chat.completions.create(
101
+ model=model,
102
+ temperature=temperature,
103
+ messages=[
104
+ {"role": "system", "content": SYSTEM_PROMPT},
105
+ {"role": "user", "content": prompt},
106
+ ],
107
+ )
108
+ return resp.choices[0].message.content
109
+
110
+
111
+ def call_gemini(api_key, model, prompt, temperature):
112
+ from google import genai
113
+ from google.genai import types
114
+
115
+ client = genai.Client(api_key=api_key)
116
+ resp = client.models.generate_content(
117
+ model=model,
118
+ contents=prompt,
119
+ config=types.GenerateContentConfig(
120
+ system_instruction=SYSTEM_PROMPT,
121
+ temperature=temperature,
122
+ ),
123
+ )
124
+ return resp.text
125
+
126
+
127
+ def generate(provider, api_key, model, prompt, temperature):
128
+ if provider == "OpenAI":
129
+ return call_openai(api_key, model, prompt, temperature)
130
+ return call_gemini(api_key, model, prompt, temperature)
131
+
132
+
133
+ # --------------------------------------------------------------------------
134
+ # UI
135
+ # --------------------------------------------------------------------------
136
+ st.set_page_config(page_title="AI Documentation Generator", page_icon="📄", layout="wide")
137
+
138
+ if "history" not in st.session_state:
139
+ st.session_state.history = []
140
+
141
+ # ---- Sidebar: settings ----
142
+ with st.sidebar:
143
+ st.header("⚙️ Settings")
144
+ provider = st.selectbox("AI Provider", list(MODELS.keys()))
145
+ model = st.selectbox("Model", MODELS[provider])
146
+
147
+ env_var = "OPENAI_API_KEY" if provider == "OpenAI" else "GEMINI_API_KEY"
148
+ api_key = st.text_input(
149
+ f"{provider} API Key",
150
+ type="password",
151
+ value=os.getenv(env_var, ""),
152
+ help=f"Or set the {env_var} environment variable.",
153
+ )
154
+ temperature = st.slider("Creativity (temperature)", 0.0, 1.0, 0.4, 0.1)
155
+ detail = st.radio("Level of detail", ["Concise", "Standard", "Very detailed"], index=1)
156
+
157
+ st.divider()
158
+ st.subheader("🕘 History")
159
+ if st.session_state.history:
160
+ for i, item in enumerate(reversed(st.session_state.history)):
161
+ if st.button(f"{item['time']} · {item['type'].split(' (')[0]}", key=f"h{i}"):
162
+ st.session_state.current = item
163
+ else:
164
+ st.caption("Generated documents will appear here.")
165
+
166
+ # ---- Main page ----
167
+ st.title("📄 AI Software Documentation Generator")
168
+ st.caption("Generate an SRS, user stories or technical documentation from a project idea.")
169
+
170
+ col1, col2 = st.columns([1, 1.4], gap="large")
171
+
172
+ with col1:
173
+ st.subheader("1. Project details")
174
+ doc_type = st.selectbox("Document type", list(DOC_TEMPLATES.keys()))
175
+ name = st.text_input("Project name", placeholder="e.g. Smart Attendance System")
176
+ description = st.text_area(
177
+ "Project description",
178
+ height=150,
179
+ placeholder="Describe what the software does and the problem it solves...",
180
+ )
181
+ users = st.text_input("Target users", placeholder="e.g. students, teachers, admin")
182
+ features = st.text_area("Key features (optional)", height=90, placeholder="One per line")
183
+ tech = st.text_input("Tech stack / constraints (optional)", placeholder="e.g. Python, React, MySQL")
184
+
185
+ go = st.button("✨ Generate", type="primary", use_container_width=True)
186
+
187
+ with col2:
188
+ st.subheader("2. Generated document")
189
+
190
+ if go:
191
+ if not api_key:
192
+ st.error("Please enter your API key in the sidebar.")
193
+ elif not name.strip() or not description.strip():
194
+ st.warning("Project name and description are required.")
195
+ else:
196
+ prompt = build_prompt(doc_type, name, description, users, features, tech, detail)
197
+ try:
198
+ with st.spinner(f"Generating with {provider} ({model})..."):
199
+ output = generate(provider, api_key, model, prompt, temperature)
200
+ item = {
201
+ "time": datetime.now().strftime("%H:%M:%S"),
202
+ "type": doc_type,
203
+ "name": name,
204
+ "content": output,
205
+ }
206
+ st.session_state.history.append(item)
207
+ st.session_state.current = item
208
+ except Exception as e: # network errors, bad key, quota, etc.
209
+ st.error(f"API error: {e}")
210
+
211
+ current = st.session_state.get("current")
212
+ if current:
213
+ st.markdown(f"**{current['name']}** · _{current['type']}_")
214
+ tab_view, tab_raw = st.tabs(["Preview", "Markdown"])
215
+ with tab_view:
216
+ st.markdown(current["content"])
217
+ with tab_raw:
218
+ st.code(current["content"], language="markdown")
219
+
220
+ filename = f"{current['name'].strip().replace(' ', '_')}_{current['type'].split(' ')[0]}.md"
221
+ st.download_button(
222
+ "⬇️ Download as .md",
223
+ data=current["content"],
224
+ file_name=filename,
225
+ mime="text/markdown",
226
+ use_container_width=True,
227
+ )
228
+ else:
229
+ st.info("Fill in the details and click **Generate**.")
@@ -0,0 +1,54 @@
1
+ # Assignment 2
2
+
3
+ from collections import deque
4
+
5
+ graph = {
6
+ 'A': ['B', 'C', 'D'],
7
+ 'B': ['A', 'E', 'F'],
8
+ 'C': ['A', 'F', 'G'],
9
+ 'D': ['A', 'G', 'H'],
10
+ 'E': ['B', 'I'],
11
+ 'F': ['B', 'C', 'I', 'J'],
12
+ 'G': ['C', 'D', 'J'],
13
+ 'H': ['D', 'J'],
14
+ 'I': ['E', 'F', 'J'],
15
+ 'J': ['F', 'G', 'H', 'I']
16
+ }
17
+
18
+
19
+ # BFS
20
+ def bfs(start):
21
+ visited = set()
22
+ queue = deque([start])
23
+
24
+ print("BFS Traversal:", end=" ")
25
+
26
+ while queue:
27
+ node = queue.popleft()
28
+
29
+ if node not in visited:
30
+ print(node, end=" ")
31
+ visited.add(node)
32
+
33
+ for neighbour in graph[node]:
34
+ if neighbour not in visited:
35
+ queue.append(neighbour)
36
+
37
+
38
+ # DFS
39
+ def dfs(node, visited):
40
+ if node not in visited:
41
+ print(node, end=" ")
42
+ visited.add(node)
43
+
44
+ for neighbour in graph[node]:
45
+ dfs(neighbour, visited)
46
+
47
+
48
+ start = 'A'
49
+
50
+ bfs(start)
51
+
52
+ visited = set()
53
+ print("\nDFS Traversal:", end=" ")
54
+ dfs(start, visited)