
Claude 3.7 Sonnet 和 Qwen 2.5 Coder 32B Instruct 是用於程式設計和程式碼生成的領先人工智慧模型。Qwen 2.5 以其高效和清晰的編碼風格脫穎而出,而 Claude 3.7 Sonnet 則在上下文理解和適應性方面大放異彩。在本文中,我將對它們生成的程式碼進行比較,重點關注語法質量、結構連貫性和整體效能。對它們編碼優勢的詳細分析將幫助您選擇最適合您程式設計需求的模型。
Claude 3.7 Sonnet和Qwen 2.5 Coder的規格
本節比較 QwenLM 和 Anthropic AI 的最新編碼語言模型。
規格 |
Qwen 2.5 Coder 32B |
Claude 3.7 Sonnet |
輸入內容視窗 |
最多 128K tokens |
最多 200K tokens |
最大輸出Token |
8K tokens |
128K tokens |
引數數量 |
320 億 |
不詳 |
釋出日期 |
2024年11月12日 |
2025年2月20日 |
每秒輸出Token |
50 tokens/秒 |
100 tokens/秒 |
基準測試:Claude 3.7 Sonnet vs Qwen 2.5 Coder
以下是不同基準測試的結果:
Qwen 2.5 Coder

Source: Qwen
- 程式碼生成:Qwen2.5-Coder-32B-Instruct 在多個流行的程式碼生成基準測試(EvalPlus、LiveCodeBench、BigCodeBench)中取得了開源模型中的最佳效能,其效能與 GPT-4o 相比也具有競爭力。
- 程式碼糾正:程式碼糾正是一項重要的程式設計技能。Qwen2.5-Coder-32B-Instruct 可以幫助使用者糾正程式碼中的錯誤,提高程式設計效率。Aider 是程式碼糾正的常用基準,Qwen2.5-Coder-32B-Instruct 在 Aider 上的得分為 73.7,與 GPT-4o 的表現相當。
- 程式碼推理:程式碼推理是指模型學習程式碼執行過程並準確預測模型輸入和輸出的能力。最近釋出的 Qwen2.5-Coder-7B-Instruct 在程式碼推理方面的表現已經令人印象深刻,而這個 32B 模型則更進一步。
Claude 3.7 Sonnet

Source: Anthropic AI
- Claude 3.7 Sonnet 在 SWE-bench Verified(評估人工智慧模型解決真實世界軟體問題的能力)上取得了最先進的效能。有關腳手架的更多資訊,請參閱附錄。
- 它在 TAU-bench 上取得了一流的效能,TAU-bench 是一個測試人工智慧代理在複雜現實世界任務中與使用者和工具互動的框架。有關腳手架的更多資訊,請參閱附錄。
- 它在指令遵循、一般推理、多模態能力和代理編碼等方面表現出色,在數學和科學方面的擴充套件思維能力也有顯著提升。除了傳統的基準測試外,它在我們的 Pokémon 遊戲測試 中的表現甚至超過了之前的所有模型。
Claude 3.7 Sonnet與Qwen 2.5 Coder任務能力測試對比
在本節中,我將使用不同的提示來測試這兩個模型的編碼能力,並確定哪個模型在每個任務中表現出色。
任務 1:HTML Code
提示詞:Create a single HTML file that sets up a basic Three.js scene with a rotating 3D globe. The globe should have high detail (64 segments), use a placeholder texture for the Earth’s surface, and include ambient and directional lighting for realistic shading. Implement smooth rotation animation around the Y-axis, handle window resizing to maintain proper proportions, and use antialiasing for smoother edges. Explanation: Scene Setup : Initializes the scene, camera, and renderer with antialiasing. Sphere Geometry : Creates a high-detail sphere geometry (64 segments). Texture : Loads a placeholder texture using THREE.TextureLoader. Material & Mesh : Applies the texture to the sphere material and creates a mesh for the globe. Lighting : Adds ambient and directional lights to enhance the scene’s realism. Animation : Continuously rotates the globe around its Y-axis. Resize Handling : Adjusts the renderer size and camera aspect ratio when the window is resized.
輸出:
觀察對比
Qwen 2.5 Coder
優點
- 在啟用抗鋸齒的情況下正確初始化 Three.js 場景、攝像頭和渲染器。
- 使用 SphereGeometry(1, 64, 64) 建立高細節球體,滿足球體細節要求。
- 使用 THREE.TextureLoader 正確載入紋理,使用的是來自 threejs.org/examples/…. 的高質量佔位符。
- 實現環境光照和定向光照,以達到逼真效果。
- 通過 requestAnimationFrame() 平滑旋轉地球儀。
- 通過更新攝像頭長寬比和渲染器大小,能很好地處理視窗大小調整。
缺點:
- 使用硬編碼的外部紋理路徑,如果連結不可用,可能會中斷。
- 缺乏載入指示器,導致在紋理載入前螢幕一片空白。
Claude 3.7 Sonnet
優點
- 在紋理載入過程中顯示 “Loading…(正在載入…)”,增強使用者體驗。
- 使用 THREE.PerspectiveCamera(45, aspectRatio, 0.1, 1000) 設定場景和攝像機,視野範圍比 Qwen 的 75 度設定更廣。
- 使用 SphereGeometry(1, 64, 64) 製作細節豐富的球體,滿足要求。
- 使用更高強度(1.0)的環境光照和定向光照,以獲得更逼真的效果。
- 使用 requestAnimationFrame() 確保流暢的動畫效果。
- 通過 renderer.setPixelRatio(window.devicePixelRatio),改進了移動縮放功能,以適應高 DPI 螢幕。
- 整潔地組織程式碼,分離紋理載入和呈現邏輯。
缺點
- 依賴於無效的紋理路徑(textureLoader.load(‘/api/placeholder/1024/512’)),除非修復,否則會導致紋理丟失。
- 將其封裝在紋理載入回撥中會延遲渲染,如果紋理載入失敗,渲染可能會停止。
- 定義 bumpScale:定義了 0.02 的凹凸貼圖,導致效果無效。
Qwen 2.5 Coder 在紋理載入功能方面提供了更可靠的基準,而 Claude 3.7 Sonnet 則將使用者體驗和可擴充套件性放在首位,但在紋理路徑和凹凸貼圖等實現細節方面有所欠缺。
結論
Claude 3.7 Sonnet ❌ | Qwen 2.5 Coder ✅
任務 2:資料視覺化
提示詞:Write a Python program that visualizes the sorting process of an array using Matplotlib. Implement the Merge Sort algorithm and display the array as a bar chart after each merge operation. The bars should dynamically update to show progress.
輸出:

