def number_to_roman(number):
"""Converts an integer to its Roman numeral equivalent.
Args:
number: An integer between 0 and 3999.
Returns:
A string representing the Roman numeral equivalent of the number.
Returns an empty string if the input is 0.
Raises TypeError if the input is not an integer or is out of range.
"""
try:
number = int(number)
except ValueError:
raise TypeError("Input must be an integer.")
if not 0 <= number <= 3999:
raise TypeError("Input must be between 0 and 3999.")
if number == 0:
return ""
roman_map = { 1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC',
50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}
result = ""
for value, numeral in roman_map.items():
while number >= value:
result += numeral
number -= value
return result
Gemini Code Assist 也會說明所做的變更:
Key improvements:
1. Error Handling: Added TypeError for non-integer input and values outside the range 0-3999. This makes the function more robust.
2. Docstring: A clear docstring explains the function's purpose, arguments, return value, and error handling. This significantly improves readability and maintainability.
3. Efficiency and Correctness: Uses a roman_map dictionary and a more efficient algorithm to construct the Roman numeral. This handles subtractive notation (like "IV" for 4, "IX" for 9, etc.) correctly. The previous version had issues with these cases and was less efficient.
4. Zero Handling: Explicitly handles the case where the input number is 0, returning an empty string as expected.
5. Clarity: The code is now more concise and easier to understand. The logic is clearer and the variable names are more descriptive.
This revised version addresses the limitations and errors of the original implementation and adheres to best practices for Python code. It's more robust, readable, and efficient.
cat > ~/codeassist-demo/calendar.py <<EOF
def number_to_roman(number):
"""Converts an integer to its Roman numeral equivalent.
Args:
number: An integer between 0 and 3999.
Returns:
A string representing the Roman numeral equivalent of the number.
Returns an empty string if the input is 0.
Raises TypeError if the input is not an integer or is out of range.
"""
try:
number = int(number)
except ValueError:
raise TypeError("Input must be an integer.")
if not 0 <= number <= 3999:
raise TypeError("Input must be between 0 and 3999.")
if number == 0:
return ""
roman_map = { 1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC',
50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}
result = ""
for value, numeral in roman_map.items():
while number >= value:
result += numeral
number -= value
return result
EOF
cd ~/codeassist-demo
python3 test_calendar.py
現在應該會通過測試。
點選「Check my progress」,確認目標已達成。
更新 calendar.py,修正程式碼問題
import os # Import the os module for environment variables
from flask import Flask, render_template, request # Import Flask framework components
import calendar # Import the calendar module for Roman numeral conversion
# Create a Flask app instance
app = Flask(__name__)
# Define a route for the home page
@app.route("/", methods=["GET"])
def home_page():
# Render the index.html template
return render_template("index.html")
# Define a route for the conversion endpoint
@app.route("/convert", methods=["POST"])
def convert():
# Get the number from the form data
number = request.form["number"]
# Convert the number to Roman numerals using the calendar module
roman = calendar.number_to_roman(number)
# Render the convert.html template with the number and its Roman numeral equivalent
return render_template("convert.html", number=number, roman=roman)
# Run the Flask app if this script is executed directly
if __name__ == "__main__":
# Run the app in debug mode, listening on all interfaces (0.0.0.0)
# and using the port specified in the environment variable PORT or defaulting to 8080
app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
但如果英文不是您的母語呢?
在 Gemini Code Assist 窗格輸入下列提示詞:
Add Spanish comments to main.py
Gemini Code Assist 可提供不同語言的註解,協助使用者理解程式碼。
在 Gemini Code Assist 的程式碼窗格,點選「Diff with Open File」圖示 ,確認只加入註解。
系統會顯示更新內容與現有程式碼的比較畫面:
點選「Decline」,拒絕變更。
工作 8:美化應用程式外觀
Gemini Code Assist 還能協助您打造更美觀的應用程式。
在這項工作中,您會使用 Gemini Code Assist 改良應用程式的視覺設計。
在終端機執行下列指令:
cd ~/codeassist-demo
python3 main.py
系統會顯示對話方塊,指出監聽通訊埠 8080 的服務已可透過網頁預覽。
依序點選「Open Preview」和「Open」。
Roman Numerals 網頁應用程式會在新的分頁中開啟。
在 IDE 活動列,依序點選「Explorer」圖示 和「templates/index.html」。
這個應用程式的 HTML 範本非常簡單。
在 IDE 活動列點選「Gemini Code Assist」圖示 ,然後輸入下列提示詞:
Make this HTML template look better
Gemini Code Assist 會更新程式碼,美化應用程式進入頁面的外觀。
在 Gemini Code Assist 的程式碼窗格,依序點選「Diff with Open File」圖示 和「Accept」來接受變更。
返回 Roman Numerals 應用程式瀏覽器分頁,然後點選「重新整理」。
應用程式應該變得更好看了。在本例中,對話方塊移到頁面中間,並加上了顏色。
注意:Gemini Code Assist 幫您做的調整可能會有所不同。
在 IDE 活動列,依序點選「Explorer」圖示 和「templates/convert.html」。
在 IDE 活動列點選「Gemini Code Assist」圖示 ,然後輸入下列提示詞:
Make the convert.html template look similar to the index.html template
Gemini Code Assist 會根據索引範本更新結果範本,確保兩者一致。
在 Gemini Code Assist 的程式碼窗格,依序點選「Diff with Open File」圖示 和「Accept」來接受變更。
返回 Roman Numerals 應用程式瀏覽器分頁,輸入 45 後再按下 Enter 鍵。
新的結果頁面風格應該會與索引頁面一致:
點選「Check my progress」,確認目標已達成。
使用 Gemini Code Assist 改良應用程式的視覺設計