conversations listlengths 2 2 |
|---|
[
{
"from": "human",
"value": "Read a given list of strings and create a new list of all strings that are longer than 5 characters long."
},
{
"from": "gpt",
"value": "def filter_long_strings(string_list):\n long_strings = []\n for string in string_list:\n if len(string) > 5:\n long_strings.append... |
[
{
"from": "human",
"value": "Craft an algorithm in Python to move all zeroes in a list to the end of the list."
},
{
"from": "gpt",
"value": "def move_zeroes(lst):\n # Count the number of non-zero elements\n num_non_zeroes = 0\n for num in lst:\n if num != 0:\n num_non... |
[
{
"from": "human",
"value": "Create a Python program to implement the Fibonacci sequence."
},
{
"from": "gpt",
"value": "def fibonacci_seq(n): \n if n==0: \n return 0\n elif n==1: \n return 1\n else: \n return fibonacci_seq(n-1)+fibonacci_seq(n-2)"
}
] |
[
{
"from": "human",
"value": "Write a function in Python to print out an array backwards."
},
{
"from": "gpt",
"value": "def print_reverse_array(arr):\n for i in range(len(arr)-1, -1, -1): \n print(arr[i])"
}
] |
[
{
"from": "human",
"value": "Create a Python program to find the possible prime numbers from one to one hundred by using the Sieve of Eratosthenes algorithm."
},
{
"from": "gpt",
"value": "def sieve_eratosthenes(n): \n prime_list = [True] * (n+1) \n prime_list[0] = False\n prime_list[1]... |
[
{
"from": "human",
"value": "Create a Python function named \"Transpile\" that takes in four arguments: \"src_dir\", \"dst_dir\", \"model_filename\", and \"params_filename\". Inside the function, create a CPUPlace object and an Executor object using Paddle Fluid. Then, create a Scope object using fluid.core... |
[
{
"from": "human",
"value": "Create a Python function called add_marks which takes two parameters: marks(a list) and mark(an integer). The function should add the mark to each value in the marks list."
},
{
"from": "gpt",
"value": "def add_marks(marks, mark):\n return [m + mark for m in marks]"
... |
[
{
"from": "human",
"value": "Design a positive feedback loop for the following python program."
},
{
"from": "gpt",
"value": "for i in range(10):\n print(\"hello\")\n i += 1\n if i == 10:\n print(\"You've got it!\")"
}
] |
[
{
"from": "human",
"value": "Implement a function that prints out the numbers from 1 to 50 in python"
},
{
"from": "gpt",
"value": "def print_numbers():\n for i in range(1, 51):\n print(i)\n\nprint_numbers()"
}
] |
[
{
"from": "human",
"value": "Write a Python program to send an automated email. The program should take a list of emails as input, iterate over the list, and send an email to each address."
},
{
"from": "gpt",
"value": "import smtplib\n\nsender_email = 'example@gmail.com'\npassword = 'example_pa... |
[
{
"from": "human",
"value": "Create a Python class which represents a 3D Vector"
},
{
"from": "gpt",
"value": "class Vector3D:\n def __init__(self, x, y, z):\n self.x = x\n self.y = y\n self.z = z\n \n def __str__(self):\n return \"(\" + str(self.x) + \", \" ... |
[
{
"from": "human",
"value": "Given two strings, write a Python program to find the total number of common characters present in both strings"
},
{
"from": "gpt",
"value": "def num_common_chars(str1, str2):\n common = 0\n for c in str1:\n if c in str2:\n common += 1\n r... |
[
{
"from": "human",
"value": "Modify the following Python code to handle errors."
},
{
"from": "gpt",
"value": "def read_data_from_json(filename):\n try:\n with open(filename, 'r') as f:\n data = json.load(f)\n return data\n except FileNotFoundError:\n print(... |
[
{
"from": "human",
"value": "Analyze a given Python code and write a function that checks if a given number is prime."
},
{
"from": "gpt",
"value": "def primeCheck(num):\n if num > 1:\n for i in range(2, num):\n if (num % i) == 0:\n return False\n else:\n return False\n return True"
}
] |
[
{
"from": "human",
"value": "Create a python program to filter out all the even numbers from a given list."
},
{
"from": "gpt",
"value": "def filter_even_numbers(numbers):\n even_numbers = []\n for i in numbers:\n if i % 2 == 0:\n even_numbers.append(i)\n return even_n... |
[
{
"from": "human",
"value": "Implement a function in Python that takes a Huffman tree and drop all its leaf nodes."
},
{
"from": "gpt",
"value": "def dropLeafNodes(head): \n \n # If node is not None and doesn't have any children \n if head and not head.left and not head.right: \n ... |
[
{
"from": "human",
"value": "Create a web crawler in Python that starts from a website and looks for other links in the page then scrapes the page content."
},
{
"from": "gpt",
"value": "import requests\nfrom bs4 import BeautifulSoup\nimport re\n\ndef crawl(url):\n visited = set()\n queue = [url... |
[
{
"from": "human",
"value": "Write a Python program to calculate the maximum, minimum and mean number of elements in a given string."
},
{
"from": "gpt",
"value": "def get_stats_for_string(string):\n num_elements = len(string)\n max_element = max(string)\n min_element = min(string)\n ... |
[
{
"from": "human",
"value": "Write a Python program to calculate the compound interest."
},
{
"from": "gpt",
"value": "def compoundInterest(investment_amount, rate_of_interest, time):\n compound_interest = investment_amount * (pow((1 + rate_of_interest / 100), time))\n return compound_inte... |
[
{
"from": "human",
"value": "Create a command-line application in Python that stores customer data and allows customer to query by customer name"
},
{
"from": "gpt",
"value": "import sys \n \ndef print_customer_data(name): \n # Code for searching customer data by customer name and \n # pr... |
[
{
"from": "human",
"value": "Develop a program in Python to calculate the Fibonacci sequence."
},
{
"from": "gpt",
"value": "def 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... |
[
{
"from": "human",
"value": "Generate a python program that takes two sets of integers as input and outputs the intersection of those sets."
},
{
"from": "gpt",
"value": "def intersection(set1, set2): \n return set1 & set2\n\nresult = intersection(set1, set2) \nprint(result)"
}
] |
[
{
"from": "human",
"value": "Design an algorithm in Python to find the smallest number in a given list."
},
{
"from": "gpt",
"value": "def smallestNumber(nums):\n smallest = nums[0]\n for i in range(1, len(nums)):\n if nums[i] < smallest:\n smallest = nums[i]\n return ... |
[
{
"from": "human",
"value": "Generate a python program for printing a Pascal triangle."
},
{
"from": "gpt",
"value": "def PascalTriangle(n) : \n \n # An auxiliary array to store \n # generated pscal triangle values \n arr = [0 for i in range(n)] \n \n # Iterate through ever... |
[
{
"from": "human",
"value": "Create a python script that filters out all negative numbers from the given matrix"
},
{
"from": "gpt",
"value": "import numpy as np\n\ndef filter_out_negative(matrix):\n # Convert matrix to numpy array\n matrix = np.array(matrix)\n # Find all negative numbers and... |
[
{
"from": "human",
"value": "Create a basic REST API using Python and Flask to list all the countries in the world."
},
{
"from": "gpt",
"value": "import flask\nfrom flask import Flask, request, jsonify\nimport json\n\napp = Flask(name)\n\n@app.route('/countries', methods=['GET'])\ndef get_count... |
[
{
"from": "human",
"value": "Create a web scraper in Python that can extract hotel reviews from TripAdvisor."
},
{
"from": "gpt",
"value": "import requests\nfrom bs4 import BeautifulSoup\n\n# Define the URL and the headers\nurl = '<url>'\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; W... |
[
{
"from": "human",
"value": "Develop a machine learning model in Python to identify the author of a given article."
},
{
"from": "gpt",
"value": "from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.pipeline import Pipeline\nfrom s... |
[
{
"from": "human",
"value": "Write a Python program to divide a given list of numbers into two equal parts such that the difference between the sum of the two parts is minimum."
},
{
"from": "gpt",
"value": "def divide_in_two_equal_parts(lst):\n target = sum(lst) // 2\n part1 = []\n par... |
[
{
"from": "human",
"value": "Develop an algorithm to detect and fix Python syntax errors in a given code snippet."
},
{
"from": "gpt",
"value": "def test():\n x = 5\n y = 3\n try:\n z\n except NameError:\n print(\"NameError: Name 'z' is not defined\")"
}
] |
[
{
"from": "human",
"value": "Design a data structure in Python to store integer values."
},
{
"from": "gpt",
"value": "class IntList:\n def __init__(self):\n self.values = []\n \n def add_value(self, value):\n self.values.append(value)\n \n def find_min(self):\n ... |
[
{
"from": "human",
"value": "Create an algorithm in Python for a linear search. The algorithm should take in an array and a value to search for, and return the index of the value if it is found, or -1 if it is not."
},
{
"from": "gpt",
"value": "def linearSearch(arr, value):\n for i in range(le... |
[
{
"from": "human",
"value": "Given a list of strings, write a Python function to remove all the whitespaces from each string."
},
{
"from": "gpt",
"value": "def remove_whitespace(word_list):\n return [word.strip() for word in word_list]\n\nstripped_list = remove_whitespace(['Hello World ', ... |
[
{
"from": "human",
"value": "Design a Python program to randomize a list of given integers using an optimized Fisher-Yates algorithm."
},
{
"from": "gpt",
"value": "def randomized_list(num_list):\n for i in range(len(num_list)-1,0,-1):\n j = random.randint(0,i)\n num_list[i],num... |
[
{
"from": "human",
"value": "Create a system in Python for generating natural language responses."
},
{
"from": "gpt",
"value": "from tensorflow.keras.layers import Input, Dense, Embedding, GRU\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.utils import plot_model\n\n# Create ... |
[
{
"from": "human",
"value": "Create a web scraper using Python that collects the title and content from the homepage of a given website."
},
{
"from": "gpt",
"value": "import requests\nimport bs4\n\nurl = 'https://www.example.com'\nr = requests.get(url)\nhtml = bs4.BeautifulSoup(r.text,\"html.pa... |
[
{
"from": "human",
"value": "Generate a Python script that finds the total surface area of a cuboid, given its three dimensions."
},
{
"from": "gpt",
"value": "def find_total_surfacearea(length, breadth, height):\n return (2*(length*breadth + breadth*height + height*length))\n\nprint(find_tota... |
[
{
"from": "human",
"value": "Generate a Python program to clean a string of HTML tags."
},
{
"from": "gpt",
"value": "import re\n\n# Clean a string of HTML tags \ndef clean_html_tags(str):\n clean_str = re.sub(\"<.*?>\", \"\", str)\n return clean_str\n\nhtml_string = \"<p>This is a <b>test... |
[
{
"from": "human",
"value": "Generate a Python function that takes an integer array as input and returns the number of unique elements in the array."
},
{
"from": "gpt",
"value": "def num_unique_elements(arr):\n unique_arr = set(arr)\n return len(unique_arr)\n\nprint(num_unique_elements([1... |
[
{
"from": "human",
"value": "Create a Python program to scrape an online news website to get the headlines."
},
{
"from": "gpt",
"value": "import requests\nfrom bs4 import BeautifulSoup \n\n# url of the website you want to scrape \nurl = \"https://www.news.com/\" \n\n# get the response in the fo... |
[
{
"from": "human",
"value": "Edit the given Python program to print 'Happy Holidays' 10 times."
},
{
"from": "gpt",
"value": "for i in range(10):\n print('Happy Holidays')"
}
] |
[
{
"from": "human",
"value": "Combine 2 strings and reverse the result in Python."
},
{
"from": "gpt",
"value": "words = \"Hello \"\nwords2 = \"world!\"\n\ncombined = words + words2\nresult = combined[::-1]\n\nprint(result)"
}
] |
[
{
"from": "human",
"value": "Create a class to represent a bank account in Python."
},
{
"from": "gpt",
"value": "class BankAccount:\n \n def __init__(self, name, balance):\n self.name = name\n self.balance = balance\n \n def deposit(self, amount):\n self.bal... |
[
{
"from": "human",
"value": "Optimize the following Python code to sort a set of numbers (set = [2, 6, 3, 8, 4]) in O(n) time complexity."
},
{
"from": "gpt",
"value": "def sort_list(unsorted_list):\n sorted_list = []\n while unsorted_list:\n min_elem = min(unsorted_list)\n u... |
[
{
"from": "human",
"value": "Design a Python program to perform linear regression for predicting the numbers in a given dataset."
},
{
"from": "gpt",
"value": "import numpy as np\nfrom sklearn.linear_model import LinearRegression\n\nX = np.array([1,2,3,4,5]).reshape(-1,1)\nY = np.array([3,5,7,9,... |
[
{
"from": "human",
"value": "Create a Python object that contains two attributes, \"Name\" and \"Age\"."
},
{
"from": "gpt",
"value": "class Person:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\nperson = Person(\"John\", 25)"
}
] |
[
{
"from": "human",
"value": "Write a function in Python that takes a list of objects and returns a list of those objects sorted by one of their attributes."
},
{
"from": "gpt",
"value": "def sort_by_attr(objects, attr):\n return sorted(objects, key=lambda item: item[attr])\n \nsort_by_attr([{\"n... |
[
{
"from": "human",
"value": "Write a Python program to generate an HTML table displaying information about the top 10 bestselling books in a specific genre."
},
{
"from": "gpt",
"value": "import sqlite3\n\n# connect to the database\nconn = sqlite3.connect('books.db')\nc = conn.cursor()\n\n# retr... |
[
{
"from": "human",
"value": "Create a Python script to filter out all the vowels from a string."
},
{
"from": "gpt",
"value": "def filter_vowels(string):\n vowels = ('a', 'e', 'i', 'o', 'u')\n return ''.join(c for c in string if c not in vowels)"
}
] |
[
{
"from": "human",
"value": "In Python, write a script to sort the list items in descending order."
},
{
"from": "gpt",
"value": "list_items = [3, 7, 5, 8, 10]\n\nlist_items.sort(reverse=True)\n\nprint(list_items) # Output: [10, 8, 7, 5, 3]"
}
] |
[
{
"from": "human",
"value": "Create a Python function that takes in a text string and returns a dictionary of words and the number of times each word appears in the text string."
},
{
"from": "gpt",
"value": "def words_count(text):\n words_dict = {}\n for word in text.split(' '):\n if word in wo... |
[
{
"from": "human",
"value": "Create an object-oriented structure to solve a maze by using python."
},
{
"from": "gpt",
"value": "import collections\n\nclass Maze:\n def __init__(self, n, m):\n self._n, self._m = n, m\n self._grid = [[None] * m for _ in range(n)]\n\n def solve... |
[
{
"from": "human",
"value": "Compose a piece of code to print the length of a given string."
},
{
"from": "gpt",
"value": "string = \"Python\"\nprint(\"Length of the given string is:\", len(string))"
}
] |
[
{
"from": "human",
"value": "Compose a Python program to calculate the maximum possible revenue from the items with given weights and values."
},
{
"from": "gpt",
"value": "\"\"\"\nCalculate the maximum possible revenue from the items with given weights and values\n\"\"\"\n\n# given weights and... |
[
{
"from": "human",
"value": "Write a Python program to read in a tweet and remove all punctuation, special characters and stopwords."
},
{
"from": "gpt",
"value": "import re\nimport string\nfrom nltk.corpus import stopwords\n\ntweet = \"I'm so excited to be going to the #MuseumTour! #BigDay #tra... |
[
{
"from": "human",
"value": "Implement a web scraper in Python to extract the top ten trending YouTube videos."
},
{
"from": "gpt",
"value": "import requests\nfrom bs4 import BeautifulSoup\n\n# make a request to get the page content\npage = requests.get(\"https://www.youtube.com/feed/trending\")... |
[
{
"from": "human",
"value": "Make a code in Python to find the mode of the given set of values."
},
{
"from": "gpt",
"value": "def find_mode(list):\n max_count = 0\n mode = list[0]\n count = {}\n for item in list:\n if (item in count):\n count[item] += 1\n else:\n count[item]... |
[
{
"from": "human",
"value": "Create a web API with Python and Flask to give the current date and time."
},
{
"from": "gpt",
"value": "from flask import Flask\nimport datetime\n\napp = Flask(__name__)\n\n@app.route('/datetime')\ndef get_datetime():\n return datetime.datetime.now().strftime(\"%... |
[
{
"from": "human",
"value": "Create a Python function that takes a list containing fruit names and returns the most common fruit name."
},
{
"from": "gpt",
"value": "def most_common_fruit(fruit_list):\n \n # Dictionary to get count of each fruit\n freq_dict = {}\n \n # Count frequency o... |
[
{
"from": "human",
"value": "Write a Python program to take in a list of phrases and generate a string with the each phrase followed by its length."
},
{
"from": "gpt",
"value": "result = \"A bird in the hand (17)is worth two in the bush (25)\"\n \ncode:\ninput_phrases = [\"A bird in the hand\",... |
[
{
"from": "human",
"value": "Write a simple Python function that takes a list of integers and returns the sum of all elements divisible by 3."
},
{
"from": "gpt",
"value": "def divisibleBy3(li):\n total = 0\n for num in li:\n if num % 3 == 0:\n total += num\n return total\n# Output: 24"
}
] |
[
{
"from": "human",
"value": "Create a program in Python that takes a number from the user and prints all the divisors of the number."
},
{
"from": "gpt",
"value": "divisors = []\n\nnum = int(input('Enter a number: '))\n \nfor i in range(1, num + 1):\n if num % i == 0:\n divisors.append... |
[
{
"from": "human",
"value": "Write a Python program to generate an HTML page containing a table with some employee data."
},
{
"from": "gpt",
"value": "<html>\n <head>\n <title>Employee Data</title>\n </head>\n <body>\n <table>\n <thead>\n <tr>\n <th>Name</th>\n ... |
[
{
"from": "human",
"value": "Create a Python function to select all rows from a table where the 'status' is 'approved'"
},
{
"from": "gpt",
"value": "def select_approved_rows():\n sql = \"SELECT * FROM table WHERE status = 'approved'\"\n cur.execute(sql)\n return cur.fetchall()"
}
] |
[
{
"from": "human",
"value": "Create a Python program to generate random passwords of length 8 characters, containing at least one lowercase letter, one uppercase letter and one number."
},
{
"from": "gpt",
"value": "from random import choice\nimport string\n\ndef generate_password():\n chars ... |
[
{
"from": "human",
"value": "Generate a solution to translate a text from English to French using Python."
},
{
"from": "gpt",
"value": "# install the module \n# in command prompt\npip install googletrans\n\n# import module\nfrom googletrans import Translator\n\n# create an object\ntranslator = ... |
[
{
"from": "human",
"value": "Create a function to generate a unique 6 digit number."
},
{
"from": "gpt",
"value": "# Python program to generate \n# a unique 6 digit number \nimport random \ndef generate_number(): \n \n # Choose a random number \n # between 10000 and 99999 \n random... |
[
{
"from": "human",
"value": "Write a Python program to generate 10 random numbers and put them in a list."
},
{
"from": "gpt",
"value": "import random\n\nrandom_list = []\nfor i in range(10):\n number = random.randint(1, 100)\n random_list.append(number)"
}
] |
[
{
"from": "human",
"value": "Write a Python program to replace all occurrences of a given string with an alternate string."
},
{
"from": "gpt",
"value": "def replace_string(input_string, target_string, replacement_string):\n return input_string.replace(target_string, replacement_string)\n\npr... |
[
{
"from": "human",
"value": "Generate a Python class for an online store item that includes fields for ID, name, price, and description."
},
{
"from": "gpt",
"value": "class StoreItem:\n def __init__(self, item_id, name, price, description):\n self.item_id = item_id\n self.name ... |
[
{
"from": "human",
"value": "Create a virtual assistant using Python and Dialogflow to answer a basic set of questions."
},
{
"from": "gpt",
"value": "import dialogflow_v2 as dialogflow\nimport requests\n\nproject_id = 'project-id'\nsession_client = dialogflow.SessionsClient()\nsession = session... |
[
{
"from": "human",
"value": "Create an algorithm in Python to solve \"Tower of Hanoi\" game of a 4 disk problem."
},
{
"from": "gpt",
"value": "def solveTowerOfHanoi(num_disks, start_rod = 'A', end_rod = 'C', aux_rod = 'B'): \n if num_disks == 1: \n print(\"Move disk 1 from rod\", star... |
[
{
"from": "human",
"value": "Generate an api response in Python for the provided data."
},
{
"from": "gpt",
"value": "response = {\n \"status\": 200,\n \"data\": {\"name\": \"John\",\"age\":28},\n \"message\": \"Success\"\n}"
}
] |
[
{
"from": "human",
"value": "Create a webscraper using Python’s Selenium that retrieves data from an online store."
},
{
"from": "gpt",
"value": "from selenium import webdriver\n\n# create a new Firefox session\ndriver = webdriver.Firefox()\ndriver.implicitly_wait(30)\ndriver.maximize_window()\n... |
[
{
"from": "human",
"value": "Develop a web scraper with Python BeautifulSoup to scrape data from an online web store."
},
{
"from": "gpt",
"value": "import requests\nfrom bs4 import BeautifulSoup\n \n# Make a GET request to fetch the raw HTML content\nhtml_content = requests.get('http://web-stor... |
[
{
"from": "human",
"value": "Implement a basic algorithm in Python to calculate the nth Fibonacci number."
},
{
"from": "gpt",
"value": "def 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 \nprint(fibonacci(6)) // 8"
}
] |
[
{
"from": "human",
"value": "Create a Python class that receives two strings and has methods for comparing the strings and returning whether they are equal, different, or similar up to a provided threshold."
},
{
"from": "gpt",
"value": "class StringComparator:\n\ndef __init__(self, string1, str... |
[
{
"from": "human",
"value": "Generate a program in Python to evaluate the accuracy of a machine-learning model."
},
{
"from": "gpt",
"value": "import numpy as np\nfrom sklearn.metrics import accuracy_score\n\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\n\n# Calculating the accuracy\n... |
[
{
"from": "human",
"value": "Write a Python program to replace all occurrences of a character in a string with the provided replacement character."
},
{
"from": "gpt",
"value": "def replace_all_occurrences(str, char, replacement):\n return str.replace(char, replacement)\n\nprint(replace_all_occ... |
[
{
"from": "human",
"value": "Create a python program to find the largest prime factor of a number."
},
{
"from": "gpt",
"value": "import math\n\ndef largest_prime_factor(n):\n\n# Separate the list of larger factors of the number into prime and composite numbers \n factors = []\n for i in r... |
[
{
"from": "human",
"value": "Write a Python program to check if an element exists within a given list of integers."
},
{
"from": "gpt",
"value": "def element_exists(elem, list_int):\n return elem in list_int"
}
] |
[
{
"from": "human",
"value": "Create a Python program that takes a sentence and converts it to Morse code."
},
{
"from": "gpt",
"value": "MORSE_CODE = {\n 'A': '.-', 'B': '-...',\n 'C': '-.-.', 'D': '-..',\n 'E': '.', 'F': '..-.',\n 'G': '--.', 'H': '....',\n 'I': '..', 'J': '.---',\n 'K': '-.-',... |
[
{
"from": "human",
"value": "Generate a python program to sort a list of numbers"
},
{
"from": "gpt",
"value": "def sort_list(array): \n n = len(array) \n \n for i in range(n): \n \n min_idx = i \n for j in range(i+1, n): \n if array[min_idx] > array[j]: \n ... |
[
{
"from": "human",
"value": "Create a program in Python to remove all the occurrences of an item from a list."
},
{
"from": "gpt",
"value": "def removeItem(list, item):\n # loop through the list\n for i in list:\n # check if the element is the item to remove\n if i == item:\n... |
[
{
"from": "human",
"value": "Could you build a web scraper in Python that collects all the links from a website?"
},
{
"from": "gpt",
"value": "# Python program to scrape a webpage\nimport requests as req \nfrom bs4 import BeautifulSoup \n \nURL = \"http://www.example.com/\"\n \n# GET request ... |
[
{
"from": "human",
"value": "Generate a Python program to delete a given key from a dictionary."
},
{
"from": "gpt",
"value": "dictionary = {'foo': 1, 'bar': 2, 'baz': 3}\nkey = 'baz'\n\ndef delete_key(dic, k):\n if k in dic:\n del dic[k]\n\ndelete_key(dictionary, key)\n\nprint(dictionary)"
... |
[
{
"from": "human",
"value": "Analyze the following Python function to detect any potential errors."
},
{
"from": "gpt",
"value": "The function is attempting to modify the list while iterating over it. This can lead to unexpected behavior and should be avoided. To fix the code, the list should be... |
[
{
"from": "human",
"value": "Generate a Python program to reverse the order of words in a sentence but keep the order of the characters in each word the same."
},
{
"from": "gpt",
"value": "def reverse_words(string):\n words = string.split(\" \")\n reversed_words = []\n for word in words:\n ... |
[
{
"from": "human",
"value": "Port a Java code snippet to Python 3."
},
{
"from": "gpt",
"value": "def foo(a, b):\n return a + b"
}
] |
[
{
"from": "human",
"value": "Generate a Python program that takes a list of strings as input and prints the strings in alphabetical order."
},
{
"from": "gpt",
"value": "strings = ['cat', 'dog', 'apple', 'banana']\n\nstrings.sort()\n\nfor string in strings:\n print(string)"
}
] |
[
{
"from": "human",
"value": "Build a Python program that extracts all email addresses from a given string."
},
{
"from": "gpt",
"value": "import re\n\ndef find_emails(text):\n regex = r\"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+)\"\n emails = re.findall(regex, text)\n return emai... |
[
{
"from": "human",
"value": "Create a Python code to generate a random string of length 8 made of uppercase letters and numbers."
},
{
"from": "gpt",
"value": "import string\nimport random\n\nlength = 8\nchars = string.ascii_uppercase + string.digits\npassword = ''.join(random.choice(chars) for ... |
[
{
"from": "human",
"value": "This code calculates the percent of transcripts mapping to rRNA. To use it, you need to supply two inputs: an HTseq_counts file and an original reference transcriptome aligned to. To produce tables with rRNA and MT counts for each sample, run the command \"./rRNA_MT_count.py --g... |
[
{
"from": "human",
"value": "Modify the following Python code to raise an exception if the input value is not an integer"
},
{
"from": "gpt",
"value": "def square_root(x):\n if not isinstance(x, int):\n raise TypeError('Input must be an integer')\n return x**0.5"
}
] |
[
{
"from": "human",
"value": "Create a program in Python that extracts titles of all YouTube videos from a URL."
},
{
"from": "gpt",
"value": "import requests\nimport re\n\nurl = \"https://www.youtube.com/user/Thexvid/videos\"\n\nr = requests.get(url)\ntitles = re.findall('<a href=\"/watch\\?v=([... |
[
{
"from": "human",
"value": "Write Python code to list the contents of a directory."
},
{
"from": "gpt",
"value": "# get the list of contents\nimport os\ndirectory_contents = os.listdir()\n\n# print the contents\nfor content in directory_contents:\n print(content)"
}
] |
[
{
"from": "human",
"value": "Create an AI-powered Python script to optimize any given code."
},
{
"from": "gpt",
"value": "# Import the required libraries\nfrom dataclasses import dataclass\n\n@dataclass\nclass Params:\n a: int\n b: int\n c: int\n\ndef get_result(params: Params) -> int:\n \"\"\"... |
[
{
"from": "human",
"value": "Create a Python function that takes two strings and returns true if the first string is a subsequence of the second."
},
{
"from": "gpt",
"value": "def is_subsequence(str1, str2):\n i = 0\n j = 0\n\n while(i < len(str1) and j < len(str2)):\n if str1[i... |
[
{
"from": "human",
"value": "Create a neural network class in Python to model a linear regression function."
},
{
"from": "gpt",
"value": "import numpy as np\nclass LinearRegressionModel:\n def __init__(self, input_dim, output_dim):\n ''' Initialises the weights and bias of the linear ... |
[
{
"from": "human",
"value": "Develop a ML model in Python for predicting the winning team of football matches. Use data from the past 5 years of the Premier League."
},
{
"from": "gpt",
"value": "import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.