Home > Back-end >  How would I make this more efficient? (python)
How would I make this more efficient? (python)

Time:10-15

This is my code and I'm wondering how I could make this more efficient and I'm also thinking about reading a json file and importing json for the student code like this

with open("filename.json") as f:
   student_info = f.readlines()

but for right now I think my version is fine but not very efficient and slow that is the main reason I made this post is to see if my design could be created more efficiently and creatively.

from imghdr import tests
import random
import time
print("Disclaimer this is a fake person with fake grades no real person had grades recorded ")
print("also thank you for using my software By: PTSCODING")
names = ["james", "john", "joe", "Jason", "Mick", "Nina"]
classes = ['math', 'science', 'social studies', 'reading', 'grammar']
student = {
    "name": names[random.randint(0, 2)],
    'tclass': [random.choice(classes)],
    "assignment": [
        random.randint(70, 100),
        random.randint(0, 100),
        random.randint(0, 100),
        random.randint(0, 100),
    ],
    "test": [random.randint(70, 100), random.randint(70, 100)],
    "participation": [random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)]
}


def get_time():
    return time.localtime


def get_average(grade):
    total_sum = sum(grade)
    total_sum = float(total_sum)
    return total_sum / len(grade)


def calculate_total_average(students):
    assignment = get_average(students["assignment"])
    test = get_average(students["test"])
    return 0.1 * assignment   0.7 * test   0.2


def assign_letter_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"


def get_all_studinfo():
    print(
        f'Name: {student["name"]}  \n Class {student["tclass"]} \n Assignments: {student["assignment"]} \n Tests: {student["test"]} \n'
    )
    print(
        f"{student['name']}'s averages in every type of class is ",
        round(calculate_total_average(student)), "\n"
    )
    print(
        f"{student['name']}'s letter grade is ",
        assign_letter_grade((calculate_total_average(student))), "\n"
    )
    print(
        f"Now that you know {student['name']}'s grade you can now leave. \nHave a great day! :)")


js = {"Name": student['name'],
      "grades": calculate_total_average(student)}
with open("C:\Users\FakeName\.vscode\python\student.json") as f:
    f.write(str(js))


get_all_studinfo()

CodePudding user response:

You can use a library called refrub, it is a tool for refurbishing and modenizing Python codebases. And see what can be optimized.

See : https://github.com/dosisod/refurb

Or see this article on Medium : https://medium.com/@fareedkhandev/make-your-python-code-more-elegant-readable-or-modern-with-one-command-eb910cefded3

CodePudding user response:

I reversed your code,

from imghdr import tests
import random
import time
import json
print("Disclaimer this is a fake person with fake grades no real person had grades recorded ")
print("also thank you for using my software By: PTSCODING")

names = ["james", "john", "joe", "Jason", "Mick", "Nina"]
classes = ['math', 'science', 'social studies', 'reading', 'grammar']

rd_1 = random.randint(0, 100) 
rd_2 = random.randint(70, 100)
student = {
    "name": names[random.randint(0, 2)],
    'tclass': [random.choice(classes)],
    "assignment": [rd_1]   [rd_2]*2,
    "test": [rd_2]*2,
    "participation": [rd_1]*3
}

def get_time():
    return time.localtime

def get_average(grade):
    return float(sum(grade)) / len(grade)

def calculate_total_average(students):
    assignment = get_average(students["assignment"])
    test = get_average(students["test"])
    return 0.1 * assignment   0.7 * test   0.2

def assign_letter_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

def get_all_studinfo():
    print(
        f'Name: {student["name"]}  \n Class {student["tclass"]} \n Assignments: {student["assignment"]} \n Tests: {student["test"]} \n'
    )
    print(
        f"{student['name']}'s averages in every type of class is ",
        round(calculate_total_average(student)), "\n"
    )
    print(
        f"{student['name']}'s letter grade is ",
        assign_letter_grade((calculate_total_average(student))), "\n"
    )
    print(
        f"Now that you know {student['name']}'s grade you can now leave. \nHave a great day! :)")


js = {"Name": student['name'],
      "grades": calculate_total_average(student)}
with open("student.json", 'w') as f:
    f.write(json.dumps(js))


get_all_studinfo()

Things changed.

  • student dictionary intialisation
  • get_average functions
  • json.dumps for the json file writing.
  • Related