conversations
listlengths
2
2
[ { "from": "human", "value": "Create a program in Python that evaluates a postfix expression. The input to the program should be a string with the postfix expression. The output should be the evaluated value of the expression." }, { "from": "gpt", "value": "def evaluate(expression): \n \n # s...
[ { "from": "human", "value": "Write a Python script to identify the words that contain more than one vowel in a given sentence." }, { "from": "gpt", "value": "import re\n\nsentence = \"The quick brown fox jumped over the lazy dog.\"\npattern = r\"\\b(\\w*[aeiou]\\w*){2,}\\b\"\n\nmatch = re.findal...
[ { "from": "human", "value": "This code provides a Python API for KB SRU. To use it, you can create an instance of the \"sru\" class and call its \"search\" method, passing in a query string and optionally a collection name, start record number, maximum number of records to return, and record schema. The met...
[ { "from": "human", "value": "Using numpy, create a Python code which would return an array with the running total of numbers in a given list." }, { "from": "gpt", "value": "import numpy as np\n\ndef runningTotal(arr):\n return np.cumsum(arr)" } ]
[ { "from": "human", "value": "Construct a neural network in Python that can perform basic regression." }, { "from": "gpt", "value": "import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n...
[ { "from": "human", "value": "Generate a program in Python to take in two strings as input, and output a list of all thewords in both strings." }, { "from": "gpt", "value": "def string_to_list(s1, s2):\n s1_list = s1.split()\n s2_list = s2.split()\n output_list = s1_list + s2_list\n r...
[ { "from": "human", "value": "Create a web scraper using Python that retrieves the 10 most recent articles from a news website." }, { "from": "gpt", "value": "import requests \nfrom bs4 import BeautifulSoup \n \n# URL to scrap \nURL = 'http://example.com/news'\n \n# get the source code \nhtml_c...
[ { "from": "human", "value": "Create a Python program to convert HTML to plain text without using any libraries." }, { "from": "gpt", "value": "def html_to_text(html_string):\n output = ''\n in_tag = False\n for char in html_string:\n if char == '<':\n in_tag = True\n ...
[ { "from": "human", "value": "Write a python program to convert the given temperature from Celsius to Fahrenheit." }, { "from": "gpt", "value": "\"\"\"\nConvert the given temperature from Celsius to Fahrenheit\n\"\"\"\n\ndef celsius_to_fahrenheit(celsius):\n fahrenheit = (celsius * 9/5) + 32\n...
[ { "from": "human", "value": "Create a lambda expression in Python to filter a list of integer greater than 50." }, { "from": "gpt", "value": "list1 = [45, 12, 52, 89, 33, 99]\nfiltered_list = list(filter(lambda x: x > 50, list1))\n\nprint(filtered_list)" } ]
[ { "from": "human", "value": "Create a Python program to evaluate and compare the performance of two different heuristics algorithms." }, { "from": "gpt", "value": "import time\nimport heuristics_algorithm1\nimport heuristics_algorithm2\n\n#input data for algorithms\ndata1 = ...\ndata2 = ...\n\n#...
[ { "from": "human", "value": "Generate a function in Python that takes in a dictionary (string → integer) and returns the sum of all values in the dictionary." }, { "from": "gpt", "value": "def compute_dict_sum(input_dict):\n result = 0\n for val in input_dict.values():\n result += v...
[ { "from": "human", "value": "Write a Python script that filters a list of integers and returns only even numbers." }, { "from": "gpt", "value": "def filter_even_numbers(lst):\n # Filter out even numbers from the given list \n even_numbers = [num for num in lst if num % 2 == 0]\n return ...
[ { "from": "human", "value": "Generate a Python program that takes a sentence as input and prints out only the verbs." }, { "from": "gpt", "value": "import nltk\n\ndef extract_verbs(sentence):\n tokens = nltk.word_tokenize(sentence)\n tags = nltk.pos_tag(tokens)\n verbs = [word for word,...
[ { "from": "human", "value": "Create an AI-based system in Python for predicting stock market movements." }, { "from": "gpt", "value": "#import libraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n#import data\ndata = pd.read_csv('data.csv'...
[ { "from": "human", "value": "Develop an API in Python that fetches data from an SQL database and presents the data in the form of a JSON." }, { "from": "gpt", "value": "import json \nimport sqlite3\nfrom flask import Flask, request, jsonify \n\napp = Flask(__name__) \n \ndef dict_factory(cursor...
[ { "from": "human", "value": "Generate a Python dictionary that contains the count of the characters in a given string." }, { "from": "gpt", "value": "def count_chars(string):\n count_dict = {}\n\n for char in string:\n if char in count_dict:\n count_dict[char] += 1\n ...
[ { "from": "human", "value": "Write a Python program to store and querying user data." }, { "from": "gpt", "value": "import json\n\nuser_data = {\"Name\": \"John\", \"Age\": 25, \"City\": \"New York\"}\n\ndef store_user_data(data):\n with open('user_data.json', 'w') as f:\n json.dump(da...
[ { "from": "human", "value": "You are required to write a Python program to optimize an equation." }, { "from": "gpt", "value": "def optimize_equation(equation):\n variables = []\n for term in equation.split('+'):\n var, count = term.strip().split(' ')\n variables.append((var,...
[ { "from": "human", "value": "Generate Python code that takes a list of strings and generates a list of lists of words from the strings. The returned list should have the first word for each string followed by following words for each string." }, { "from": "gpt", "value": "def get_word_lists(stri...
[ { "from": "human", "value": "Create a web scraper that extracts specific data from a given website." }, { "from": "gpt", "value": "The web scraper should utilize the Python package BeautifulSoup to parse webpages and extract the required data. BeautifulSoup will allow us to find HTML elements on...
[ { "from": "human", "value": "Construct a script in Bash that can install a given software." }, { "from": "gpt", "value": "#!/bin/bash\n\n# Download latest version of Python\ncurl -O https://www.python.org/ftp/python/3.8.5/Python-3.8.5.tgz\n\n# Extract the tgz file\ntar -xzf Python-3.8.5.tgz\n\n#...
[ { "from": "human", "value": "Write a function in Python that takes a list of integers and returns a new list containing only odd numbers." }, { "from": "gpt", "value": "def odd_numbers_list(numbers):\n return [num for num in numbers if num % 2 != 0]" } ]
[ { "from": "human", "value": "Create a Python script that adds two numbers together and prints the result." }, { "from": "gpt", "value": "def add(a, b):\n sum = a + b\n print(sum)\n\nadd(5,7)" } ]
[ { "from": "human", "value": "Design an algorithm in Python to find the most common elements in an array of integers." }, { "from": "gpt", "value": "def most_common(nums):\n # Create a dictionary to store the counts\n counts = {}\n\n # Iterate over the elements\n for num in nums:\n ...
[ { "from": "human", "value": "Write a Python program to find the maximum element in the given array [1, 10, 50, 3, 8]." }, { "from": "gpt", "value": "array = [1, 10, 50, 3, 8]\n\n# Get the maximum element\nmax_element = max(array)\n\nprint(max_element) # Output: 50" } ]
[ { "from": "human", "value": "Create a Python script to analyze the sentiment of a text." }, { "from": "gpt", "value": "import re\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.sentiment.vader import Sentiment...
[ { "from": "human", "value": "Create a Python script that takes a list of email addresses as input and prints a filtered list of email addresses that belong to a particular domain." }, { "from": "gpt", "value": "filtered_list = [email for email in list if email.endswith(\"@gmail.com\")]\n\nprint(...
[ { "from": "human", "value": "Generate a Python function to execute a valid insertion sort on a given list of integers." }, { "from": "gpt", "value": "def insertion_sort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i -1\n while j >= 0 and key < arr[j] :\n arr[j + 1] = arr[j]\n ...
[ { "from": "human", "value": "Generate a program to sort a list of numbers using Insertion Sort algorithm in Python." }, { "from": "gpt", "value": "def insertionSort(arr):\n\tfor i in range(1, len(arr)):\n\t\tcurrent = arr[i]\n\t\tj =i-1\n\t\twhile j>=0 and arr[j]>current:\n\t\t\tarr[j+1] = arr[j...
[ { "from": "human", "value": "Create an Python function that takes a string containing a numerical expression and returns the result." }, { "from": "gpt", "value": "def eval_expr(expr):\n return eval(expr)" } ]
[ { "from": "human", "value": "Given a json-formatted string, create a python program to parse it into a dict." }, { "from": "gpt", "value": "import json\n\ndata = '{\"name\": \"John\",\"age\": 30,\"address\": {\"city\": \"New York\",\"state\": \"NY\"}}'\n\ndata_dict = json.loads(data)" } ]
[ { "from": "human", "value": "Create a Python program to compress a given string by replacing all repeating characters with a single instance and its count." }, { "from": "gpt", "value": "def compress(s): \n # Initialize results \n output = \"\" \n \n # Initialize count \n count = 1\...
[ { "from": "human", "value": "Create a basic CRUD API for the BlogPost model with Python/Flask. The API should include endpoints for creating a post, getting all posts, getting a single post, editing a post, and deleting a post." }, { "from": "gpt", "value": "from flask import Flask, jsonify, req...
[ { "from": "human", "value": "Write a Python program that calculates the distance between two points on a two-dimensional plane." }, { "from": "gpt", "value": "#include <iostream>\n#include <math.h>\n\nint main() \n{ \n int x1 = 3; \n int y1 = 4; \n\n int x2 = -9; \n int y2 = -2;\n\n ...
[ { "from": "human", "value": "Create an AI-based chatbot in Python that can answer simple queries about a product or service." }, { "from": "gpt", "value": "import random\n\n# The answers to the queries\nanswers = {\n 'What is XYZ?': 'XYZ is a company that provides XYZ services.',\n 'What d...
[ { "from": "human", "value": "Generate a python program to read the contents from a given URL" }, { "from": "gpt", "value": "import requests\n\ndef read_url(url):\n r = requests.get(url)\n if r.status_code == 200:\n return r.text\n else:\n return None" } ]
[ { "from": "human", "value": "Code a function in Python that takes a list of integers (denoted by `lst`) and returns a list of booleans where each element of the output list is `True` if the corresponding element in the input list is a prime number, and `False` otherwise." }, { "from": "gpt", "va...
[ { "from": "human", "value": "Generate a program in Python to output the top 3 numbers from an array of integers" }, { "from": "gpt", "value": "def top_three(numbers):\n sorted_numbers = sorted(numbers, reverse=True)\n return sorted_numbers[:3]\n\nprint(top_three([7, 13, 5, 8, 50, 11, 64, 4...
[ { "from": "human", "value": "Using Python, build a dictionary containing the numbers from 1 to n as the key and the square of each number as the value." }, { "from": "gpt", "value": "my_dict = {}\n\nfor i in range(1,n+1):\n my_dict[i] = i**2\n\nprint(my_dict)" } ]
[ { "from": "human", "value": "Edit the following Python program to make a correct API request and parse the response." }, { "from": "gpt", "value": "import requests\n\nurl = 'https://api.example.com/users'\n\nheaders = {\n 'Authorization': 'Bearer YOUR_API_TOKEN',\n 'Content-Type': 'application/j...
[ { "from": "human", "value": "Create a Python program that takes in text input from the user and searches a given list of strings to find any matches." }, { "from": "gpt", "value": "import re \n \n# input string \nstrings = [\"First\",\"Second\",\"Third\"]\n\n# Get the string \ninp_str = input(\...
[ { "from": "human", "value": "Generate a program in Python to convert all characters of a string in lowercase." }, { "from": "gpt", "value": "def to_lower(string):\n return string.lower()" } ]
[ { "from": "human", "value": "Edit the following Python program to use a dictionary instead of a list." }, { "from": "gpt", "value": "items = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}\n\nfor key, value in items.items():\n print(value)" } ]
[ { "from": "human", "value": "Construct a prime number sieve in Python which returns a list of all primes up to a given number." }, { "from": "gpt", "value": "def primeSieve(n): \n prime_list = [True for i in range(n+1)] \n p = 2\n while (p * p <= n): \n if (prime_list[p] == True)...
[ { "from": "human", "value": "Write a python code to print all prime numbers between 1 and a given number n." }, { "from": "gpt", "value": "# Function to generate prime numbers between 1 and a given number n \ndef generate_prime_numbers(n): \n \n # Array for checking if a number is prime or n...
[ { "from": "human", "value": "Find the optimal solution to solve a knapsack problem using dynamic programming." }, { "from": "gpt", "value": "// A Naive recursive Python \n// program for 0-1 Knapsack problem \n \n# Returns the maximum value \n# that can be put in a knapsack of \n# capacity W \n...
[ { "from": "human", "value": "Using Python, create a function that calculates the objective function of a linear equation." }, { "from": "gpt", "value": "def linear_eq(a, b, c):\n return a*x + b*y - c\n\n# For example:\nresult = linear_eq(3, 5, 7)\nprint(result)" } ]
[ { "from": "human", "value": "Implement an insertion sort algorithm in Python." }, { "from": "gpt", "value": "def insertion_sort(list):\n for i in range(1,len(list)):\n key = list[i]\n j = i - 1\n while j>=0 and key < list[j]:\n list[j+1] = list[j]\n ...
[ { "from": "human", "value": "Write a python program to generate a random password given a set of letters, numbers, and characters." }, { "from": "gpt", "value": "import random \n \n \n# All the possible characters \n# that could go into the password \nstring = \"abcdefghijklmnopqrstuvwxyz01234...
[ { "from": "human", "value": "Develop a Python module to generate random numbers." }, { "from": "gpt", "value": "import random\n\ndef generate_random_numbers(length, min_value, max_value):\n return [random.uniform(min_value, max_value) for _ in range(length)]" } ]
[ { "from": "human", "value": "How do we use recursion to solve a given problem in Python?" }, { "from": "gpt", "value": "Recursion is a powerful technique for solving problems. It involves defining a problem in terms of itself. A recursion problem is solved by breaking it down into smaller proble...
[ { "from": "human", "value": "Create an application using Python and Flask to submit form data and store it in a database." }, { "from": "gpt", "value": "from flask import Flask, render_template, request, redirect\nimport sqlite3\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n return r...
[ { "from": "human", "value": "Optimize a Python program that processes a 2d array and stores the transpose output in a new array." }, { "from": "gpt", "value": "def transpose(A):\n n = len(A)\n m = len(A[0])\n\n B = [[0 for x in range(n)] for x in range(m)]\n\n for i in range(n):\n for j in range...
[ { "from": "human", "value": "Generate a Python script that takes any number of integer arguments and returns their sum." }, { "from": "gpt", "value": "def sum_ints(*args):\n total = 0\n for num in args:\n total += num\n \n return total\n\nprint(sum_ints(3, 5, 7))" } ]
[ { "from": "human", "value": "Create a function in Python which takes a list as input and returns the sum of the items in the list." }, { "from": "gpt", "value": "def sum_list(input_list):\n sum = 0\n for i in input_list:\n sum += i\n return sum" } ]
[ { "from": "human", "value": "Create a Selenium script in Python to automate the login process in a given website." }, { "from": "gpt", "value": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\n# Initialize web driver\ndriver = webdriver.Chrome()\n\...
[ { "from": "human", "value": "Create an AI model in Python to classify emails from the Enron Spam Dataset as either spam or non-spam." }, { "from": "gpt", "value": "import pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_spl...
[ { "from": "human", "value": "Re-write the following SQL query in Python." }, { "from": "gpt", "value": "import sqlite3\n\nconn = sqlite3.connect('movies.db') \ncursor = conn.cursor()\n\ncursor.execute(\"SELECT * FROM Movies WHERE category = 'horror'\")\n\nresult = cursor.fetchall()\nfor row in r...
[ { "from": "human", "value": "Take two matrices, A and B, and produce a matrix C where each element is the product of the corresponding elements of A and B." }, { "from": "gpt", "value": "# Python\ndef matrixMultiplication(A, B):\n if len(A[0]) != len(B):\n return \"Matrix multiplicatio...
[ { "from": "human", "value": "Come up with a correct approach to optimize the following python program." }, { "from": "gpt", "value": "numbers = [1, 2, 3, 4, 5, 6]\n\nprint(*numbers, sep='\\n')" } ]
[ { "from": "human", "value": "Design a program in Python to detect the vowel in a given string." }, { "from": "gpt", "value": "def vowelCheck(inputString): \n vowels = ['a','e','i','o','u','A','E','I','O','U'] \n for x in inputString: \n if x in vowels: \n return x" } ]
[ { "from": "human", "value": "Convert a given SQL statement into a Python Pandas DataFrame." }, { "from": "gpt", "value": "import pandas as pd\n\ndf = pd.read_sql_query(\"SELECT * FROM book;\", conn)" } ]
[ { "from": "human", "value": "Using the data provided, generate a histogram in Python." }, { "from": "gpt", "value": "import matplotlib.pyplot as plt\n\ndata = [3, 5, 7, 2, 8, 10, 11, 65, 72, 81, 99, 100, 150]\n\n# plotting the histogram \nplt.hist(data, bins = [0, 20, 40, 60, 80, 100, 120, 140, ...
[ { "from": "human", "value": "Create a Python script to populate an array with random numbers from 1-100." }, { "from": "gpt", "value": "import random\n\ndef populateArray(array_length):\n array = []\n for i in range(array_length):\n array.append(random.randint(1, 100))\n return array" } ]
[ { "from": "human", "value": "Create an natural language processing application in Python that extracts the top 10 most frequent words from a given text." }, { "from": "gpt", "value": "from collections import Counter\n\ntext = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eius...
[ { "from": "human", "value": "Given an array of strings, write a Python function to remove all duplicates and return the resulting array." }, { "from": "gpt", "value": "def removeDuplicates(arr):\n result = [] \n \n # traverse for all elements \n for i in arr: \n \n # check if exists in result...
[ { "from": "human", "value": "Generate a Python script to find the longest common substring in two strings." }, { "from": "gpt", "value": "def longest_common_substring(str1, str2):\n match = 0\n substr = \"\"\n for i in range(len(str1)):\n for j in range(len(str2)):\n l...
[ { "from": "human", "value": "Write a function in Python to search for a character in a given string." }, { "from": "gpt", "value": "def serach_char(input_str, char):\n for char in input_str:\n if char == input_char:\n return True\n return False" } ]
[ { "from": "human", "value": "Write a python program to parse an XML document and return a list of tag objects." }, { "from": "gpt", "value": "def parse_xml(text):\n tag_objects = []\n\n root = ET.fromstring(text)\n for child in root:\n tag = Tag(child.attrib[\"id\"])\n for...
[ { "from": "human", "value": "Based on a given input, create a function in Python to generate a random string of length 6." }, { "from": "gpt", "value": "import random\nimport string\n\ndef random_string(length):\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for...
[ { "from": "human", "value": "Create a Python program to average the elements of a 2-dimensional array." }, { "from": "gpt", "value": "def averageMatrix(matrix):\n sum = 0\n for row in matrix:\n for e in row:\n sum += e\n\n return sum / (len(matrix) * len(matrix[0]))\n\na = [[3,2,6],\n [8,...
[ { "from": "human", "value": "Generate a code in Python to convert a number into binary format." }, { "from": "gpt", "value": "\"\"\"\nGenerate a code in Python to convert a number into binary format\n\"\"\"\ndef convert_to_binary(num):\n # check if the number is 0, if so return 0\n if num ...
[ { "from": "human", "value": "Generate a python program that takes an integer and then prints out the factorial of it?" }, { "from": "gpt", "value": "def factorial(num):\n if num <= 1:\n return 1\n else:\n return num * factorial(num - 1) \n\nn = int(input(\"Enter a number: \")...
[ { "from": "human", "value": "Write a Python program to convert a positive integer to negative or vice versa using bitwise NOT operator." }, { "from": "gpt", "value": "def convert_to_negative(x): \n return ~x + 1 \n \ndef convert_to_positive(x): \n return ~(x-1)" } ]
[ { "from": "human", "value": "Build a simple blockchain system in Python." }, { "from": "gpt", "value": "import hashlib\nimport json\n\n# Define the Block class\nclass Block:\n def __init__(self, index, timestamp, data, previous_hash):\n self.index = index\n self.timestamp = timestamp\n self.data...
[ { "from": "human", "value": "Write a Python script to find the GCD of two numbers." }, { "from": "gpt", "value": "def findGCD(a, b): \n if (b == 0): \n return a\n return findGCD(b, a % b)\n \na = 1000\nb = 500\nprint(\"GCD of number is: \", findGCD(a, b))" } ]
[ { "from": "human", "value": "Create a program in Python to find the number of occurrences of an element x in a list y." }, { "from": "gpt", "value": "def count_x(x, y):\n count = 0\n for i in y:\n if i == x:\n count += 1\n return count" } ]
[ { "from": "human", "value": "Write a Python program to convert ratings in a list of strings to a float." }, { "from": "gpt", "value": "def str_to_float(ratings):\n return [float(x) for x in ratings]" } ]
[ { "from": "human", "value": "Create a Python program that encrypts a message using a Caesar cipher." }, { "from": "gpt", "value": "def caesar_encrypt(message, shift):\n encrypted_message = \"\"\n for c in message:\n encrypted_c = ord(c) + shift\n if encrypted_c > 126:\n ...
[ { "from": "human", "value": "Write a Python program to find the largest three numbers in a list." }, { "from": "gpt", "value": "my_list = [1, 6, 3, 8, 7, 4]\nlargest_three = sorted(my_list)[-3:]\nprint(largest_three)" } ]
[ { "from": "human", "value": "Given two binary trees, check if the first tree is subtree of the second tree." }, { "from": "gpt", "value": "# Python program to check if \n# a binary tree is subtree of another binary tree \n \n# A binary tree node \nclass Node: \n \n # Constructor to crea...
[ { "from": "human", "value": "Write a Python program to swap the values of two variables." }, { "from": "gpt", "value": "x = 5\ny = 10\n\n# Swapping process \nx, y = y, x \n\nprint(\"x:\", x) \nprint(\"y:\", y)" } ]
[ { "from": "human", "value": "Optimize the following Python code to use built-in functions." }, { "from": "gpt", "value": "def removeDuplicates(array): \n finalArray = []\n for element in array: \n if element not in finalArray: \n finalArray.append(element)\n return fin...
[ { "from": "human", "value": "Create a program in Python that takes a list of words and an integer n and returns a list of words that appear at least n times in the given list." }, { "from": "gpt", "value": "from collections import Counter\n\ndef frequent_words(words, n):\n counts = Counter(wo...
[ { "from": "human", "value": "Devise a Python program to determine whether a given number is even or odd." }, { "from": "gpt", "value": "def even_or_odd(num):\n if num % 2 == 0:\n return \"Even\"\n else:\n return \"Odd\"" } ]
[ { "from": "human", "value": "Compose a basic blockchain system in Python." }, { "from": "gpt", "value": "import hashlib\nimport json\n\n# We will use SHA256 as our hashing function\ndef sha256(data):\n hash_function = hashlib.sha256()\n hash_function.update(data.encode('utf-8'))\n retur...
[ { "from": "human", "value": "Provide a Python code that uses the exponential smoothing algorithm to predict the next day's forecast temperature given the past three day's forecast temperatures." }, { "from": "gpt", "value": "\"\"\"\nThis code uses the exponential smoothing algorithm to predict t...
[ { "from": "human", "value": "Write a function in Python to sort a dictionary according to its values, in descending order." }, { "from": "gpt", "value": "def sortDictionary(dictionary):\n sorted_list = sorted(dictionary.items(), key=lambda x: x[1], reverse=True)\n sorted_dictionary = dict(sort...
[ { "from": "human", "value": "Create a function in Python to generate a multiplication table with numbers in a range given start and end parameters." }, { "from": "gpt", "value": "def multiplication_table(start, end):\n\tfor x in range(start, end + 1):\n\t\tfor y in range(start, end + 1):\n\t\t\t...
[ { "from": "human", "value": "Write a python program to identify if a string s has matching parentheses" }, { "from": "gpt", "value": "def matching_paren(s):\n stack = []\n for char in s:\n if char == '(':\n stack.append(char)\n elif char == ')':\n if len...
[ { "from": "human", "value": "Develop a function in Python to take as input two array of integers and swap their elements." }, { "from": "gpt", "value": "def swap(arr1, arr2):\n assert len(arr1) == len(arr2)\n for i in range(len(arr1)):\n temp = arr1[i]\n arr1[i] = arr2[i]\n ...
[ { "from": "human", "value": "Can you design a function in Python for reversing a list?" }, { "from": "gpt", "value": "def reverse_list(list): \n return list[::-1]" } ]
[ { "from": "human", "value": "Create a Python script to build a dictionary from string to string of the given samples." }, { "from": "gpt", "value": "def build_dictionary(samples):\n dictionary = {}\n for sample in samples:\n key, value = sample.split(\"->\")\n dictionary[key] = value\n return ...
[ { "from": "human", "value": "Write a Python script to find the average of numbers stored in an array." }, { "from": "gpt", "value": "def calculate_mean(numbers):\n total_sum = 0\n for num in numbers:\n total_sum += num\n mean = total_sum / len(numbers)\n return mean\n\nprint(c...
[ { "from": "human", "value": "Generate a Python program that takes two lists as input and returns a new list containing only the common elements." }, { "from": "gpt", "value": "def common_elements(list1, list2): \n common_list=[]\n for element in list1: \n if element in list2: \n ...
[ { "from": "human", "value": "Create a loop in Python to print out all the odd numbers from 1 to 10." }, { "from": "gpt", "value": "for i in range(1, 11):\n if i % 2 != 0:\n print(i)" } ]
[ { "from": "human", "value": "Create a machine learning model in Python that predecits customer lifetime value given a customer's past transactions." }, { "from": "gpt", "value": "import pandas as pd\nimport numpy as np\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble im...
[ { "from": "human", "value": "Given a list of numbers and a target number, write a Python program to find a pair of numbers from the given list that add up to the given target." }, { "from": "gpt", "value": "def find_pair(lst, target):\n for i in range(len(lst)):\n if (target - lst[i]) ...
[ { "from": "human", "value": "Develop a class in Python to perform various matrix operations like addition, subtraction, multiplication and transpose." }, { "from": "gpt", "value": "class Matrix: \n def __init__(self, m, n, lst): \n self.m = m \n self.n = n ...