Kodu tamamlama ve geliştirme sürecine yardımcı olması

Tamamlandı

Azure OpenAI, birim testleri yazma, kısmi kodu tamamlama, kod açıklama ekleme ve belge oluşturma gibi yaygın yazılım geliştirme görevlerinde geliştiricilere yardımcı olabilir. Yapay zeka yardımının kullanılması, geliştiricilerin karmaşık programlama ve sorun çözme görevlerine daha fazla zaman harcamasına olanak sağlayabilir.

Kısmi kodu tamamlama

Azure OpenAI modelleri açıklamalara, işlev adlarına ve kısmen yazılmış koda göre kod oluşturabilir. Modeli ne kadar çok bağlam sağlayabilirseniz, yanıt büyük olasılıkla o kadar doğru olur.

Örneğin, aşağıdaki istem verildiğinde:

complete the following function  
"""  
# calculate the average of the numbers in an array, but only if they're even  
def 
complete the following function    
"""    
// calculate the average of the numbers in an array, but only if they're even    
public 

Model, açıklamaları alır ve işlev tanımının başlangıcını alır ve sahip olduğu bağlamdan tamamlar.

# calculate the average of the even numbers in an array  
def calculate_even_average(numbers):  
    total = 0  
    count = 0  
    for number in numbers:  
        if number % 2 == 0:  
            total += number  
            count += 1  
    if count == 0:  
        return 0  # avoid division by zero  
    else:  
        return total / count  
// calculate the average of the even numbers in an array  
public double CalculateEvenAverage(int[] numbers) {  
    int total = 0;  
    int count = 0;  
    foreach (int number in numbers) {  
        if (number % 2 == 0) {  
            total += number;  
            count++;  
        }  
    }  
    if (count == 0) {  
        return 0;  // avoid division by zero  
    } else {  
        return (double) total / count;  
    }  
}

Bu durumda, işlevin başlangıcından önceki nispeten basit ve eksiksiz bir açıklama nedeniyle ne istediğimizi ayırt edebildi. Daha karmaşık işlevler veya görevlerle, yararlı bir yanıt almak için daha fazla bağlam gerekir.

Python gibi bazı dillerde söz diziminin modelin hangi dilin istendiğini varsayacak kadar net olduğunu unutmayın. C# veya Java gibi söz dizimsel olarak benzer diller için modelin yanlış dil kullanma olasılığı daha yüksektir. Bu durumda, istemde dili belirtmeyi veya bağlam için daha fazla kod sağlamayı deneyin.

Benzer işlevler, modele açıklama olmadan kısmi kod sağlayarak görülebilir. Örneğin aşağıdaki istemi alın.

