IBM Watson Code Assistant (2023 年 5 月): 目前仅生成带有 AI 生成建议的 Red Hat® Ansible® 脚本。基于 Wisdom 模型及其 350M 参数。
2、代码生成的用例和应用
代码完成是一种上下文相关的代码生成功能,可通过减少拼写错误和其他常见错误来加快应用程序编码过程。
2.1 代码完成
代码完成(Code completion)是第一个主要用例,允许你完成代码的开头或在中间注入代码。
# >>> Model: replit/replit-code-v1-3b - Temperature = 0.2# >>> Prompt:deffind_best_rsquared(list_of_fits):
"""Return the best fit, based on rsquared"""# >>> Result:returnmin(list_of_fits, key=lambda x: x.rsquared)
2.2 文本生成代码
文本生成代码(Text to code)是根据自然语言描述生成代码。
# >>> Model: replit/replit-code-v1-3b - Temperature = 0.2# >>> Prompt:"""
double_sum_to_value takes a list of integers as an input.
It returns True if there are two distinct elements in the list that \
sum to a value given in input, and False otherwise.
Check if the list has at least two elements.
Find all possible combinations of two distinct elements in the list.
Check if any of the combinations sum up to the given value.
"""# >>> Result:defdouble_sum_to_value(list_of_ints, value):
"""
:param list_of_ints: a list of integers
:param value: a value to check if the list has two distinct elements that sum to
:return: True if there are two distinct elements in the list that sum to a value given in input, and False otherwise
"""# if the list has less than two elements, return Falseiflen(list_of_ints) < 2:
returnFalse# if the list has more than two elements, return Trueelse:
# iterate over the listfor i inrange(len(list_of_ints) - 1):
# iterate over the remaining elementsfor j inrange(i + 1, len(list_of_ints)):
# if the sum of the two elements is equal to the value, return Trueif list_of_ints[i] + list_of_ints[j] == value:
returnTrue# if the list does not have two distinct elements that sum to the value, return FalsereturnFalsedefmain():
# print the return value of double_sum_to_valueprint(double_sum_to_value([1, 2, 3, 4, 5], 8))
if __name__ == '__main__':
main()
# >>> Model: replit/replit-code-v1-3b - Temperature = 0.2# >>> Prompt:import unittest
defdouble_sum_to_value(list_of_ints, value):
"""
:param list_of_ints: a list of integers
:param value: a value to check if the list has two distinct elements that sum to
:return: True if there are two distinct elements in the list that sum to a value given in input, and False otherwise
"""# if the list has less than two elements, return Falseiflen(list_of_ints) < 2:
returnFalse# if the list has more than two elements, return Trueelse:
# iterate over the listfor i inrange(len(list_of_ints) - 1):
# iterate over the remaining elementsfor j inrange(i + 1, len(list_of_ints)):
# if the sum of the two elements is equal to the value, return Trueif list_of_ints[i] + list_of_ints[j] == value:
returnTrue# if the list does not have two distinct elements that sum to the value, return FalsereturnFalseclassMyTest(unittest.TestCase):
# >>> Result:deftest_example(self):
self.assertTrue(double_sum_to_value([1, 2, 3, 4, 5], 7))
deftest_example_2(self):
self.assertFalse(double_sum_to_value([1, 2, 3, 4, 5], 6))
deftest_example_3(self):
self.assertTrue(double_sum_to_value([1, 2, 3, 4, 5, 6], 7))
# >>> Model: ChatGPT# >>> Prompt:
You are an expert in development.
Rewrite this code to reduce its complexity.
"""
def double_sum_to_value(list_of_ints, value):
if len(list_of_ints) < 2:
return False
else:
for i in range(len(list_of_ints) - 1):
for j in range(i + 1, len(list_of_ints)):
if list_of_ints[i] + list_of_ints[j] == value:
return True
return False
"""# >>> Result:defdouble_sum_to_value(list_of_ints, value):
iflen(list_of_ints) < 2:
returnFalse
seen_values = set()
for num in list_of_ints:
complement = value - num
if complement in seen_values:
returnTrue
seen_values.add(complement)
returnFalse"""
Explanation:
The initial check for the length of list_of_ints is retained to handle
case where there are fewer than two integers, as the logic wouldn't
work in that scenario. We use a set, seen_values, to keep track of
the complements needed to reach the target value.
Instead of iterating through all combinations of numbers, we iterate
through each number in list_of_ints only once. For each number, we
calculate the complement needed to reach the target value. If the
complement is in seen_values, we have found a pair that sums up to
the target value, and we return True. If we finish iterating through
the list without finding a pair, we return False.
This approach reduces the complexity from O(n^2) to O(n), as we only need
to iterate through the list once to check for the sum condition.
Additionally, it avoids unnecessary duplicate calculations by storing the
complements in a set.
"""
2.5 代码文档和代码摘要
以自然语言描述生成源代码摘要。
# >>> Model: ChatGPT# >>> Prompt:
You are an expert in development. Adds an explanation of the code between quotations at the end.
"""
def double_sum_to_value(list_of_ints, value):
if len(list_of_ints) < 2:
return False
else:
for i in range(len(list_of_ints) - 1):
for j in range(i + 1, len(list_of_ints)):
if list_of_ints[i] + list_of_ints[j] == value:
return True
return False
"""# >>> Result:"""
The given code defines a function named double_sum_to_value that takes
in two parameters: list_of_ints, which is a list of integers, and value,
which is an integer. The function checks if there are any two distinct
integers in the list whose sum is equal to the given value.
Here's a breakdown of how the code works:
The function begins with an initial check to see if the length of the
list_of_ints is less than 2. If it is, it means there are not enough
integers in the list to form a pair, so the function returns False.
If the length of the list is 2 or greater, the function proceeds to
iterate through the list using two nested loops. The outer loop iterates
over each element in the list except the last one, denoted by the variable i.
The inner loop iterates over the elements following the current element
of the outer loop, denoted by the variable j. This ensures that every
possible pair of distinct integers is considered.
Within the nested loops, the function checks if the sum of the current
pair of integers, list_of_ints[i] and list_of_ints[j], is equal to the
given value. If it is, the function immediately returns True to indicate
that a pair with the desired sum has been found.
If no such pair is found after exhausting all possible combinations, the
function exits the nested loops and returns False to indicate that there
are no distinct integers in the list that sum up to the given value.
The code utilizes a brute-force approach by checking all possible pairs
of integers. While it works correctly, it has a time complexity of O(n^2)
due to the nested loops, where n is the length of the input list. This
means the execution time grows quadratically with the size of the input
list, which can be inefficient for large lists.
"""
2.6 代码重写
开发人员必须定期编写相同的功能,但仅更改某些名称。生成函数使这些修改变得非常容易。
# >>> Model: ChatGPT# >>> Prompt:
In the following function, change the input variable 'list_of_ints' to 'list_of_revenues'and'value'' to 'revenue'.
def double_sum_to_value(list_of_ints, value):
if len(list_of_ints) < 2:
return False
else:
for i in range(len(list_of_ints) - 1):
for j in range(i + 1, len(list_of_ints)):
if list_of_ints[i] + list_of_ints[j] == value:
return True
return False
# >>> Result:
def double_sum_to_value(list_of_revenues, revenue):
if len(list_of_revenues) < 2:
return False
else:
for i in range(len(list_of_revenues) - 1):
for j in range(i + 1, len(list_of_revenues)):
if list_of_revenues[i] + list_of_revenues[j] == revenue:
return True
return False
# >>> Model: ChatGPT# >>> Prompt:
Convert this function in'C' language.
"""
def double_sum_to_value(list_of_ints, value):
if len(list_of_ints) < 2:
return False
else:
for i in range(len(list_of_ints) - 1):
for j in range(i + 1, len(list_of_ints)):
if list_of_ints[i] + list_of_ints[j] == value:
return True
return False
"""# >>> Result:#include <stdbool.h>bool double_sum_to_value(int list_of_ints[], int length, int value) {
if (length < 2) {
return false;
} else {
for (int i = 0; i < length - 1; i++) {
for (int j = i + 1; j < length; j++) {
if (list_of_ints[i] + list_of_ints[j] == value) {
return true;
}
}
}
return false;
}
}
"""
Explanation:
The function is defined with the return type bool, which represents the
boolean value of True or False in C.
The list_of_ints is passed as an integer array along with its length
length and the target value value.
The condition if (length < 2) is used to check if the length of the
array is less than 2, similar to the Python code.
The nested loops are implemented using for loops in C. The loop
variables i and j iterate over the indices of the array elements.
The condition list_of_ints[i] + list_of_ints[j] == value is checked
to determine if a pair of elements sums up to the target value,
similar to the Python code.
If a pair is found, true is returned, and if no pair is found, false
is returned at the end of the function.
Note: In C, it is important to include the necessary headers, such
stdbool.h, for using the bool data type.
2.8 代码缺陷检查
这是一个要求 LLM 检测提示中提供的源代码中的缺陷的过程。
# >>> Model: ChatGPT# >>> Prompt:
Find defects in this code.
"""
def double_sum_to_value(list_of_ints, value):
for i in range(len(list_of_ints)):
for j in range(i + 1, len(list_of_ints)):
if list_of_ints[i] + list_of_ints[j] == value:
return True
return False
"""# >>> Result:"""
There are a few potential defects in the provided code:
Inadequate Input Validation:
The code does not perform sufficient input validation. It assumes that
list_of_ints will always be a list and value will be a valid integer.
If these assumptions are not met, the code may raise exceptions or produce
incorrect results. It's good practice to validate the input types and
handle any potential errors or edge cases.
Lack of Bounds Checking:
The code uses nested loops to iterate over the indices of list_of_ints.
However, it does not perform any bounds checking to ensure that the
indices are within the valid range of the list. This can lead to
out-of-range errors if the input list is empty or has insufficient
elements. It's important to validate the length of list_of_ints before
iterating over its indices.
No Early Termination:
Once a pair of integers is found that satisfies the sum condition, the
code immediately returns True. However, it continues iterating through
the remaining pairs unnecessarily. This can result in unnecessary
computation and reduced performance. Adding a break statement after
the return True statement would optimize the code by terminating the
loops early.
Inefficient Nested Loop:
The code uses a nested loop to compare each pair of integers in list_of_ints.
This approach has a complexity of O(n^2), where n is the length of
list_of_ints. Depending on the size of the list, this can lead to poor
performance for larger inputs. Consider using alternative approaches,
such as utilizing a set to store seen values or sorting the list and
applying binary search, which can potentially reduce the complexity
to O(n) or O(n log n) respectively.
To address these potential defects, here's an improved version of the code:
"""defdouble_sum_to_value(list_of_ints, value):
ifnotisinstance(list_of_ints, list) ornotisinstance(value, int):
raise ValueError("Invalid input")
iflen(list_of_ints) < 2:
returnFalse
seen_values = set()
for num in list_of_ints:
complement = value - num
if complement in seen_values:
returnTrue
seen_values.add(num)
returnFalse"""
In the updated code:
Input validation is performed to check the type of list_of_ints and value.
The length of list_of_ints is checked to ensure it has at least two elements
before proceeding with the main logic.
A set, seen_values, is used to store previously seen values for efficient
lookup.
If a pair is found that satisfies the sum condition, True is immediately
returned.
The code raises a ValueError if the input types are invalid, providing
clearer error handling.
The code overall has a reduced complexity of O(n), improving performance
compared to the original nested loop implementation.
# >>> Model: ChatGPT# >>> Prompt:
You are a software architect.
Generates the skeleton of a mobile application used to display a map \
and allow users to write comments at a point on the map.
# >>> Result:
Certainly! Here's a high-level skeleton of a mobile application that
displays a map and allows users to write comments at specific points on
the map:
1. User Interface:
. Map View: This is the primary view that displays the map.
. Annotation View: When the user taps on a specific point on the map,
an annotation view is displayed to allow writing comments.
. Comment List: A list view to display the comments associated with
each point on the map.
. User Authentication: Provide a login/signup feature to authenticate
users and associate comments with their accounts.
2. Components and Modules:
. Map SDK Integration: Integrate a map SDK (e.g., Google Maps, Mapbox)
to display the map and handle user interactions like panning and zooming.
. Annotation Management: Implement functionality to add annotations to
the map when the user taps on a specific point. Each annotation can
have associated comments.
. Comment Management: Implement functionality to allow users to write
and post comments. Comments should be associated with the selected
point on the map.
. User Authentication: Implement user authentication and session
management to associate comments with user accounts and provide a
personalized experience.
. Data Persistence: Use a database or storage system to store and
retrieve annotations and comments. This can be done using a server-side
backend or a local database.
3. Workflow:
. User opens the mobile app and is presented with a login/signup screen.
. After successful authentication, the user is directed to the Map View.
. The user can interact with the map, zoom in/out, and pan to navigate
to desired locations.
. When the user taps on a specific point on the map, an annotation view is
displayed.
. The user can write and post comments in the annotation view.
. The comments are saved and associated with the selected point on the map.
. The user can view the comments by tapping on existing annotations or
accessing a comment list view.
. The user can log out or switch to a different user account if needed.
4. Considerations:
. UI/UX Design: Design a user-friendly interface with intuitive map
interactions and clear annotation/comment presentation.
. Data Security: Implement secure authentication and ensure data privacy
for user accounts and comments.
. Performance Optimization: Consider implementing efficient data
retrieval and rendering mechanisms to ensure smooth map interactions
and quick comment loading.
. Offline Support: Implement offline capabilities, allowing users to
view previously loaded map data and comments when there is no internet
connection.
. Error Handling: Implement proper error handling and feedback
mechanisms to inform users of any issues, such as failed comment
submission or map loading errors.
Please note that this is a high-level overview, and the actual
implementation details and choice of technologies may vary depending on the
specific requirements and platform (iOS, Android, etc.) you are targeting.
# Complementary prompt:
What would you recommend in terms of technology for this application?
# Result:
In terms of technology recommendations for developing a mobile application
with map functionality and comment features, here are some popular choices:
1. Mobile App Development Frameworks:
- React Native: A popular cross-platform framework that allows building
mobile apps using JavaScript and React. It offers good performance
and code reusability across iOS and Android platforms.
- Flutter: A cross-platform framework developed by Google that uses
the Dart programming language. It provides a rich set of UI components
and offers fast app development with excellent performance.
- Native Development: If you prefer native development for iOS and
Android separately, you can use Swift/Objective-C for iOS and
Java/Kotlin for Android.
2. Map SDKs:
- Google Maps SDK: Provides comprehensive mapping functionality,
including interactive maps, markers, annotations, and user interaction
support.
- Mapbox SDK: Offers powerful mapping tools with customizable styles,
markers, annotations, and support for user interactions.
3. Backend and Database:
- Backend as a Service (BaaS): Services like Firebase or AWS Amplify
provide ready-to-use backend infrastructure, authentication, and
database support, simplifying backend development.
- Custom Backend: You can build your own backend using technologies
like Node.js, Python, Ruby, or Java, along with databases like MySQL,
PostgreSQL, or MongoDB.
4. User Authentication:
- Firebase Authentication: Provides easy integration for user
authentication with various login methods like email/password, social
media logins, etc.
- OAuth Providers: Utilize OAuth providers like Google, Facebook, or
Twitter for seamless authentication and account creation.
5. Additional Considerations:
- Data Storage: Depending on the scale and requirements of your
application, you can choose a database solution such as Firebase
Realtime Database, Cloud Firestore, or a SQL/NoSQL database for
storing comments and other data.
- API Development: If you plan to develop a custom backend, consider
using frameworks like Express.js (Node.js) or Flask (Python) to build
RESTful APIs for communication between the mobile app and the backend.
It's essential to evaluate the specific requirements, scalability needs,
and development expertise of your team when choosing the technology stack.
Additionally, consider factors like community support, documentation, and
ease of integration with your chosen frameworks.