Skip to main content

Python Project: AI Based Assignment Completer

Python Project: AI-Based Assignment Completer

A small suite of Python scripts that generate C programs from prompts, create outputs and collect code into a .docx file.

1. File 1 — generator (generate C files)

Notes:

  • Replace the API key placeholder on the line where openai.api_key is set with your own key, or set openai.api_key elsewhere in your environment.
  • Create a prompt.txt file in the same directory with one question per line.
  • Create a folder named programms in the same directory — generated C files will be placed there.
The Python code (unchanged):
import os
import openai

class Ai:
    number=0
    def automatedquery(self, query):
        '''this f(x) returns the responce generated by cahtgpt'''
        openai.api_key = "Your Api Key Here!"
        response = openai.Completion.create(
            model="text-davinci-003",
            prompt=query,
            temperature=0.7,
            max_tokens=256,
            top_p=1,
            frequency_penalty=0,
            presence_penalty=0
        )
        return(response["choices"][0]["text"])
    #i in this f(x) is for checking for errors in filename
    def writeanswers(self, query, i=0):
        self.number+=1
        with open(f'''programms//{self.number}.c''', "w") as fh:
            #responce from chatgpt
            result=self.automatedquery(f"{query} in c language without output and comments")
            #writing responce
            fh.write(f'''/*		program {self.number}
	{query}

Roll No - 2271268
Name- Rohit Singh
Course - BCA
Semester-II
Section-B
*/
{result}''')
        return 1

class FileItemList:
    def __init__(self, file):
        self.list=[]
        with open (file) as fh:
            self.list=(fh.read()).split("\n")

if __name__ == "__main__":
    questions=FileItemList("prompt.txt")
    assistant=Ai()
    for index, query in enumerate(questions.list):

        if assistant.writeanswers(query):
            print(f"{index+1} question written")
        else:
            print("something went wrong!")

2. File 2 — output generator (generate outputs)

This script reads the generated C files and uses the AI to produce expected output. The code (unchanged):

from generate import Ai
import os

class Output:
    fileExtention=".c" #because i am doing it for c program
    def __init__(self, location):
        self.location=location
        if os.path.exists(self.location):
            self.list_of_programs=[i for i in os.listdir(self.location) if i.endswith(self.fileExtention)]
        else:
            self.list_of_programs=[]
            print(f"Location not found!")
    #to get output of program
    def getout(self, program):
        solver=Ai()
        output=solver.automatedquery(f'''generate the output of the following code if need of input give any- \n{program}''')
        return output
    #for all the files
    def outputall(self):
        for index,programms in enumerate(self.list_of_programs):
            with open(fr"{self.location}{programms}") as fh:
                program=fh.read()
            output=self.getout(program)
            with open(fr"{self.location}{programms}","a") as fh:
                fh.write(f'''\n/*\n{output}\n*/''')
            print(index+1, "output written")
        return 1

if __name__=="__main__":
    o=Output("/media/rohiyaa/link_between/c project/programms/")
    o.outputall()

3. File 3 — collect code into a .docx

This script reads all generated .c files and appends their contents to file.docx. The code (unchanged):

import os

with open("file.docx", "a") as fh:
    l=[i for i in os.listdir("programms/") if i.endswith(".c")]
    #bubble sort
    for i in range(len(l)-1):
        for j in range(0, len(l)-i-1):
            if int(l[j][0:-2])>int(l[j+1][0:-2]):
                l[j], l[j+1]=l[j+1],l[j]
    for i in l:
        with open(f"programms/{i}") as f:
            fh.write(f.read())

Now you can print the file.docx. If you prefer, use .txt instead for cross-platform compatibility.


I have a YouTube channel called Road2geeks. Subscribe for tutorials and walkthroughs. Thanks for reading — see you in the next post. Jai Hind.

Comments

Popular posts from this blog

LeetCode 88 Explained: Four Approaches, Mistakes, Fixes & the Final Optimal Python Solution

Evolving My Solution to “Merge Sorted Array” A practical, beginner-friendly walkthrough showing four versions of my code (from a naive approach to the optimal in-place two-pointer solution). Includes explanations, complexity and ready-to-paste code. Problem Summary You are given two sorted arrays: nums1 with size m + n (first m are valid) nums2 with size n Goal: Merge nums2 into nums1 in sorted order in-place . Version 1 — Beginner Approach (Extra List) I merged into a new list then copied back. Works, but not in-place and uses extra memory. class Solution: def merge(self, nums1, m, nums2, n): result = [] p1 = 0 p2 = 0 for _ in range(m+n): if p1 >= m: result.extend(nums2[p2:n]) break elif p2 >= n: result.extend(nums1[p1:m]) break elif nu...

Introducing CodeMad: Your Ultimate Universal IDE with Custom Shortcuts

Introducing CodeMad: Your Ultimate Multi-Language IDE with Custom Shortcuts Welcome to the world of CodeMad, your all-in-one Integrated Development Environment (IDE) that simplifies coding and boosts productivity. Developed in Python, CodeMad is designed to make your coding experience smoother and more efficient across a variety of programming languages, including C, C++, Java, Python, and HTML. Whether you're a beginner or an experienced programmer, CodeMad is your go-to tool. In this blog, we'll dive deep into the workings of CodeMad, highlighting its unique features and easy installation process. The Power of Shortcuts CodeMad's intuitive interface is built around a set of powerful keyboard shortcuts that make coding a breeze. Here are some of the key shortcuts you'll find in CodeMad: Copy (Ctrl+C) : Duplicate text with ease. Paste (Ctrl+V) : Quickly insert copied content into your code. Undo (Ctrl+Z) and Redo (Ctrl+Y) : Correct mistakes and s...

Product of Array Except Self in Python | Prefix & Suffix Explained (LeetCode 238)

Problem Overview The Product of Array Except Self is a classic problem that tests your understanding of array traversal and optimization. The task is simple to state but tricky to implement efficiently. Given an integer array nums , you need to return an array such that each element at index i is equal to the product of all the elements in nums except nums[i] . The challenge is that: Division is not allowed The solution must run in O(n) time Initial Thoughts At first glance, it feels natural to compute the total product of the array and divide it by the current element. However, this approach fails because division is forbidden and handling zeroes becomes messy. This pushed me to think differently — instead of excluding the current element, why not multiply everything around it? That’s where the prefix and suffix product pattern comes in. Key Insight: Prefix & Suffix Products For every index i : Prefix product → product of all elements to t...