Vytvoření kódu z přirozeného jazyka
Jednou z možností modelů Azure OpenAI je vygenerovat kód z výzev přirozeného jazyka. Úkoly můžou být v rozsahu od jednoduchého příkazu o jeden řádek až po celou aplikaci. Modely AI můžou také upravit a aktualizovat zadaný kód nebo předchozí odpovědi, aby bylo možné dokončit požadovaný úkol.
Příklady v této lekci se používají gpt-35-turbo
.
Psaní funkcí
Modely Azure OpenAI můžou vytvářet funkce a aplikace v několika jazycích pouhým popisem toho, co chcete. Například vzhledem k výzvě write a function for binary search in python
pravděpodobně obdržíte odpověď s funkcí a vysvětlení kódu.
Sure, here's an example implementation of binary search algorithm in Python:
def binary_search(array, target):
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == target:
return mid
elif array[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
This function takes in two arguments - an array of integers and a target integer that we want to search
for in the array. The function initializes two pointers - low and high - to the first and last indices
of the array, respectively.
Inside the while loop, the function calculates the middle index using integer division (//). If the
middle element is equal to the target, the function returns the index of the middle element. If the
middle element is less than the target, we update the low pointer to mid + 1. Otherwise, we update the
high pointer to mid - 1. We continue these steps until we find the target or the pointers cross each
other (i.e., low > high).
If the target is not found in the array, the function returns -1.
Note that the binary search algorithm assumes that the input array is sorted in ascending order. If
the array is not sorted, the algorithm may not return the correct result.
Požadavek může jít dál než funkce a požádat o řadu funkcí nebo celé aplikace. Odpověď poskytuje dobrý výchozí bod pro úkol, který se pokoušíte dosáhnout.
Změna jazyka kódování
Pokud máte kód v jednom jazyce, ale potřebujete ho v jiném, Azure OpenAI vám ho může přeložit. Řekněme například, že máte tuto print_squares
funkci v Pythonu.
def print_squares(n):
for i in range(1, n+1):
print(i**2)
Pokud zadáte tento kód spolu s výzvou convert this code to C#
, pravděpodobně se zobrazí něco podobného následující funkci.
public void PrintSquares(int n)
{
for (int i = 1; i <= n; i++)
{
Console.WriteLine(i * i);
}
}
Všimněte si rozdílů mezi tím, jak for
se smyčky a funkce definují v různých jazycích (včetně modifikátorů přístupu v jazyce C#), a odpovídajícím způsobem změnil kód.
Vysvětlení neznámého kódu
Modely Azure OpenAI jsou užitečné pro pochopení kódu, který nedává smysl, nebo může být v jazyce, který neznáte. Řekněme například, že jste dostali následující funkci (ve fiktivním programovacím jazyce!) a nevěděli jste, jak ji pochopit.
fn qzplv(n: i32, m: i32) -> i32 {
if n == 0 {
return m + 1;
} else if m == 0 {
return qzplv(n - 1, 1);
} else {
return qzplv(n - 1, qzplv(n, m - 1));
}
}
Při poskytnutí modelu spolu s výzvou could you explain what this code is doing?
získáte odpověď podobnou následující:
Sure, I'd be happy to explain what this code is doing!
This code is implementing the Ackermann function, which is a well-known mathematical function that
grows very quickly in terms of computation time as its inputs increase. The function takes two integer
arguments (n and m) and returns another integer.
Here's how the function works:
- If n is equal to 0, the function returns m + 1.
- If m is equal to 0, the function calls itself recursively with n - 1 and 1 as arguments.
- Otherwise, the function calls itself recursively with n - 1 and the result of calling itself with n
and m - 1 as arguments.
The function is implemented in a way that is easy to understand and follow, but it has a very high
computational complexity. In fact, it grows so quickly that it can't be computed for values of n and m
greater than about 4 or 5.
Díky kombinaci vysvětlení a překladu do jazyka, který znáte, je tato funkce ještě užitečnější.
Kompletní kód a pomoc s procesem vývoje
Azure OpenAI může vývojářům pomoct při běžných úlohách vývoje softwaru, jako je psaní testů jednotek, dokončování částečného kódu, komentování kódu a generování dokumentace. Pomocí pomoci s AI můžou vývojáři trávit více času na složitém programování a řešení problémů.
Modely Azure OpenAI můžou generovat kód na základě komentářů, názvů funkcí a částečně napsaného kódu. Čím více kontextu můžete modelu poskytnout, tím přesnější je pravděpodobnost odpovědi.
Například při zadání následující výzvy:
complete the following function
"""
# calculate the average of the numbers in an array, but only if they're even
def
Model vezme komentáře a začátek definice funkce a dokončí ho z libovolného kontextu, který má.
Podobné funkce lze vidět poskytnutím částečného kódu modelu bez jakýchkoli komentářů. Podívejte se například na následující výzvu.
complete the following code
"""
def func1(n)
if n==0:
complete the following code
"""
public int Func1(int n) {
if (n == 0) {
Model AI nejlépe dokončí funkci s nejpravděpodobnějším dokončením funkce.
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);
}
}
Odpověď pravděpodobně obsahuje také vysvětlení přirozeného jazyka, co tato funkce dělá. V tomto případě odpověděl rekurzivní implementací faktoriální funkce.
Zápis testů jednotek
Modely Azure OpenAI můžou generovat testy jednotek pro funkce, které napíšete, aby byl váš kód robustnější. Vezměte například funkci binárního vyhledává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;
}
Zadejte tuto funkci spolu s výzvou write three unit tests for this function
a získáte odpověď podobnou následující.
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);
}
Tato funkce je ještě užitečnější, pokud zadáte případy, které chcete zahrnout do výzvy, což zkracuje dobu potřebnou k psaní testů jednotek pro váš kód.
Přidání komentářů a generování dokumentace
Pro další vylepšení kódu můžou modely AI přidávat komentáře a dokumentaci za vás. Jako příklad použijte následující funkci, která může být při prvním čtení bez komentářů ke kódu trochu obtížná.
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;
}
}
Poskytněte této funkci modelu spolu s výzvou, že do kódu přidá komentáře, a dostanete odpověď podobnou následující.
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;
}
}
Pokud ho provedete ještě o krok dál a požádáte o dokumentaci, OpenAI přidá popis včetně vstupů a výstupů.
Oprava chyb a vylepšení kódu
Vývojáři někdy můžou psát kód, který většinou funguje, ale může se zlepšit opravou chyb, syntaxe, výkonu nebo modularity. Modely Azure OpenAI vám můžou pomoct identifikovat způsoby, jak vylepšit a poskytnout návrhy na psaní lepšího kódu.
Oprava chyb v kódu
Modely Azure OpenAI můžou pomoct opravit chyby v kódu tím, že analyzují kód a navrhují změny, které by mohly problém vyřešit. To může vývojářům pomoct rychleji a efektivněji identifikovat a vyřešit chyby.
Řekněme například, že máte následující funkci, která vám nefunguje.
def calculate_average(numbers):
total = 0
for i in range(len(numbers)):
number = numbers[i]
total += number
average = total
rerun averave
public double CalculateAverage(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
int number = numbers[i];
total += number;
}
double average = (double)total;
rerun averave;
}
Poskytněte této funkci modelu spolu s výzvou Fix the bugs in this function
a získáte odpověď s pevným kódem a vysvětlením toho, co bylo opraveno.
def calculate_average(numbers):
total = 0
for i in range(len(numbers)):
number = numbers[i]
total += number
average = total / len(numbers)
return average
public double CalculateAverage(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
int number = numbers[i];
total += number;
}
double average = (double)total / numbers.Length;
return average;
}
There were a few issues with the original code:
1. The variable "average" was assigned the value of "total" instead of the actual average.
2. There was a typo in the last line - "rerun" should be "return".
3. The average was not actually calculated - the corrected code divides the total by the length of
the "numbers" list to get the average.
Zvýšení výkonu
I když vývojáři kódu můžou pracovat, může být efektivnější způsob, jak tento úkol provést. Tady je příklad funkce, která vypočítá součet prvních n kladných celých čísel, pravděpodobně neefektivní:
def sum_of_n(n):
result = 0
for i in range(1, n+1):
result += i
return result
public int SumOfN(int n)
{
int result = 0;
for (int i = 1; i <= n; i++)
{
result += i;
}
return result;
}
Tato verze funguje správně, ale její časová složitost je O(n). Pokud je model poskytnutý, tady je odpověď:
We can improve this function it by using a mathematical formula instead.
Here's the more efficient version:
def sum_of_n(n):
return n * (n + 1) // 2
public int SumOfN(int n)
{
return n * (n + 1) / 2;
}
Tato verze stále vrací správný výsledek, ale jeho časová složitost je nyní O(1), což z něj dělá mnohem efektivnější.
Refaktoring neefektivního kódu
Lepší kód je méně náchylný k chybám a je jednodušší udržovat a modely Azure OpenAI můžou vývojářům pomoct při refaktoringu kódu.
Zvažte následující funkci.
def calculateTotalPrice(item, quantity):
if item == 'apple':
return quantity * 0.5
elif item == 'banana':
return quantity * 0.75
elif item == 'orange':
return quantity * 0.6
else:
return 0
public double CalculateTotalPrice(string item, int quantity)
{
if (item == "apple")
{
return quantity * 0.5;
}
else if (item == "banana")
{
return quantity * 0.75;
}
else if (item == "orange")
{
return quantity * 0.6;
}
else
{
return 0;
}
}
Tento kód vypočítá celkovou cenu konkrétní položky na základě jejího názvu a množství. Kód ale není modulární a může být obtížné ho udržovat. Když model poskytnete s požadavkem na refaktoring, tady je odpověď:
item_prices = {
'apple': 0.5,
'banana': 0.75,
'orange': 0.6
}
def calculate_total_price(item, quantity):
price = item_prices.get(item, 0)
return quantity * price
static Dictionary<string, double> itemPrices = new Dictionary<string, double>()
{
{"apple", 0.5},
{"banana", 0.75},
{"orange", 0.6}
};
static double CalculateTotalPrice(string item, int quantity)
{
double price;
if (!itemPrices.TryGetValue(item, out price))
{
price = 0;
}
return quantity * price;
}
Společně s kódem poskytuje model vysvětlení refaktoringu.
In this refactored code, we've created an object called itemPrices that maps item names to their
prices. We've also simplified the calculateTotalPrice function by using the itemPrices object to look
up the price of the item, rather than using a series of if/else statements. This makes the code more
modular and easier to maintain, and also reduces the risk of introducing bugs in the future.