Coding Menggunakan ChatGPT – Part 3

Masih membahas coding menggunakan chatGPT, kali ini kita akan coba meminta model memperbaiki bug dan menjelaskannya.

Pada contoh digunakan fungsi Python yang bertujuan menambahkan underscore setelah setiap huruf dalam sebuah kata. Jadi misalnya kata hallo menjadi h_a_l_l_o.

Sengaja disediakan fungsi yang salah dimana hasilnya adalah 0_.

import openai
from dotenv import dotenv_values

config = dotenv_values(".env")
openai.api_key = config["OPENAI_KEY"]

code = """
def add_underscores(word):
    new_word = "_"
    for i in range(len(word)):
        new_word = word[i] + "_"
    return new_word

phrase = "hallo"
print(add_underscores(phrase))
"""

messages = [
    {"role": "user", "content": f"Fix and explain the bug in the following python code : {code}"}

]

    
response = openai.ChatCompletion.create(
    model = "gpt-3.5-turbo",
    messages = messages,
)

print(response.choices[0]["message"]["content"])

Dan hasilnya cukup mengesankan, model memahami bug dan dapat memperbaiki serta menjelaskan kesalahannya.

The bug in the code is that it only adds underscore after each letter but not before the first letter. Also, it assigns the value of new_word to the letter plus underscore, instead of concatenating it.

To fix the code, we need to initialize the new_word variable with the first letter of the word and then concatenate an underscore and the subsequent letters in the loop.

Here's the corrected code:

def add_underscores(word):
    new_word = word[0]
    for i in range(1, len(word)):
        new_word += "_" + word[i]
    return new_word

phrase = "hallo"
print(add_underscores(phrase))

# Output: h_a_l_l_o

Sharing is caring: