messages listlengths 2 2 |
|---|
[
{
"content": "用 Python 產生一個機器學習模型,可以預測給定專案的成功機率。",
"role": "user"
},
{
"content": "```python\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression \n\n# Load the dataset \ndf = pd.read_csv('data.csv')\n\n# ... |
[
{
"content": "使用 Python 建立一個演算法,計算達到給定索引的斐波那契數列。",
"role": "user"
},
{
"content": "```python\ndef fibonacci_seq(n):\n if n < 0:\n raise ValueError(\"Index must be a positive integer.\")\n elif n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n a = 0\n ... |
[
{
"content": "在 Python 中從給定的字典生成結構化陣列。",
"role": "user"
},
{
"content": "```python\nimport numpy as np\ndata = np.array(list(dictionary.values()),\n dtype=[('name','U20'),('age','i4'),('nationality','U10')]\n)\n```",
"role": "assistant"
}
] |
[
{
"content": "使用 Python 編寫冒泡排序程式。",
"role": "user"
},
{
"content": "```python\ndef bubble_sort(unsorted_list): \n n = len(unsorted_list) \n \n for i in range(n): \n for j in range(0, n-i-1): \n \n if unsorted_list[j] > unsorted_list[j+1] : \n unsorted_list[j]... |
[
{
"content": "使用 Python 建立機器學習模型,對手寫數字進行分類。",
"role": "user"
},
{
"content": "```python\nimport tensorflow as tf\nfrom tensorflow.keras.datasets import mnist\n\n# Get train and test data\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n# Reshape data\nx_train = x_train.reshape(60000, 784... |
[
{
"content": "建立一個 Python 程序,對數字列表進行從低到高的排序。",
"role": "user"
},
{
"content": "```python\ndef sort_list(nums):\n for i in range(len(nums)):\n min_index = i\n \n for j in range(i+1, len(nums)):\n if nums[min_index] > nums[j]:\n min_index = j\n ... |
[
{
"content": "你能在Python中實作一個接受兩個字串並傳回最長公共子字串的函數嗎?",
"role": "user"
},
{
"content": "```python\ndef longest_common_substring(s1, s2):\n dp = [[0 for _ in range(len(s2) + 1)] for _ in range(len(s1) + 1)]\n longest_len = 0\n longest_string = \"\"\n\n for i in range(1, len(s1) + 1):\n ... |
[
{
"content": "使用 Python 建立一個 Web API 來存取電影和演員的資料庫。 API 應該具有用於獲取電影列表、獲取電影演員、向電影添加演員以及從電影中刪除演員的端點",
"role": "user"
},
{
"content": "```python\nimport sqlite3\nfrom flask import Flask, jsonify, request, abort\n\n# Initial setup of a Flask application\napp = Flask(__name__)\nconn = sqlite3.connect('movi... |
[
{
"content": "編寫 Python 程式碼將華氏溫度轉換為攝氏度。",
"role": "user"
},
{
"content": "```python\ndef convert_to_celsius(fahrenheit):\n celsius = (fahrenheit - 32) * 5 / 9\n return celsius\n\nfahrenheit = 32\ncelsius = convert_to_celsius(fahrenheit)\nprint(f\"Fahrenheit: {fahrenheit},, Celsius: {celsius},\... |
[
{
"content": "建立一個 Python 腳本來創建所提供資料的資料視覺化。",
"role": "user"
},
{
"content": "```python\nimport matplotlib.pyplot as plt \ndata = [5, 10, 15, 20, 25, 30, 35, 40, 45]\nplt.plot(data) \n\n# formatting the text\nplt.title('Data Visualisation') \nplt.xlabel('Data Points') \nplt.ylabel('Value') \n\n# fun... |
[
{
"content": "建立一個函數,在 Python 中使用凱撒密碼對字串進行編碼。",
"role": "user"
},
{
"content": "```python\ndef caesar_encrypt(string, encryption_key):\n encrypted_string = \"\"\n for char in string:\n # convert char to ASCII code\n ascii_code = ord(char)\n # shift the char by given encryp... |
[
{
"content": "在 Python 中產生一個 while 循環,以逆向列印 15 到 10 的數字。",
"role": "user"
},
{
"content": "```python\nnum = 15\nwhile num >= 10:\n print(num)\n num -= 1\n```",
"role": "assistant"
}
] |
[
{
"content": "開發一個 Python 程序,根據兩個數字之間的比較列印一個值",
"role": "user"
},
{
"content": "```python\nif a < b:\n print(\"A is less than B\")\nelse:\n print(\"A is not less than B\")\n```",
"role": "assistant"
}
] |
[
{
"content": "在 Production 中將 `settings.base.prepopulate` 設為 0,以節省每個頁面 1x DAL 的點擊量。如果「pop_list」不等於 0,則將「table」設為「db[auth.settings.table_group_name]」。如果 db(table.id > 0).select(table.id, limitby=(0, 1)).first() 為 true,則將 pop_list 設為空列表。如果「pop_list」不是清單或元組,請將「pop_list」設定為包含「pop_list」的清單。如果「pop_list」的長度大於 0,則填入預設角... |
[
{
"content": "建立一個 Python 程序,根據給定參數產生並列印時間表。",
"role": "user"
},
{
"content": "```python\ndef print_schedule(working_hours, tasks):\n start = working_hours[0]\n end = working_hours[1]\n time = start\n\n print(\"| Tasks | Start | End | Duration |\")\n print(\"| ----- | ----- | --- | --... |
[
{
"content": "使用 Python 設計資料結構來儲存電子郵件和相關元資料。",
"role": "user"
},
{
"content": "```python\nclass Message(object):\n def __init__(self,subject, sender, receiver, body):\n self.subject = subject\n self.sender = sender\n self.receiver = receiver\n self.body = body\n\nclass... |
[
{
"content": "使用 python 字典建立哈希表。",
"role": "user"
},
{
"content": "```python\nclass HashTable:\n def __init__(self):\n self.table = {},\n\n def put(self, key, value):\n # Get the hash for the given key\n hash_value = self._hash(key)\n # If the hash value is not in t... |
[
{
"content": "在 Python Flask 中建立 API 端點,以從 MongoDB 儲存和檢索產品詳細資訊。",
"role": "user"
},
{
"content": "```python\nfrom flask import Flask, jsonify, request\nfrom flask_pymongo import PyMongo\n\napp = Flask(name)\nmongo = PyMongo(app)\n \n@app.route('/products', methods=['POST'])\ndef add_product():\n dat... |
[
{
"content": "在 Python 中編寫一個函數,該函數接受字串列表並傳回列表中的所有唯一字串。",
"role": "user"
},
{
"content": "```python\ndef find_unique_strings(strings):\n \n unique_strings = []\n for s in strings:\n if s not in unique_strings:\n unique_strings.append(s)\n \n return unique_strings\n```",
... |
[
{
"content": "設計一個 Python 程序,它接收電子郵件地址,檢查它是否有效,如果無效則列印出相應的錯誤訊息。",
"role": "user"
},
{
"content": "```python\nimport re\n\ndef validate_email(address):\n regex = '^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3},)+$'\n if re.search(regex, address):\n return True\n else:\n ret... |
[
{
"content": "在 Python 中建立一個程序,接受使用者輸入並列印出其類型。",
"role": "user"
},
{
"content": "```python\nuser_input = input('Please enter anything: ')\n\nprint('The type of user input is:', type(user_input))\n```",
"role": "assistant"
}
] |
[
{
"content": "給定一組 Python 類,產生程式碼來建立每個類別的實例並列印與每個實例關聯的屬性和方法。",
"role": "user"
},
{
"content": "```python\n# Create instances of each class\ncar1 = Car('Toyota', 'Camry', '2018')\ndog1 = Dog('Labrador', 'Max')\n\n# Print attributes and methods\nprint(\"The car is a {}, {}, manufactured in {},\".forma... |
[
{
"content": "使用表單建立一個 HTML 頁面,允許使用者輸入兩個城市的座標並使用 Python 返回從來源到目的地的最短路徑。",
"role": "user"
},
{
"content": "```python\n<html>\n<head>\n <title>Shortest Path Finder</title>\n</head>\n<body>\n <form method=\"post\" action=\"pathFinder.py\">\n <input type=\"text\" name=\"source\" placeholder=\"Sourc... |
[
{
"content": "編寫一個 Python 腳本,以以下格式列印目前日期:「Monday, October 5th, 2020」。",
"role": "user"
},
{
"content": "```python\nimport datetime\n\ndate_info = datetime.datetime.today()\n\nday_name = date_info.strftime(\"%A\")\nmonth_name = date_info.strftime(\"%B\")\ndate_num = date_info.strftime(\"%-d\")\nyear_... |
[
{
"content": "優化將兩個矩陣相乘的 Python 腳本。此腳本應適用於作為輸入給出的任兩個矩陣。",
"role": "user"
},
{
"content": "```python\ndef multiply_matrices(m1, m2):\n if len(m1[0]) != len(m2):\n raise ValueError('The matrices cannot be multiplied.')\n\n # Create the result matrix\n # Dimensions would be m1 rows x m2 columns\n resul... |
[
{
"content": "建立一個 Python 程式來比較兩個字串並傳回匹配字元的百分比。",
"role": "user"
},
{
"content": "```python\ndef compare_strings( string1, string2 ):\n s1, s2 = set(string1), set(string2)\n intersection = s1.intersection(s2)\n\n return (len(intersection) * 100) / len(s1)\n```",
"role": "assistant"
}
... |
[
{
"content": "產生一個 Python 腳本來尋找給定清單中最受歡迎的 5 個項目。",
"role": "user"
},
{
"content": "```python\nfrom collections import Counter\n\n# Get the input list\nlist = [1, 3, 5, 3, 6, 2, 4, 6, 8, 4]\n\n# Use Counter library to get a dictionary of the top 5 items\ntop_five = Counter(list).most_common(5)\n\n# P... |
[
{
"content": "建立一個計算數字陣列的中位數的 Python 程式。",
"role": "user"
},
{
"content": "```python\ndef median(arr):\n arr.sort()\n if len(arr) % 2 != 0:\n return arr[int(len(arr)/2)]\n else:\n return (arr[int(len(arr)/2)] + arr[int(len(arr)/2)-1]) / 2\n\nmedianValue = median(arr)\nprint(me... |
[
{
"content": "",
"role": "user"
},
{
"content": "```python\ndef check_palindrome(string):\n reversed_string = string[::-1]\n if string == reversed_string:\n return True\n else:\n return False\n```",
"role": "assistant"
}
] |
[
{
"content": "建立一個 python 腳本,根據第二個元素對元組清單進行排序。",
"role": "user"
},
{
"content": "```python\nsortedTuples = sorted(tuples, key = lambda x: x[1])\n```",
"role": "assistant"
}
] |
[
{
"content": "使用 Python 建立一個程式來產生 8 個字元的隨機密碼。",
"role": "user"
},
{
"content": "```python\nimport random\nimport string\n \n# Random password generator \ndef randomString(stringLength=8):\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(stringLength))\... |
[
{
"content": "編寫一個 Python 程式來實作決策樹分類器,將鳶尾花分為三類(setosa、versicolor 和 virginica)。",
"role": "user"
},
{
"content": "```python\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.datasets import load_iris\n\n# load data... |
[
{
"content": "建立一個 Python 列表理解來尋找兩個給定列表中偶數的總和。",
"role": "user"
},
{
"content": "```python\neven_nums_sum = [x + y for x in [1, 2, 3, 4] for y in [9, 8, 7, 6] if x % 2 == 0 and y % 2 == 0]\nprint(sum(even_nums_sum))\n```",
"role": "assistant"
}
] |
[
{
"content": "寫一個 python 函數來找出兩個數中的最大值,而不使用最大值函數。",
"role": "user"
},
{
"content": "```python\ndef find_max(a, b):\n if a > b:\n return a\n else:\n return b\n```",
"role": "assistant"
}
] |
[
{
"content": "寫一個 Python 程序,列印給定列表中所有能被 7 整除的數字。",
"role": "user"
},
{
"content": "```python\ndef divisible_by_seven(number_list):\n for i in number_list:\n if i % 7 == 0:\n print(i)\n```",
"role": "assistant"
}
] |
[
{
"content": "使用 NLTK 在 Python 中建立情緒分析系統,以提供評論正面或負面的分數。",
"role": "user"
},
{
"content": "```python\nimport nltk\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\n# Create a SentimentIntensityAnalzyer\nanalyzer = SentimentIntensityAnalyzer()\n \n# Calculate scores\nscores = analyzer.po... |
[
{
"content": "使用 Python 建立一個程序,可以分析超過一百萬篇文章以查找最常用的單字。",
"role": "user"
},
{
"content": "```python\nimport os\nfrom collections import Counter\nfrom nltk import word_tokenize\n\n# Specify the directory containing the files\ndirectory = 'articles_folder'\n\n# Initialize a Counter object\nword_counts =... |
[
{
"content": "在 Python 中產生一個函數,按給定字串清單的長度對字串進行排序。",
"role": "user"
},
{
"content": "```python\ndef sortByLength(strings):\n return sorted(strings, key=len)\n\nstrings = ['cat', 'dog', 'goat', 'tiger', 'bird']\n\nprint(sortByLength(strings)) # Output: ['cat', 'dog', 'goat', 'bird', 'tiger']\n```",... |
[
{
"content": "設計一個Python腳本,以相反的順序列印字串中的字元。",
"role": "user"
},
{
"content": "```python\ndef reverseString(string):\n reversed = \"\" \n for character in string:\n reversed = character + reversed\n return reversed\n```",
"role": "assistant"
}
] |
[
{
"content": "在 Python 中建立一個函數來計算字串中特定字母的出現次數。",
"role": "user"
},
{
"content": "```python\ndef CountLetterOccurrences(str, letter): \n return str.count(letter)\n```",
"role": "assistant"
}
] |
[
{
"content": "建立一個 Python 程式來產生帶有 X 和 O 字元的井字遊戲板。",
"role": "user"
},
{
"content": "```python\nimport random\n\n# Function to print the tic tac toe board\ndef print_board(board):\n for i in range(3):\n for j in range(3):\n print(board[i][j], end=\" \")\n print()\n print()\n\n# Function to generate a... |
[
{
"content": "建立一個名為「Circle」的 Python 類,它將其半徑作為參數。這個類別應該有一個名為「area」的方法來計算圓的面積,還有一個名為「circumference」的方法來計算週長",
"role": "user"
},
{
"content": "```python\nclass Circle:\n def __init__(self, radius):\n self.radius = radius\n \n def area(self):\n return 3.14 * (self.radius ** 2)\n \n def circumference(se... |
[
{
"content": "用 Python 編寫一個腳本來傳回字串的加密雜湊值。",
"role": "user"
},
{
"content": "```python\nimport hashlib\n\ndef get_hash(string):\n sha1 = hashlib.sha1()\n sha1.update(string.encode('utf-8'))\n return sha1.hexdigest()\n\nprint(get_hash(string))\n```",
"role": "assistant"
}
] |
[
{
"content": "產生一個函數來尋找 Python 中巢狀列表中元素的總和。",
"role": "user"
},
{
"content": "```python\ndef sum_of_element(arr):\n s = 0\n for sub_list in arr:\n for element in sub_list:\n s += element\n return s\n\narr = [[1, 2], [3, 4], [5, 6]]\ntotal = sum_of_element(arr)\nprint(total... |
[
{
"content": "使用 Python 建立基本遺傳演算法程序,以確定線性迴歸模型的最佳參數,從而最小化均方誤差。",
"role": "user"
},
{
"content": "```python\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\n\n# Parameters for the genetic algorithm\nnum_generations = 50 # Number of generations\npopulation_size = 20 # Populati... |
[
{
"content": "你能編寫一個以兩個字串作為參數並將它們連接在一起的 Python 函數嗎?",
"role": "user"
},
{
"content": "```python\ndef concatenate_strings(string1, string2):\n return string1 + string2\n```",
"role": "assistant"
}
] |
[
{
"content": "寫一個Python程式來偵測給定的數字是否為回文。",
"role": "user"
},
{
"content": "```python\ndef is_palindrome(n):\n n = str(n)\n return n == n[::-1]\n\nprint(is_palindrome(\"middle\"))\n```",
"role": "assistant"
}
] |
[
{
"content": "設計一個python程式產生單鍊錶",
"role": "user"
},
{
"content": "```python\nclass Node: \n def __init__(self, data):\n self.data = data\n self.next = None\n \n\nclass LinkedList: \n def __init__(self):\n self.head = None\n \n # Function to insert a new node at the be... |
[
{
"content": "在 Python 中開發一個函數,列印出直到給定數字 n 的斐波那契數列。",
"role": "user"
},
{
"content": "```python\ndef printFibonacci(n):\n if n<0:\n print('Incorrect input')\n elif n==0:\n print(0)\n elif n==1:\n print(0,1)\n else:\n a=0\n b=1\n print(a)\n ... |
[
{
"content": "透過使用函數來提高Python程式的效率。",
"role": "user"
},
{
"content": "```python\narr = [1, 2, 3, 4, 5]\n\ndef calculate(arr):\n return sum(arr)\n\ndef main():\n print(calculate(arr))\n\nif __name__ == '__main__':\n main()\n```",
"role": "assistant"
}
] |
[
{
"content": "使用 Python 開發一個程式來找出給定數字的階乘。",
"role": "user"
},
{
"content": "```python\ndef factorial(n):\n if n < 0:\n return None\n elif n == 0:\n return 1\n else:\n result = 1\n for i in range(1, n + 1):\n result *= i\n return result\n\nnum = ... |
[
{
"content": "建立一個 Python 程式來產生 0 - 9 之間的 4 個隨機數。",
"role": "user"
},
{
"content": "```python\nimport random\n\nfor i in range(4):\n num = random.randint(0,9)\n print(num)\n```",
"role": "assistant"
}
] |
[
{
"content": "使用 Python 建立一個程序,列印前 10 個質數。",
"role": "user"
},
{
"content": "```python\nimport math\n\ndef is_prime(n):\n if n == 1:\n return False\n \n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\nprime_nums = []\n\n... |
[
{
"content": "建立一個 Python 程式來為給定資料集產生隨機森林模型。",
"role": "user"
},
{
"content": "```python\nimport pandas as pd\n\n# Read in the dataset\ndf = pd.read_csv('data.csv')\n\n# Specify the feature and target columns\nfeatures = ['age', 'gender', 'hours_per_week',\n 'marital_status', 'education']... |
[
{
"content": "在 Python 中設計一個演算法,用一個字串替換給定字串中所有出現的空格。",
"role": "user"
},
{
"content": "```python\ndef replace_spaces(s,replace_with):\n return s.replace(\" \",replace_with)\n\ns = \"This is a test string\"\nreplace_with = \"X\"\n\nprint(replace_spaces(s,replace_with))\n```",
"role": "assistan... |
[
{
"content": "使用 Python 設計一個基於規則的系統來產生自然語言問題。",
"role": "user"
},
{
"content": "```python\nimport re\n\ndef generate_question(sentence):\n tokens = re.findall('\\w+', sentence)\n if tokens[0] == 'The':\n question = 'What is' + ' ' + ' '.join(tokens[1:]) + '?'\n else:\n question = 'What is the' + '... |
[
{
"content": "建立 Webhook 來呼叫 Python Web 服務。",
"role": "user"
},
{
"content": "```python\nimport requests\n\ndef call_web_service():\n API_ENDPOINT = \"http://example.com/api/v1\"\n\n # Make a post request to call the web service\n r = requests.post(url= API_ENDPOINT)\n\n# Create webhook\nwe... |
[
{
"content": "使用 Python 建立一個程序,對 1 到 1000 之間的 3 或 5 的倍數求和",
"role": "user"
},
{
"content": "```python\ntotal = 0\n\nfor i in range(1,1000):\n if i % 3 == 0 or i % 5 == 0:\n total += i\n\nprint(total)\n```",
"role": "assistant"
}
] |
[
{
"content": "使用 Python 使用給定資料集建立決策樹模型。",
"role": "user"
},
{
"content": "```python\nimport numpy as np\nimport pandas as pd\nfrom sklearn import tree\n\n# Load the dataset\ndata = pd.read_csv(\"data.csv\")\n\n# Create target variable\ntarget = data[\"target\"]\n\n# Create feature variables\nfeature... |
[
{
"content": "在 Python 中建構一個計算三角形面積的函數",
"role": "user"
},
{
"content": "```python\ndef area_of_triangle(base, height):\n \"\"\"Compute the area of a triangle in Python\n \n Parameters\n --------------\n base: float\n The length of the triangle's base\n height: float\n ... |
[
{
"content": "寫一個 Python 程式來建立 n 長度的斐波那契數列。",
"role": "user"
},
{
"content": "```python\ndef fibonacci(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n\nfor i in range(10):\n print(fibonacci(i))\n```",
"role": "assistant"
}
] |
[
{
"content": "更新給定的 Python 程式以相反順序列印結果。",
"role": "user"
},
{
"content": "```python\nnumbers = [1, 2, 3, 4, 5, 6]\n\nfor x in reversed(numbers):\n print(x)\n```",
"role": "assistant"
}
] |
[
{
"content": "Python程式碼:產生一個將十進制數轉換為二進制數的函數。",
"role": "user"
},
{
"content": "```python\ndef decToBin(n):\n binString = \"\"\n while n > 0:\n binary = n % 2\n binString = str(binary) + binString\n n = n//2\n \n return binString\n \n# Driver Code \nn = int(input(\"Ente... |
[
{
"content": "修改下面現有的Python程式碼,使其傳回小於輸入n的奇數總和。",
"role": "user"
},
{
"content": "```python\ndef sum_odd_numbers(n):\n result = 0\n for i in range(n):\n if i % 2 != 0:\n result += i\n return result\n```",
"role": "assistant"
}
] |
[
{
"content": "用 Python 重寫以下 Java 程式來計算三角形的面積。",
"role": "user"
},
{
"content": "```python\ndef area(b, h):\n return 0.5 * b * h\n```",
"role": "assistant"
}
] |
[
{
"content": "產生一個 Python 程序,將 -5 到 5 之間的整數分類為「負」、「零」和「正」。",
"role": "user"
},
{
"content": "```python\ndef classify_int(x):\n if x < 0:\n return 'negative'\n elif x == 0: \n return 'zero'\n elif x > 0:\n return 'positive'\n```",
"role": "assistant"
}
] |
[
{
"content": "產生一個 html 頁面,該頁面將接受使用者輸入並將其發送到 python 腳本。",
"role": "user"
},
{
"content": "```python\n<!DOCTYPE html>\n<html>\n<head>\n <title>Input Page</title>\n</head>\n<body>\n <h1>Input Page</h1>\n <form action=\"script.py\" method=\"POST\">\n <label>Enter your input: <input type=\... |
[
{
"content": "在 Python 中實作線性搜尋演算法來尋找陣列中給定元素的位置。",
"role": "user"
},
{
"content": "```python\ndef linear_search(arr, element):\n for i in range(len(arr)):\n if arr[i] == element:\n return i\n return -1\n```",
"role": "assistant"
}
] |
[
{
"content": "在 python 中產生一個程序,該程序接受給定的數字列表並創建一個字典,其中每個數字是鍵,給定數字的倍數是值。",
"role": "user"
},
{
"content": "```python\ndef create_dictionary(my_list):\n res = {num: num * 2 for num in my_list},\n return res\n\n# run the code\nmy_list = [3, 5, 7]\n\nres = create_dictionary(my_list)\nprint('The dic... |
[
{
"content": "建立一個 Python 程式來讀取包含 A、B 和 C 欄位的 CSV,並建立一個僅包含 A 和 C 欄位的新 CSV。",
"role": "user"
},
{
"content": "```python\nimport csv\n\ndef read_csv(filename):\n with open(filename, 'r') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n next(csv_reader) # Skip the head... |
[
{
"content": "將以下演算法轉換為 Python 中的函數式程式設計風格。",
"role": "user"
},
{
"content": "```python\ndef add_number(x, y):\n return sum(range(x, y))\n```",
"role": "assistant"
}
] |
[
{
"content": "產生一個命令,列印 Python 中任何給定變數的類型。",
"role": "user"
},
{
"content": "```python\nprint(type(variable))\n```",
"role": "assistant"
}
] |
[
{
"content": "編寫一個 Python 程式將字串拆分為單字列表。",
"role": "user"
},
{
"content": "```python\ndef split_into_words(text):\n \"\"\"\n Splits a string into a list of words\n \"\"\"\n # Split the text on whitespace\n return text.split()\n```",
"role": "assistant"
}
] |
[
{
"content": "使用 Python 設計一個程序,將數字列表作為輸入並傳回平均值。",
"role": "user"
},
{
"content": "```python\n# Function to return average\ndef average(lst):\n \n # Calculate sum of list\n sum_num = 0\n for x in lst:\n sum_num += x\n \n # Return average \n return sum_num / len(lst)\n\... |
[
{
"content": "使用 Python 建立一個腳本來產生斐波那契數列的第 n 項。",
"role": "user"
},
{
"content": "```python\ndef Fibonacci(n):\n a = 0\n b = 1\n if n < 0:\n print(\"Incorrect input\")\n elif n == 0:\n return a\n elif n == 1:\n return b\n else:\n for i in range(2,n):\n c = a + b\n a = b\n b = c\n return b\... |
[
{
"content": "在 Python 中,如何傳回清單中的最後 N 個元素?",
"role": "user"
},
{
"content": "```python\ndef last_elements(lst, n):\n return lst[-n:]\n```",
"role": "assistant"
}
] |
[
{
"content": "使用 Python 設計一維元胞自動機。",
"role": "user"
},
{
"content": "```python\nimport numpy as np\n\n# Define the automata\ncell_size = 10\nauto = np.zeros(cell_size)\n\n# Create the display\ndef display_automata(cells):\n for cell in cells:\n if cell == 0:\n print('█', end=\"\")\n else:\n print(' ... |
[
{
"content": "建立一個 python 函數,將字串作為輸入並檢查它是否是有效的識別碼。",
"role": "user"
},
{
"content": "```python\nimport string\n\ndef isValidIdentifier(name):\n validChar = string.ascii_letters + \"_\"\n if name[0] not in string.ascii_letters:\n return False\n for char in name[1:]:\n if char n... |
[
{
"content": "建立一個 Python 程序,將兩個數字作為輸入,並傳回兩個數字之間範圍內的素數列表。",
"role": "user"
},
{
"content": "```python\ndef find_primes(start, end):\n # create a list of numbers\n # between start and end\n numbers = range(start, end + 1)\n \n # iterate over the list\n for i in numbers:\n # check if number is divisib... |
[
{
"content": "建立一個 python 程序,該程序接受一個字串列表並傳回一個刪除了所有重複項的字串列表。",
"role": "user"
},
{
"content": "```python\ndef remove_duplicates(lst):\n new_lst = []\n\n for item in lst:\n if item not in new_lst:\n new_lst.append(item)\n\n return new_lst\n\nresult = remove_duplicates([\"a\"... |
[
{
"content": "創建一個 Python 程序,根據動物的特徵將其分為四類(魚類、鳥類、哺乳動物、爬行動物)之一。",
"role": "user"
},
{
"content": "```python\n\"\"\"\nCreate a Python program to classify an animal into one of four classes\n\n\"\"\"\n# define the characteristics\nis_cold_blooded = True\nlays_eggs = True\nhas_scales = True\n\n# determi... |
[
{
"content": "用 Python 寫一個函數,將年份從羅馬數字轉換為阿拉伯數字。",
"role": "user"
},
{
"content": "```python\n# define a dictionary of Roman Numerals to Arabic numbers\nroman = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000\n},\n\ndef roman_to_arabic(roman_string)... |
[
{
"content": "指示: \n\n1. 建立一個Python檔案並向其中加入給定的程式碼。\n2. 導入必要的模組:logging.handlers、configparser、re 和 time。\n3. 建立一個TimedRotatingFileHandler實例,參數如下:filename=\"test\",when='s',interval=2,backupCount=5,encoding='UTF-8'。\n4. 將處理程序的後綴設定為「%Y-%m-%d-%H-%M-%S.log」。\n5. 將處理程序的 extMatch 設定為 re.compile(r'^\\d{4},-\\d{2},-\\d{... |
[
{
"content": "在 Python 中建立一個函數來計算兩個日期之間的天數。",
"role": "user"
},
{
"content": "```python\ndef days_between_dates(date1, date2):\n delta = date2 - date1\n return delta.days\n```",
"role": "assistant"
}
] |
[
{
"content": "建立一個 python 程序,將包含逗號分隔值的字串轉換為整數列表。",
"role": "user"
},
{
"content": "```python\ndef str_to_list(input_str):\n result = [int(i) for i in input_str.split(\",\")]\n return result\n\nstr = \"12,34,55,67\"\nint_list = str_to_list(str)\nprint(int_list) # Output: [12, 34, 55, 67]\n```",... |
[
{
"content": "在 Python 中設計一個演算法,按字母順序對字串陣列進行排序。",
"role": "user"
},
{
"content": "```python\ndef sort_strings_alphabetically(arr):\n arr.sort(key=str.lower)\n return arr\n```",
"role": "assistant"
}
] |
[
{
"content": "建立一個用於產生第 n 個斐波那契數的 Python 程式。",
"role": "user"
},
{
"content": "```python\ndef fibonacci(n): \n if n == 0: \n return 0\n elif n == 1: \n return 1\n else:\n return fibonacci(n - 1) + fibonacci(n - 2)\n```",
"role": "assistant"
}
] |
[
{
"content": "用Python設計一個哈希表",
"role": "user"
},
{
"content": "```python\n# initialize size\nSIZE = 256\n\n# defining Node class\nclass Node:\n def __init__(self, key, data):\n self.key = key\n self.data = data\n self.next = None\n\n# defining HashTable\nclass HashTable:\n ... |
[
{
"content": "編寫 python 程序,將一串數字作為輸入並確定它是否是有效的 ISBN。",
"role": "user"
},
{
"content": "```python\ndef isValidISBN(input):\n '''\n This function takes a string of numbers as input \n and returns True if it is a valid ISBN \n otherwise False.\n '''\n\n # Check length of string\n i... |
[
{
"content": "產生一個 Python 程式來比較兩個給定的字典,並輸出一個包含兩個字典中共有元素的字典。",
"role": "user"
},
{
"content": "```python\ndef compare_dicts(dict1, dict2):\n common_elements = {},\n for key1, value1 in dict1.items():\n for key2, value2 in dict2.items():\n if key1 == key2:\n comm... |
[
{
"content": "建立一個 python 程序,根據給定的數量和價格計算商品的總成本。",
"role": "user"
},
{
"content": "```python\ndef calcTotalCost(quantity, price):\n totalCost = quantity * price\n return totalCost\n\nresult = calcTotalCost(5, 10)\nprint(result)\n```",
"role": "assistant"
}
] |
[
{
"content": "用 Python 寫一個網頁抓取工具,從以下網站下載電子郵件地址清單:https://example.com/page",
"role": "user"
},
{
"content": "```python\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = 'https://example.com/page'\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.text, 'html.parser')\n\nemails = [a.t... |
[
{
"content": "建議使用 Python 程式碼列印以下模式。",
"role": "user"
},
{
"content": "```python\nfor row in range(6): \n for col in range(7): \n if (row == 0 and col % 3 != 0) or (row == 1 and col % 3 == 0) or (row - col == 2) or (row + col == 8): \n print(\"*\", end=\"\") \n else: \n ... |
[
{
"content": "建立一個 Python 函數來尋找陣列中的最大數字。該函數應接受單一參數並傳回陣列中的最大值。",
"role": "user"
},
{
"content": "```python\ndef find_maximum(arr):\n max_val = arr[0]\n for value in arr:\n if value > max_val:\n max_val = value\n return max_val\n\n# Usage\nmax_num = find_maximum([5, 8, 0, 1, 3, 9])\nprint(m... |
[
{
"content": "用Python實作SVM學習器來對特徵向量進行分類",
"role": "user"
},
{
"content": "```python\n# Import the necessary libraries\nimport numpy as np\nfrom sklearn.svm import SVC\n\n# Load data\nX = np.load('X.npy')\ny = np.load('y.npy')\n\n# Create and fit an SVM learner\nsvm_learner = SVC(gamma='auto') # Init... |
[
{
"content": "給定一個字串列表,編寫一個 Python 程式以按字母順序對字串進行排序。",
"role": "user"
},
{
"content": "```python\ndef sort_strings(strings):\n\treturn sorted(strings)\n\nif __name__ == '__main__':\n\tstrings = ['Python', 'Java', 'C++', 'C#']\n\tsorted_strings = sort_strings(strings)\n\tprint(sorted_strings)\n```",
... |
[
{
"content": "用 Python 創建一個程式來解這個方程式:X^2 - 6X + 9。",
"role": "user"
},
{
"content": "```python\nimport numpy as np\n\n# Define the function\ndef function(x):\n return x**2 - 6*x + 9\n\n# Calculate the roots\nroots = np.roots([1, -6, 9])\n\nprint(\"The solutions for the equation are: x={}, and x={... |
[
{
"content": "開發一個Python腳本來列印1到100之間的所有數字",
"role": "user"
},
{
"content": "```python\nfor i in range(1,101):\n print(i)\n```",
"role": "assistant"
}
] |
[
{
"content": "在 Python 中產生一個函數來檢查給定的數字是否為回文(顛倒數字後保持不變的數字)。",
"role": "user"
},
{
"content": "```python\ndef isPalindrome(n):\n temp = n\n rev = 0\n while(temp > 0): \n rev = (rev * 10) + (temp % 10) \n temp = temp // 10\n if n == rev:\n return True\n else:\n ... |
[
{
"content": "使用 Python 寫一個函數來打亂單字。",
"role": "user"
},
{
"content": "```python\nimport random\n\ndef scramble_word(word):\n # Convert the word to a list\n word_list = list(word)\n #Scramble the Letters\n random.shuffle(word_list)\n #Convert back to a string\n scrambled_word = ''.j... |
End of preview. Expand in Data Studio
No dataset card yet
- Downloads last month
- 2