complete the following code  
"""  
def func1(n)
  if n==0:
complete the following code  
"""  
public int Func1(int n) {  
    if (n == 0) { 

Yapay zeka modeli, işlevin tamamlanması en olası olan işlevi tamamlamak için en iyisini yapar.

def func1(n):  
    if n == 0:  
        return 1  
    else:  
        return n * func1(n-1)  
public int Func1(int n) {  
    if (n == 0) {  
        return 1;  
    } else {  
        return n * Func1(n-1);  
    }  
}

Yanıt büyük olasılıkla bu işlevin ne yaptığına ilişkin doğal bir dil açıklaması da içerir. Bu durumda, faktöriyel işlevin özyinelemeli bir uygulamasıyla yanıt verdi. Ancak istem, modelden ne istediğimizi daha iyi belirtmek için istemde daha fazla bağlama ihtiyaç duyulan bir durumu gösteren bir Fibonacci işlevinin başlangıcı da olabilir.

GitHub Copilot gibi araçlar, yukarıdaki örneklere benzer şekilde kod ve işlev tamamlamaları önermek için OpenAI modellerini kullanır. GitHub Copilot, yerleşik istemleri ve eşleştirilmiş programcı olarak çalışmak için yazdığınız kodun bağlamını kullanan bu işlevselliğin gerçek dünya kullanımına mükemmel bir örnektir.

Birim testleri yazma

Azure OpenAI modelleri, kodunuzu daha sağlam hale getirmek için yazdığınız işlevler için birim testleri oluşturabilir. Örneğin ikili arama işlevini alın.

def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1
public static int BinarySearch(int[] arr, int target)
{
    int left = 0;
    int right = arr.Length - 1;

    while (left <= right)
    {
        int mid = (left + right) / 2;

        if (arr[mid] == target)
        {
            return mid;
        }
        else if (arr[mid] < target)
        {
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }

    return -1;
}

istemiyle write three unit tests for this functionbirlikte bu işlevi sağlayın ve aşağıdakine benzer bir yanıt alırsınız.

def test_binary_search():  
    # Test case 1: Target element is in the middle of the array  
    arr1 = [1, 2, 3, 4, 5, 6]  
    target1 = 4  
    assert binary_search(arr1, target1) == 3  

    # Test case 2: Target element is at the beginning of the array  
    arr2 = [1, 2, 3, 4, 5, 6]  
    target2 = 1  
    assert binary_search(arr2, target2) == 0  

    # Test case 3: Target element is not in the array  
    arr3 = [1, 2, 3, 4, 5, 6]  
    target3 = 7  
    assert binary_search(arr3, target3) == -1
[Test]  
public void TestBinarySearch1()  
{  
    int[] arr = { 1, 2, 3, 4, 5 };  
    int target = 3;  
    int expected = 2;  
    int result = BinarySearch(arr, target);  
    Assert.AreEqual(expected, result);  
}  

[Test]  
public void TestBinarySearch2()  
{  
    int[] arr = { 10, 20, 30, 40, 50 };  
    int target = 35;  
    int expected = -1;  
    int result = BinarySearch(arr, target);  
    Assert.AreEqual(expected, result);  
}  

[Test]  
public void TestBinarySearch3()  
{  
    int[] arr = { 3, 6, 9, 12, 15 };  
    int target = 6;  
    int expected = 1;  
    int result = BinarySearch(arr, target);  
    Assert.AreEqual(expected, result);  
}  

Bu işlev, isteminize eklenmesini istediğiniz durumları belirtirseniz daha da kullanışlıdır ve bu da kodunuz için birim testleri yazma süresini kısaltır.

Açıklama ekleme ve belge oluşturma

Kodunuzu daha da geliştirmek için yapay zeka modelleri sizin için açıklamalar ve belgeler ekleyebilir. Aşağıdaki işlevi örnek olarak alın; kod açıklamaları olmadan ilk kez okurken anlaşılması biraz zor olabilir.

def permutations(lst):  
    if len(lst) == 0:  
        return []  
    elif len(lst) == 1:  
        return [lst]  
    else:  
        result = []  
        for i in range(len(lst)):  
            temp = lst[i]  
            remaining = lst[:i] + lst[i+1:]  
            for p in permutations(remaining):  
                result.append([temp] + p)  
        return result  
public static List<List<int>> Permutations(List<int> lst)  
{  
    if (lst.Count == 0)  
    {  
        return new List<List<int>>();  
    }  
    else if (lst.Count == 1)  
    {  
        return new List<List<int>> { lst };  
    }  
    else  
    {  
        List<List<int>> result = new List<List<int>>();  
        for (int i = 0; i < lst.Count; i++)  
        {  
            int temp = lst[i];  
            List<int> remaining = new List<int>(lst);  
            remaining.RemoveAt(i);  
            foreach (List<int> p in Permutations(remaining))  
            {  
                List<int> permutation = new List<int> { temp };  
                permutation.AddRange(p);  
                result.Add(permutation);  
            }  
        }  
        return result;  
    }  
}  

Koda açıklama eklemesini isteyen bir istemle birlikte modele bu işlevi sağlayın ve aşağıdakine benzer bir yanıt alırsınız.

def permutations(lst):  
    # Check if the input list is empty  
    if len(lst) == 0:  
        return []  
    # Check if the input list has only one element  
    elif len(lst) == 1:  
        return [lst]  
    else:  
        # Initialize an empty list to store permutations  
        result = []  
        # Iterate through each element of the input list  
        for i in range(len(lst)):  
            # Remove the current element from the list and store it in a variable  
            temp = lst[i]  
            remaining = lst[:i] + lst[i+1:]  
            # Recursively call the function on the remaining list  
            for p in permutations(remaining):  
                # Append the current element to the beginning of each permutation and add it to the result list  
                result.append([temp] + p)  
        # Return the final list of permutations  
        return result  
public static List<List<int>> Permutations(List<int> lst)  
{  
    // Check if the input list is empty  
    if (lst.Count == 0)  
    {  
        return new List<List<int>>();  
    }  
    // Check if the input list has only one element  
    else if (lst.Count == 1)  
    {  
        return new List<List<int>> { lst };  
    }  
    else  
    {  
        // Initialize an empty list to store permutations  
        List<List<int>> result = new List<List<int>>();  
        // Iterate through each element of the input list  
        for (int i = 0; i < lst.Count; i++)  
        {  
            // Remove the current element from the list and store it in a variable  
            int temp = lst[i];  
            List<int> remaining = new List<int>(lst);  
            remaining.RemoveAt(i);  
            // Recursively call the function on the remaining list  
            foreach (List<int> p in Permutations(remaining))  
            {  
                // Append the current element to the beginning of each permutation and add it to the result list  
                List<int> permutation = new List<int> { temp };  
                permutation.AddRange(p);  
                result.Add(permutation);  
            }  
        }  
        // Return the final list of permutations  
        return result;  
    }  
}  

Bunu bir adım ileri götürün ve açıklama eklediği işlev için belge isteyin.

def permutations(lst):  
    """  
    Generates all possible permutations of a given list of integers using recursion.  

    Args:  
        lst (list): The list of integers to generate permutations for.  

    Returns:  
        list: A list of all possible permutations of the input list.  
    """  
    # Check if the input list is empty  
    if len(lst) == 0:  
        return []  
    # Check if the input list has only one element  
    elif len(lst) == 1:  
        return [lst]  
    else:  
        # Initialize an empty list to store permutations  
        result = []  
        # Iterate through each element of the input list  
        for i in range(len(lst)):  
            # Remove the current element from the list and store it in a variable  
            temp = lst[i]  
            remaining = lst[:i] + lst[i+1:]  
            # Recursively call the function on the remaining list  
            for p in permutations(remaining):  
                # Append the current element to the beginning of each permutation and add it to the result list  
                result.append([temp] + p)  
        # Return the final list of permutations  
        return result  
/// <summary>  
/// Generates all possible permutations of a given list of integers using recursion.  
/// </summary>  
/// <param name="lst">The list of integers to generate permutations for.</param>  
/// <returns>A list of all possible permutations of the input list.</returns>  ```
public static List<List<int>> Permutations(List<int> lst)  
{  
    // Check if the input list is empty  
    if (lst.Count == 0)  
    {  
        return new List<List<int>>();  
    }  
    // Check if the input list has only one element  
    else if (lst.Count == 1)  
    {  
        return new List<List<int>> { lst };  
    }  
    else  
    {  
        // Initialize an empty list to store permutations  
        List<List<int>> result = new List<List<int>>();  
        // Iterate through each element of the input list  
        for (int i = 0; i < lst.Count; i++)  
        {  
            // Remove the current element from the list and store it in a variable  
            int temp = lst[i];  
            List<int> remaining = new List<int>(lst);  
            remaining.RemoveAt(i);  
            // Recursively call the function on the remaining list  
            foreach (List<int> p in Permutations(remaining))  
            {  
                // Append the current element to the beginning of each permutation and add it to the result list  
                List<int> permutation = new List<int> { temp };  
                permutation.AddRange(p);  
                result.Add(permutation);  
            }  
        }  
        // Return the final list of permutations  
        return result;  
    }  
}