透過自然語言建構程式碼
Azure OpenAI 模型的其中一個功能是透過自然語言提示產生程式碼。 工作的範圍可以從簡單的單行命令到完整的應用程式。 AI 模型也可以編輯和更新所提供的程式碼或先前的回應,以完成要求的工作。
本單元中的範例會使用 gpt-35-turbo
。
撰寫函式
只要描述您想要的內容,Azure OpenAI 模型即可建立數種語言的函式和應用程式。 例如,根據提示 write a function for binary search in python
,您可能會收到一個包含函式以及程式碼說明的回應。
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.
要求可以超過函式,並要求一系列的函式或整個應用程式。 回應能為您試圖完成的工作提供一個良好的起點。
變更編碼語言
如果您有一種語言的程式碼,但需要轉換成另一種語言,Azure OpenAI 可以為您進行翻譯。 例如,假設您在 Python 中擁有此 print_squares
函式。
def print_squares(n):
for i in range(1, n+1):
print(i**2)
如果您提供該程式碼以及提示 convert this code to C#
,您可能會得到類似下列函式的內容。
public void PrintSquares(int n)
{
for (int i = 1; i <= n; i++)
{
Console.WriteLine(i * i);
}
}
請注意,模型理解 for
迴圈和函式在不同語言 (包含 C# 中的存取修飾詞) 中的定義差異,並已適當地變更程式碼。
理解未知的程式碼
Azure OpenAI 模型有助您理解不合理或使用您不熟悉語言的程式碼。 舉例來說,您獲得了以下函式 (使用虛構編碼語言),但不知道如何理解。
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));
}
}
當您提供給模型該函式和提示 could you explain what this code is doing?
後,會取得類似以下內容的回應:
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.
因為這項功能可結合說明並翻譯成您熟悉的語言,所以更加實用。
完成程式碼並協助開發流程
Azure OpenAI 可以協助開發人員完成常見的軟體開發工作單位,如撰寫單元測試、完成部分程式碼、註解程式碼和產生檔案。 使用 AI 協助可以使開發人員將更多時間花在複雜的程式設計和問題解决工作上。
Azure OpenAI 模型能够根據註解、函式名稱和部分撰寫的程式碼產生程式碼。 您可以提供的模型内容越多,回應可能就越準確。
例如,當給出以下提示時:
complete the following function
"""
# calculate the average of the numbers in an array, but only if they're even
def
模型接受函式定義的註解和開頭,並自任何内容完成它。
透過向模型提供部分程式碼 (而不需要任何註解),可以看到類似的功能。 以以下提示為例。
complete the following code
"""
def func1(n)
if n==0:
complete the following code
"""
public int Func1(int n) {
if (n == 0) {
AI 模型盡最大努力完成函式。
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);
}
}
回應可能還包括對該函式作用的自然語言説明。 在這種情況下,它以階乘函式的遞迴實作作為回應。
撰寫單元測試
Azure OpenAI 模型可以為您撰寫的函式產生單元測試,以協助您的程式碼更加強固。 以二進位搜尋函式為例。
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;
}
將該函式與提示 write three unit tests for this function
一起提供,您會得到類似於以下內容的回應。
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);
}
如果您指定了要包含在提示中的案例 (其减少了為程式碼撰寫單元測試所需的時間),則此功能將更加實用。
新增註解並產生文件
為了進一步改進程式碼,AI 模型可以為您新增註解和文件。 以下方的函式為例,第一次讀它時,如果沒有任何程式碼註解,可能會有點難以理解。
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;
}
}
將該函式提供給模型,並提示它向程式碼中新增註解,您會得到類似於以下內容的回應。
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;
}
}
如果您再進一步並要求記載,OpenAI 會新增包括輸入和輸出的描述。
修正錯誤並改善程式碼
開發人員有時可以撰寫大部分運作的程式碼,但可藉由修正錯誤、語法、效能或模組化來改善程式碼。 Azure OpenAI 模型可協助識別改善的方式,並提供如何撰寫更佳程式碼的建議。
修正程式碼中的錯誤
Azure OpenAI 模型可藉由分析程式碼,並建議可能修正問題的變更,以協助修正程式碼中的錯誤。 這可協助開發人員更快且更有效率地識別和解決錯誤。
例如,假設您有下列無法運作的函式。
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;
}
將該函式提供給模型,以及提示 Fix the bugs in this function
,而您會收到具有固定程式碼的回應,以及已修正內容的說明。
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.
改善效能
雖然程式碼開發人員撰寫可能正常運作,但可能有更有效率的方式來完成工作。 以下是計算前 n 個正整數總和的函式範例,其效率可能不佳:
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;
}
此版本會正常運作,但其時間複雜度為 O(n)。 提供給模型時,回應如下:
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;
}
此版本仍然傳回正確的結果,但其時間複雜度現在是 O(1),因此更有效率。
重構效率不佳的程式碼
較佳的程式碼較不容易發生錯誤,而且更容易維護,而 Azure OpenAI 模型可協助引導開發人員重構其程式碼。
以下列函數為例。
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;
}
}
此程式碼會根據其名稱和數量來計算特定項目的總價格。 不過,程式碼並非模組化,可能難以維護。 將要求提供給模型以重構時,回應如下:
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;
}
除了程式碼之外,模型也提供重構的說明。
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.