觀察對比
Qwen 2.5 Coder
優點
- 簡潔明瞭:採用簡約方法,增強程式碼的可讀性和可理解性。
- 基於生成器的排序:利用收益率有效返回中間排序狀態。
- 使用 FuncAnimation:採用 Matplotlib 的動畫框架,實現流暢有效的視覺化。
- 最小化依賴性:只需要 NumPy 和 Matplotlib,確保了設定和執行的簡便性。
缺點
- 動畫實現不正確:更新函式預期會出現條形圖,但卻無法在視覺化中正確更新條形圖的高度。
- 初始化缺失(init 函式問題):初始化函式在條形圖正確定義之前就引用了它們。
- 視覺反饋有限:缺乏顏色變化或標籤來突出顯示排序步驟,從而降低了清晰度。
- 固定的排序速度:無法調整動畫速度的延遲,限制了使用者的控制。
Claude 3.7 Sonnet
優點
- 增強視覺化:使用彩色條(皇家藍、橙色和紅色)突出顯示活動排序區域,提高視覺清晰度。
- 實時狀態更新:動態顯示排序步驟資訊,提供更好的使用者反饋。
- 可調速度 :允許通過延遲(time.sleep(self.speed))對排序速度進行微調,從而提供使用者控制。
- 互動性更強,資訊量更大:包括一個合併操作計數器和跟蹤進度的文字更新,增強了互動性。
缺點
- 程式碼更復雜:包含更多行程式碼,初學者較難掌握。
- 阻塞執行:依賴 time.sleep(),在某些環境下可能會破壞流暢的動畫效果。
- 嚴重影響效能:頻繁更新整個圖形,可能會導致大型資料集的延遲。
結論
Claude 3.7 Sonnet ✅ | Qwen 2.5 Coder ❌
任務 3:最大子陣列
提示詞:Design and implement an efficient algorithm to solve the “Maximum Subarray Sum” problem, commonly known as Kadane’s Algorithm. Given an array of integers, your task is to find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Qwen 2.5 Coder 32B
def max_subarray_sum(arr):
raise ValueError("Array must contain at least one number")
# Iterate through the array starting from the second element
for i in range(1, len(arr)):
maxEndingHere = max(arr[i], maxEndingHere + arr[i])
# Update maxSoFar if needed
maxSoFar = max(maxSoFar, maxEndingHere)
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("Maximum subarray sum is:", max_subarray_sum(arr))
def max_subarray_sum(arr):
if not arr:
raise ValueError("Array must contain at least one number")
# Initialize variables
maxSoFar = arr[0]
maxEndingHere = arr[0]
# Iterate through the array starting from the second element
for i in range(1, len(arr)):
# Update maxEndingHere
maxEndingHere = max(arr[i], maxEndingHere + arr[i])
# Update maxSoFar if needed
maxSoFar = max(maxSoFar, maxEndingHere)
return maxSoFar
# Example usage
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("Maximum subarray sum is:", max_subarray_sum(arr))
def max_subarray_sum(arr):
if not arr:
raise ValueError("Array must contain at least one number")
# Initialize variables
maxSoFar = arr[0]
maxEndingHere = arr[0]
# Iterate through the array starting from the second element
for i in range(1, len(arr)):
# Update maxEndingHere
maxEndingHere = max(arr[i], maxEndingHere + arr[i])
# Update maxSoFar if needed
maxSoFar = max(maxSoFar, maxEndingHere)
return maxSoFar
# Example usage
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("Maximum subarray sum is:", max_subarray_sum(arr))
輸出:
Maximum subarray sum is: 6
Claude 3.7 Sonnet
function maxSubArray(nums) {
// Handle edge case of empty array
if (nums.length === 0) return 0;
let maxSum = nums[0]; // Best solution found so far
let currentSum = nums[0]; // Best solution ending at current position
for (let i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
{ input: [-2, 1, -3, 4, -1, 2, 1, -5, 4], expected: 6 }, // Subarray [4, -1, 2, 1]
{ input: [1], expected: 1 }, // Single element
{ input: [-1], expected: -1 }, // Single negative element
{ input: [-2, -3, -1, -5], expected: -1 }, // All negative elements
{ input: [5, 4, -1, 7, 8], expected: 23 } // Subarray [5, 4, -1, 7, 8] (entire array)
for (const test of testCases) {
const result = maxSubArray(test.input);
console.log(`Input: [${test.input}]`);
console.log(`Expected: ${test.expected}, Result: ${result}`);
console.log(`Test ${result === test.expected ? 'PASSED' : 'FAILED'}`);
function maxSubArray(nums) {
// Handle edge case of empty array
if (nums.length === 0) return 0;
let maxSum = nums[0]; // Best solution found so far
let currentSum = nums[0]; // Best solution ending at current position
for (let i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
// Example usage
function testKadane() {
const testCases = [
{ input: [-2, 1, -3, 4, -1, 2, 1, -5, 4], expected: 6 }, // Subarray [4, -1, 2, 1]
{ input: [1], expected: 1 }, // Single element
{ input: [-1], expected: -1 }, // Single negative element
{ input: [-2, -3, -1, -5], expected: -1 }, // All negative elements
{ input: [5, 4, -1, 7, 8], expected: 23 } // Subarray [5, 4, -1, 7, 8] (entire array)
];
for (const test of testCases) {
const result = maxSubArray(test.input);
console.log(`Input: [${test.input}]`);
console.log(`Expected: ${test.expected}, Result: ${result}`);
console.log(`Test ${result === test.expected ? 'PASSED' : 'FAILED'}`);
console.log('---');
}
}
testKadane();
function maxSubArray(nums) {
// Handle edge case of empty array
if (nums.length === 0) return 0;
let maxSum = nums[0]; // Best solution found so far
let currentSum = nums[0]; // Best solution ending at current position
for (let i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
// Example usage
function testKadane() {
const testCases = [
{ input: [-2, 1, -3, 4, -1, 2, 1, -5, 4], expected: 6 }, // Subarray [4, -1, 2, 1]
{ input: [1], expected: 1 }, // Single element
{ input: [-1], expected: -1 }, // Single negative element
{ input: [-2, -3, -1, -5], expected: -1 }, // All negative elements
{ input: [5, 4, -1, 7, 8], expected: 23 } // Subarray [5, 4, -1, 7, 8] (entire array)
];
for (const test of testCases) {
const result = maxSubArray(test.input);
console.log(`Input: [${test.input}]`);
console.log(`Expected: ${test.expected}, Result: ${result}`);
console.log(`Test ${result === test.expected ? 'PASSED' : 'FAILED'}`);
console.log('---');
}
}
testKadane();
輸出:
Input: [-2,1,-3,4,-1,2,1,-5,4]Expected: 6, Result: 6Test PASSED---Input: [1]Expected: 1, Result: 1Test PASSED---Input: [-1]Expected: -1, Result: -1Test PASSED---Input: [-2,-3,-1,-5]Expected: -1, Result: -1Test PASSED---Input: [5,4,-1,7,8]Expected: 23, Result: 23Test PASSED---
觀察對比
Qwen 2.5 Coder 32B
優點
- 簡潔明瞭:採用邏輯清晰的簡約方法。
- 高效(複雜度為 O(n)):以最佳方式執行 Kadane 演算法。
- 處理空陣列:如果陣列為空,會引發錯誤,防止出現未定義的行為。
缺點
- 缺乏邊緣案例測試:沒有內建測試用例來驗證各種情況。
- 沒有詳細解釋:不提供幫助初學者理解邏輯的內聯註釋。
- 不返回子陣列:只返回最大和,不返回產生最大和的子陣列。
Claude 3.7 Sonnet
優點
- 程式碼註釋詳細:每一步都有詳細解釋。
- 包含測試用例:包含多個測試用例,可驗證不同場景下的正確性。
- 優雅地處理邊緣情況:測試空陣列、單元素陣列和全負數。
- 高效(O(n) 複雜度):採用與 Qwen 實現相同的最優方法。
缺點
- 只返回最大和:與 Qwen 的版本一樣,它不返回實際的子陣列。
- 不處理空陣列錯誤:返回 0 而不是丟擲錯誤。
結論
Claude 3.7 Sonnet ✅ | Qwen 2.5 Coder ❌
任務 4:迷宮解法
提示詞:Use an SQLite database to generate and solve a simple 5×5 ASCII maze.The maze should be stored in a table Maze(x, y, type) where type is ‘wall’ or ‘path’. Implement a SQL query to find the shortest path from (0,0) to (4,4) using recursive Common Table Expressions (CTEs).
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('maze.db')
CREATE TABLE IF NOT EXISTS Maze (
# Insert the sample maze into the table
(0, 0, 'path'), (0, 1, 'path'), (0, 2, 'path'), (0, 3, 'path'), (0, 4, 'path'),
(1, 0, 'path'), (1, 1, 'path'), (1, 2, 'path'), (1, 3, 'wall'), (1, 4, 'path'),
(2, 0, 'path'), (2, 1, 'wall'), (2, 2, 'path'), (2, 3, 'wall'), (2, 4, 'path'),
(3, 0, 'path'), (3, 1, 'path'), (3, 2, 'path'), (3, 3, 'wall'), (3, 4, 'path'),
(4, 0, 'path'), (4, 1, 'path'), (4, 2, 'path'), (4, 3, 'path'), (4, 4, 'path'),
(1, 2, 'path'), (2, 2, 'path'), (3, 2, 'path') # Ensure paths are correctly set
cursor.executemany('INSERT INTO Maze (x, y, type) VALUES (?, ?, ?)', maze_data)
# Define the recursive CTE query to find the shortest path
-- Anchor member: Start at (0, 0)
SELECT x, y, type, CAST(CAST(x AS TEXT) || ',' || CAST(y AS TEXT) AS TEXT) AS path, 0 AS cost
-- Recursive member: Explore neighbors
SELECT m.x, m.y, m.type, p.path || ',' || CAST(m.x AS TEXT) || ',' || CAST(m.y AS TEXT) AS path, p.cost + 1 AS cost
JOIN Path p ON (m.x = p.x + 1 AND m.y = p.y) OR
(m.x = p.x - 1 AND m.y = p.y) OR
(m.x = p.x AND m.y = p.y + 1) OR
(m.x = p.x AND m.y = p.y - 1)
WHERE m.type = 'path' AND
CAST(m.x AS TEXT) || ',' || CAST(m.y AS TEXT) NOT IN (SELECT SUBSTR(path, -4) FROM Path)
-- Select the shortest path to (4, 4)
result = cursor.fetchone()
print(f"Shortest path: {path}")
import sqlite3
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('maze.db')
cursor = conn.cursor()
# Create the Maze table
cursor.execute('''
CREATE TABLE IF NOT EXISTS Maze (
x INTEGER,
y INTEGER,
type TEXT,
PRIMARY KEY (x, y)
)
''')
# Insert the sample maze into the table
maze_data = [
(0, 0, 'path'), (0, 1, 'path'), (0, 2, 'path'), (0, 3, 'path'), (0, 4, 'path'),
(1, 0, 'path'), (1, 1, 'path'), (1, 2, 'path'), (1, 3, 'wall'), (1, 4, 'path'),
(2, 0, 'path'), (2, 1, 'wall'), (2, 2, 'path'), (2, 3, 'wall'), (2, 4, 'path'),
(3, 0, 'path'), (3, 1, 'path'), (3, 2, 'path'), (3, 3, 'wall'), (3, 4, 'path'),
(4, 0, 'path'), (4, 1, 'path'), (4, 2, 'path'), (4, 3, 'path'), (4, 4, 'path'),
(1, 2, 'path'), (2, 2, 'path'), (3, 2, 'path') # Ensure paths are correctly set
]
# Insert the maze data
cursor.executemany('INSERT INTO Maze (x, y, type) VALUES (?, ?, ?)', maze_data)
conn.commit()
# Define the recursive CTE query to find the shortest path
query = '''
WITH RECURSIVE Path AS (
-- Anchor member: Start at (0, 0)
SELECT x, y, type, CAST(CAST(x AS TEXT) || ',' || CAST(y AS TEXT) AS TEXT) AS path, 0 AS cost
FROM Maze
WHERE x = 0 AND y = 0
UNION ALL
-- Recursive member: Explore neighbors
SELECT m.x, m.y, m.type, p.path || ',' || CAST(m.x AS TEXT) || ',' || CAST(m.y AS TEXT) AS path, p.cost + 1 AS cost
FROM Maze m
JOIN Path p ON (m.x = p.x + 1 AND m.y = p.y) OR
(m.x = p.x - 1 AND m.y = p.y) OR
(m.x = p.x AND m.y = p.y + 1) OR
(m.x = p.x AND m.y = p.y - 1)
WHERE m.type = 'path' AND
m.x BETWEEN 0 AND 4 AND
m.y BETWEEN 0 AND 4 AND
CAST(m.x AS TEXT) || ',' || CAST(m.y AS TEXT) NOT IN (SELECT SUBSTR(path, -4) FROM Path)
)
-- Select the shortest path to (4, 4)
SELECT path, cost
FROM Path
WHERE x = 4 AND y = 4
ORDER BY cost ASC
LIMIT 1
'''
# Execute the query
cursor.execute(query)
result = cursor.fetchone()
if result:
path, cost = result
print(f"Shortest path: {path}")
print(f"Cost: {cost}")
else:
print("No path found")
# Close the connection
conn.close()
import sqlite3
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('maze.db')
cursor = conn.cursor()
# Create the Maze table
cursor.execute('''
CREATE TABLE IF NOT EXISTS Maze (
x INTEGER,
y INTEGER,
type TEXT,
PRIMARY KEY (x, y)
)
''')
# Insert the sample maze into the table
maze_data = [
(0, 0, 'path'), (0, 1, 'path'), (0, 2, 'path'), (0, 3, 'path'), (0, 4, 'path'),
(1, 0, 'path'), (1, 1, 'path'), (1, 2, 'path'), (1, 3, 'wall'), (1, 4, 'path'),
(2, 0, 'path'), (2, 1, 'wall'), (2, 2, 'path'), (2, 3, 'wall'), (2, 4, 'path'),
(3, 0, 'path'), (3, 1, 'path'), (3, 2, 'path'), (3, 3, 'wall'), (3, 4, 'path'),
(4, 0, 'path'), (4, 1, 'path'), (4, 2, 'path'), (4, 3, 'path'), (4, 4, 'path'),
(1, 2, 'path'), (2, 2, 'path'), (3, 2, 'path') # Ensure paths are correctly set
]
# Insert the maze data
cursor.executemany('INSERT INTO Maze (x, y, type) VALUES (?, ?, ?)', maze_data)
conn.commit()
# Define the recursive CTE query to find the shortest path
query = '''
WITH RECURSIVE Path AS (
-- Anchor member: Start at (0, 0)
SELECT x, y, type, CAST(CAST(x AS TEXT) || ',' || CAST(y AS TEXT) AS TEXT) AS path, 0 AS cost
FROM Maze
WHERE x = 0 AND y = 0
UNION ALL
-- Recursive member: Explore neighbors
SELECT m.x, m.y, m.type, p.path || ',' || CAST(m.x AS TEXT) || ',' || CAST(m.y AS TEXT) AS path, p.cost + 1 AS cost
FROM Maze m
JOIN Path p ON (m.x = p.x + 1 AND m.y = p.y) OR
(m.x = p.x - 1 AND m.y = p.y) OR
(m.x = p.x AND m.y = p.y + 1) OR
(m.x = p.x AND m.y = p.y - 1)
WHERE m.type = 'path' AND
m.x BETWEEN 0 AND 4 AND
m.y BETWEEN 0 AND 4 AND
CAST(m.x AS TEXT) || ',' || CAST(m.y AS TEXT) NOT IN (SELECT SUBSTR(path, -4) FROM Path)
)
-- Select the shortest path to (4, 4)
SELECT path, cost
FROM Path
WHERE x = 4 AND y = 4
ORDER BY cost ASC
LIMIT 1
'''
# Execute the query
cursor.execute(query)
result = cursor.fetchone()
if result:
path, cost = result
print(f"Shortest path: {path}")
print(f"Cost: {cost}")
else:
print("No path found")
# Close the connection
conn.close()
輸出:
---------------------------------------------------------------------------
IntegrityError Traceback (most recent call last)
<ipython-input-7-69b873cc8b5b> in <cell line: 28>()
27 # Insert the maze data
---> 28 cursor.executemany('INSERT INTO Maze (x, y, type) VALUES (?, ?, ?)', maze_data)
IntegrityError: UNIQUE constraint failed: Maze.x, Maze.y
---------------------------------------------------------------------------
IntegrityError Traceback (most recent call last)
<ipython-input-7-69b873cc8b5b> in <cell line: 28>()
26
27 # Insert the maze data
---> 28 cursor.executemany('INSERT INTO Maze (x, y, type) VALUES (?, ?, ?)', maze_data)
29 conn.commit()
30
IntegrityError: UNIQUE constraint failed: Maze.x, Maze.y
---------------------------------------------------------------------------
IntegrityError Traceback (most recent call last)
<ipython-input-7-69b873cc8b5b> in <cell line: 28>()
26
27 # Insert the maze data
---> 28 cursor.executemany('INSERT INTO Maze (x, y, type) VALUES (?, ?, ?)', maze_data)
29 conn.commit()
30
IntegrityError: UNIQUE constraint failed: Maze.x, Maze.y
Claude 3.7 Sonnet
"""Create and initialize the SQLite database for the maze."""
conn = sqlite3.connect(':memory:') # Using in-memory database for simplicity
def generate_maze(cursor):
"""Generate a random 5x5 maze and store it in the database."""
# First, fill everything with walls
cursor.execute('INSERT INTO Maze VALUES (?, ?, ?)', (x, y, 'wall'))
# Create a simple maze with a guaranteed path from start to end
# Using a simplified version of randomized DFS for maze generation
# Set start and end as paths
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', 0, 0))
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', 4, 4))
# Get unvisited neighbors
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for dx, dy in directions:
if 0 <= nx < 5 and 0 <= ny < 5 and (nx, ny) not in visited:
neighbors.append((nx, ny))
# Choose a random unvisited neighbor
nx, ny = random.choice(neighbors)
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', nx, ny))
# Make sure there's a valid path from start to end
# This is a simplified approach and might create a very direct path
def make_valid_path(cursor):
"""Ensure there's a valid path from (0,0) to (4,4)."""
# Simple approach: create a direct path if needed
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', i, i))
"""Print the maze in ASCII format."""
cursor.execute('SELECT x, y, type FROM Maze ORDER BY y, x')
maze_grid = [['#' for _ in range(5)] for _ in range(5)]
for x, y, cell_type in rows:
maze_grid[y][x] = '#' if cell_type == 'wall' else ' '
def print_solution_path(cursor, path):
"""Print the maze with the solution path marked."""
cursor.execute('SELECT x, y, type FROM Maze ORDER BY y, x')
maze_grid = [['#' for _ in range(5)] for _ in range(5)]
for x, y, cell_type in rows:
maze_grid[y][x] = '#' if cell_type == 'wall' else ' '
print("\nSolution Path:")
def solve_maze_with_sql(cursor):
"""Solve the maze using recursive Common Table Expressions (CTE) in SQL."""
PathFinder(x, y, path, visited) AS (
SELECT 0, 0, '(0,0)', '(0,0)'
-- Recursive part: explore in four directions
WHEN m.type = 'path' AND direction = 0 THEN p.x + 1
WHEN m.type = 'path' AND direction = 1 THEN p.x
WHEN m.type = 'path' AND direction = 2 THEN p.x - 1
WHEN m.type = 'path' AND direction = 3 THEN p.x
WHEN m.type = 'path' AND direction = 0 THEN p.y
WHEN m.type = 'path' AND direction = 1 THEN p.y + 1
WHEN m.type = 'path' AND direction = 2 THEN p.y
WHEN m.type = 'path' AND direction = 3 THEN p.y - 1
WHEN m.type = 'path' AND direction = 0 THEN p.x + 1
WHEN m.type = 'path' AND direction = 1 THEN p.x
WHEN m.type = 'path' AND direction = 2 THEN p.x - 1
WHEN m.type = 'path' AND direction = 3 THEN p.x
WHEN m.type = 'path' AND direction = 0 THEN p.y
WHEN m.type = 'path' AND direction = 1 THEN p.y + 1
WHEN m.type = 'path' AND direction = 2 THEN p.y
WHEN m.type = 'path' AND direction = 3 THEN p.y - 1
p.visited || ',' || '(' ||
WHEN m.type = 'path' AND direction = 0 THEN p.x + 1
WHEN m.type = 'path' AND direction = 1 THEN p.x
WHEN m.type = 'path' AND direction = 2 THEN p.x - 1
WHEN m.type = 'path' AND direction = 3 THEN p.x
WHEN m.type = 'path' AND direction = 0 THEN p.y
WHEN m.type = 'path' AND direction = 1 THEN p.y + 1
WHEN m.type = 'path' AND direction = 2 THEN p.y
WHEN m.type = 'path' AND direction = 3 THEN p.y - 1
(SELECT 0 AS direction UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) AS dirs,
-- 0: right, 1: down, 2: left, 3: up
(dirs.direction = 0 AND m.x = p.x + 1 AND m.y = p.y) OR
(dirs.direction = 1 AND m.x = p.x AND m.y = p.y + 1) OR
(dirs.direction = 2 AND m.x = p.x - 1 AND m.y = p.y) OR
(dirs.direction = 3 AND m.x = p.x AND m.y = p.y - 1)
-- Check if the new position is a valid path and hasn't been visited
AND p.visited NOT LIKE '%(' || m.x || ',' || m.y || ')%'
-- Select the shortest path to the destination
result = cursor.fetchone()
print("No solution found!")
# Parse the path string into coordinates
coord_strs = path_str.split('->')
for coord_str in coord_strs:
# Extract x and y from strings like "(0,0)"
coord = coord_str.strip('()').split(',')
path.append((int(coord[0]), int(coord[1])))
conn, cursor = create_database()
# Print the generated maze
print("\nSolving maze with SQL recursive CTE...")
path = solve_maze_with_sql(cursor)
print(f"Solution found! Path length: {len(path)}")
print_solution_path(cursor, path)
if __name__ == "__main__":
import sqlite3
import random
def create_database():
"""Create and initialize the SQLite database for the maze."""
conn = sqlite3.connect(':memory:') # Using in-memory database for simplicity
cursor = conn.cursor()
# Create the maze table
cursor.execute('''
CREATE TABLE Maze (
x INTEGER,
y INTEGER,
type TEXT,
PRIMARY KEY (x, y)
)
''')
# Generate a random maze
generate_maze(cursor)
return conn, cursor
def generate_maze(cursor):
"""Generate a random 5x5 maze and store it in the database."""
# First, fill everything with walls
for x in range(5):
for y in range(5):
cursor.execute('INSERT INTO Maze VALUES (?, ?, ?)', (x, y, 'wall'))
# Create a simple maze with a guaranteed path from start to end
# Using a simplified version of randomized DFS for maze generation
visited = set()
stack = [(0, 0)]
visited.add((0, 0))
# Set start and end as paths
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', 0, 0))
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', 4, 4))
while stack:
x, y = stack[-1]
# Get unvisited neighbors
neighbors = []
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < 5 and 0 <= ny < 5 and (nx, ny) not in visited:
neighbors.append((nx, ny))
if neighbors:
# Choose a random unvisited neighbor
nx, ny = random.choice(neighbors)
visited.add((nx, ny))
stack.append((nx, ny))
# Mark as path
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', nx, ny))
else:
# Backtrack
stack.pop()
# Make sure there's a valid path from start to end
# This is a simplified approach and might create a very direct path
make_valid_path(cursor)
def make_valid_path(cursor):
"""Ensure there's a valid path from (0,0) to (4,4)."""
# Simple approach: create a direct path if needed
for i in range(5):
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', i, i))
def print_maze(cursor):
"""Print the maze in ASCII format."""
cursor.execute('SELECT x, y, type FROM Maze ORDER BY y, x')
rows = cursor.fetchall()
maze_grid = [['#' for _ in range(5)] for _ in range(5)]
for x, y, cell_type in rows:
maze_grid[y][x] = '#' if cell_type == 'wall' else ' '
print("Maze:")
for row in maze_grid:
print(''.join(row))
def print_solution_path(cursor, path):
"""Print the maze with the solution path marked."""
cursor.execute('SELECT x, y, type FROM Maze ORDER BY y, x')
rows = cursor.fetchall()
# Create maze grid
maze_grid = [['#' for _ in range(5)] for _ in range(5)]
for x, y, cell_type in rows:
maze_grid[y][x] = '#' if cell_type == 'wall' else ' '
# Mark path
for x, y in path:
maze_grid[y][x] = 'X'
# Mark start and end
maze_grid[0][0] = 'S'
maze_grid[4][4] = 'E'
print("\nSolution Path:")
for row in maze_grid:
print(''.join(row))
def solve_maze_with_sql(cursor):
"""Solve the maze using recursive Common Table Expressions (CTE) in SQL."""
query = '''
WITH RECURSIVE
-- Define starting point
PathFinder(x, y, path, visited) AS (
SELECT 0, 0, '(0,0)', '(0,0)'
UNION ALL
-- Recursive part: explore in four directions
SELECT
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.x + 1
WHEN m.type = 'path' AND direction = 1 THEN p.x
WHEN m.type = 'path' AND direction = 2 THEN p.x - 1
WHEN m.type = 'path' AND direction = 3 THEN p.x
ELSE p.x
END,
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.y
WHEN m.type = 'path' AND direction = 1 THEN p.y + 1
WHEN m.type = 'path' AND direction = 2 THEN p.y
WHEN m.type = 'path' AND direction = 3 THEN p.y - 1
ELSE p.y
END,
p.path || '->' || '(' ||
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.x + 1
WHEN m.type = 'path' AND direction = 1 THEN p.x
WHEN m.type = 'path' AND direction = 2 THEN p.x - 1
WHEN m.type = 'path' AND direction = 3 THEN p.x
ELSE p.x
END || ',' ||
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.y
WHEN m.type = 'path' AND direction = 1 THEN p.y + 1
WHEN m.type = 'path' AND direction = 2 THEN p.y
WHEN m.type = 'path' AND direction = 3 THEN p.y - 1
ELSE p.y
END || ')',
p.visited || ',' || '(' ||
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.x + 1
WHEN m.type = 'path' AND direction = 1 THEN p.x
WHEN m.type = 'path' AND direction = 2 THEN p.x - 1
WHEN m.type = 'path' AND direction = 3 THEN p.x
ELSE p.x
END || ',' ||
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.y
WHEN m.type = 'path' AND direction = 1 THEN p.y + 1
WHEN m.type = 'path' AND direction = 2 THEN p.y
WHEN m.type = 'path' AND direction = 3 THEN p.y - 1
ELSE p.y
END || ')'
FROM
PathFinder p,
(SELECT 0 AS direction UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) AS dirs,
Maze m
WHERE
-- Check direction:
-- 0: right, 1: down, 2: left, 3: up
(
(dirs.direction = 0 AND m.x = p.x + 1 AND m.y = p.y) OR
(dirs.direction = 1 AND m.x = p.x AND m.y = p.y + 1) OR
(dirs.direction = 2 AND m.x = p.x - 1 AND m.y = p.y) OR
(dirs.direction = 3 AND m.x = p.x AND m.y = p.y - 1)
)
-- Check if the new position is a valid path and hasn't been visited
AND m.type = 'path'
AND p.visited NOT LIKE '%(' || m.x || ',' || m.y || ')%'
)
-- Select the shortest path to the destination
SELECT path
FROM PathFinder
WHERE x = 4 AND y = 4
ORDER BY length(path)
LIMIT 1;
'''
cursor.execute(query)
result = cursor.fetchone()
if result is None:
print("No solution found!")
return None
# Parse the path string into coordinates
path_str = result[0]
coord_strs = path_str.split('->')
path = []
for coord_str in coord_strs:
# Extract x and y from strings like "(0,0)"
coord = coord_str.strip('()').split(',')
path.append((int(coord[0]), int(coord[1])))
return path
def main():
conn, cursor = create_database()
# Print the generated maze
print_maze(cursor)
# Solve the maze
print("\nSolving maze with SQL recursive CTE...")
path = solve_maze_with_sql(cursor)
if path:
print(f"Solution found! Path length: {len(path)}")
print(f"Path: {path}")
# Visualize the solution
print_solution_path(cursor, path)
conn.close()
if __name__ == "__main__":
main()
import sqlite3
import random
def create_database():
"""Create and initialize the SQLite database for the maze."""
conn = sqlite3.connect(':memory:') # Using in-memory database for simplicity
cursor = conn.cursor()
# Create the maze table
cursor.execute('''
CREATE TABLE Maze (
x INTEGER,
y INTEGER,
type TEXT,
PRIMARY KEY (x, y)
)
''')
# Generate a random maze
generate_maze(cursor)
return conn, cursor
def generate_maze(cursor):
"""Generate a random 5x5 maze and store it in the database."""
# First, fill everything with walls
for x in range(5):
for y in range(5):
cursor.execute('INSERT INTO Maze VALUES (?, ?, ?)', (x, y, 'wall'))
# Create a simple maze with a guaranteed path from start to end
# Using a simplified version of randomized DFS for maze generation
visited = set()
stack = [(0, 0)]
visited.add((0, 0))
# Set start and end as paths
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', 0, 0))
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', 4, 4))
while stack:
x, y = stack[-1]
# Get unvisited neighbors
neighbors = []
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < 5 and 0 <= ny < 5 and (nx, ny) not in visited:
neighbors.append((nx, ny))
if neighbors:
# Choose a random unvisited neighbor
nx, ny = random.choice(neighbors)
visited.add((nx, ny))
stack.append((nx, ny))
# Mark as path
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', nx, ny))
else:
# Backtrack
stack.pop()
# Make sure there's a valid path from start to end
# This is a simplified approach and might create a very direct path
make_valid_path(cursor)
def make_valid_path(cursor):
"""Ensure there's a valid path from (0,0) to (4,4)."""
# Simple approach: create a direct path if needed
for i in range(5):
cursor.execute('UPDATE Maze SET type = ? WHERE x = ? AND y = ?', ('path', i, i))
def print_maze(cursor):
"""Print the maze in ASCII format."""
cursor.execute('SELECT x, y, type FROM Maze ORDER BY y, x')
rows = cursor.fetchall()
maze_grid = [['#' for _ in range(5)] for _ in range(5)]
for x, y, cell_type in rows:
maze_grid[y][x] = '#' if cell_type == 'wall' else ' '
print("Maze:")
for row in maze_grid:
print(''.join(row))
def print_solution_path(cursor, path):
"""Print the maze with the solution path marked."""
cursor.execute('SELECT x, y, type FROM Maze ORDER BY y, x')
rows = cursor.fetchall()
# Create maze grid
maze_grid = [['#' for _ in range(5)] for _ in range(5)]
for x, y, cell_type in rows:
maze_grid[y][x] = '#' if cell_type == 'wall' else ' '
# Mark path
for x, y in path:
maze_grid[y][x] = 'X'
# Mark start and end
maze_grid[0][0] = 'S'
maze_grid[4][4] = 'E'
print("\nSolution Path:")
for row in maze_grid:
print(''.join(row))
def solve_maze_with_sql(cursor):
"""Solve the maze using recursive Common Table Expressions (CTE) in SQL."""
query = '''
WITH RECURSIVE
-- Define starting point
PathFinder(x, y, path, visited) AS (
SELECT 0, 0, '(0,0)', '(0,0)'
UNION ALL
-- Recursive part: explore in four directions
SELECT
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.x + 1
WHEN m.type = 'path' AND direction = 1 THEN p.x
WHEN m.type = 'path' AND direction = 2 THEN p.x - 1
WHEN m.type = 'path' AND direction = 3 THEN p.x
ELSE p.x
END,
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.y
WHEN m.type = 'path' AND direction = 1 THEN p.y + 1
WHEN m.type = 'path' AND direction = 2 THEN p.y
WHEN m.type = 'path' AND direction = 3 THEN p.y - 1
ELSE p.y
END,
p.path || '->' || '(' ||
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.x + 1
WHEN m.type = 'path' AND direction = 1 THEN p.x
WHEN m.type = 'path' AND direction = 2 THEN p.x - 1
WHEN m.type = 'path' AND direction = 3 THEN p.x
ELSE p.x
END || ',' ||
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.y
WHEN m.type = 'path' AND direction = 1 THEN p.y + 1
WHEN m.type = 'path' AND direction = 2 THEN p.y
WHEN m.type = 'path' AND direction = 3 THEN p.y - 1
ELSE p.y
END || ')',
p.visited || ',' || '(' ||
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.x + 1
WHEN m.type = 'path' AND direction = 1 THEN p.x
WHEN m.type = 'path' AND direction = 2 THEN p.x - 1
WHEN m.type = 'path' AND direction = 3 THEN p.x
ELSE p.x
END || ',' ||
CASE
WHEN m.type = 'path' AND direction = 0 THEN p.y
WHEN m.type = 'path' AND direction = 1 THEN p.y + 1
WHEN m.type = 'path' AND direction = 2 THEN p.y
WHEN m.type = 'path' AND direction = 3 THEN p.y - 1
ELSE p.y
END || ')'
FROM
PathFinder p,
(SELECT 0 AS direction UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) AS dirs,
Maze m
WHERE
-- Check direction:
-- 0: right, 1: down, 2: left, 3: up
(
(dirs.direction = 0 AND m.x = p.x + 1 AND m.y = p.y) OR
(dirs.direction = 1 AND m.x = p.x AND m.y = p.y + 1) OR
(dirs.direction = 2 AND m.x = p.x - 1 AND m.y = p.y) OR
(dirs.direction = 3 AND m.x = p.x AND m.y = p.y - 1)
)
-- Check if the new position is a valid path and hasn't been visited
AND m.type = 'path'
AND p.visited NOT LIKE '%(' || m.x || ',' || m.y || ')%'
)
-- Select the shortest path to the destination
SELECT path
FROM PathFinder
WHERE x = 4 AND y = 4
ORDER BY length(path)
LIMIT 1;
'''
cursor.execute(query)
result = cursor.fetchone()
if result is None:
print("No solution found!")
return None
# Parse the path string into coordinates
path_str = result[0]
coord_strs = path_str.split('->')
path = []
for coord_str in coord_strs:
# Extract x and y from strings like "(0,0)"
coord = coord_str.strip('()').split(',')
path.append((int(coord[0]), int(coord[1])))
return path
def main():
conn, cursor = create_database()
# Print the generated maze
print_maze(cursor)
# Solve the maze
print("\nSolving maze with SQL recursive CTE...")
path = solve_maze_with_sql(cursor)
if path:
print(f"Solution found! Path length: {len(path)}")
print(f"Path: {path}")
# Visualize the solution
print_solution_path(cursor, path)
conn.close()
if __name__ == "__main__":
main()
輸出:
Solving maze with SQL recursive CTE...
Solution found! Path length: 9
Path: [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (4, 1), (4, 2), (4, 3),
Maze:
Solving maze with SQL recursive CTE...
Solution found! Path length: 9
Path: [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (4, 1), (4, 2), (4, 3),
(4, 4)]
Solution Path:
SXXXX
X
X
X
E
Maze:
Solving maze with SQL recursive CTE...
Solution found! Path length: 9
Path: [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (4, 1), (4, 2), (4, 3),
(4, 4)]
Solution Path:
SXXXX
X
X
X
E
觀察對比
Qwen 2.5 Coder 32B
優點
- 簡潔直接:使用結構化遞迴 CTE 查詢最短路徑。
- 優化查詢:SQL 可高效計算最短路徑,無需手動回溯。
- 資料庫永續性:將迷宮儲存在資料庫中,方便日後執行查詢。
缺點
- 靜態迷宮資料:預設迷宮並手動插入,缺乏隨機性。
- 無視覺表現:不列印迷宮或以圖形方式顯示解決方案。
- 有限的錯誤處理:無法驗證迷宮是否包含有效的起點到終點路徑。
Claude 3.7 Sonnet
優點
- 動態迷宮生成:使用基於 DFS 的隨機演算法建立獨一無二的迷宮。
- 視覺化表示:使用 ASCII 碼列印迷宮並突出顯示解謎路徑。
- 記憶體資料庫:使用 SQLite 的記憶體模式,使執行速度更快,並避免檔案處理開銷。
- 確保有效路徑:保證從起點到終點的連線,防止出現不可能的迷宮。
缺點
- 更復雜:有額外的迷宮生成邏輯,程式碼更長。
- 尋路效率可能較低:SQL 尋路器並不總是返回最優路徑。
- 冗長的 SQL 查詢:遞迴 CTE 解決方案比 Qwen 的更復雜。
結論
Claude 3.7 Sonnet ✅ | Qwen 2.5 Coder ❌
最終結論
任務 |
勝出者 |
任務 1:HTML 程式碼(Three.js Globe) |
Qwen 2.5 Coder |
任務 2:資料視覺化(合併排序) |
Claude 3.7 Sonnet |
任務 3:最大子陣列(Kadane演算法) |
Claude 3.7 Sonnet |
任務 4:迷宮求解(SQLite 迷宮) |
Claude 3.7 Sonnet |
Qwen 2.5 Coder 32B 和 Claude 3.7 Sonnet 在編碼領域都具有獨特的優勢。Claude 3.7 Sonnet 在各種基準測試中表現出卓越的效能,尤其是在推理和程式碼生成任務方面。不過,Qwen 2.5 Coder 32B 憑藉高效的數學問題解決能力,也佔據了一席之地。根據您的具體需求,無論是廣泛的上下文處理還是更快的輸出速度,這兩種模式都可以成為開發人員和程式設計師的寶貴工具。
評論留言