Use ChatGPT to Improve Code
You can ask ChatGPT for suggestions about how to improve programs that you’ve written. This can be the beginning of a larger strategy that culminates in ChatGPT writing new code. But it’s often best to start with a high-level discussion, just like you would with another engineer. Here’s an example:
Prompt: How could this program to read and analyze survey data in a spreadsheet be improved? Do not write code; just make suggestions.
fromutilimport*importpandasaspddf=pd.read_excel("data.xlsx")df.fillna("No answer",inplace=True)cols=df.columnstotalrows=len(df)("total answers:",totalrows)name=0forcolincolsname+=1noans=len(df[df[col]=="No answer"])nonnull=totalrows-noans(col)("No answer:",noans,"Total answers:",nonnull)answers=set(df[col])foranswerinanswers:adf=df[df[col]==answer]nanswer=len(adf)p=pct(nanswer,nonnull)ifanswer!="No answer":(" ",answer,":",nanswer,":",p)()ChatGPT: Here are some suggestions to improve the program:
Function encapsulation: Consider breaking the code into smaller functions, each with a specific task, such as loading data, preprocessing, and analyzing the data. This will improve code readability and make it easier to maintain and debug.
Variable naming: Use more descriptive variable names to make the code more understandable. For instance, instead of using name, you ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access