text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Modify the following HTML code to add a new div element inside the existing div.
<div> Hello, world! </div>
<div> <div>New div element</div> Hello, world! </div>
null
Delete all duplicated characters in a string.
String: abcabcabc
abc
null
Create an R program to find the percentage of males and females in a given dataset.
Table Name: people
male_count <- nrow(people[people$Gender == "Male", ]) female_count <- nrow(people[people$Gender == "Female", ]) total <- nrow(people) male_percentage <- (male_count / total) * 100 female_percentage <- (female_count / total) * 100 print(paste0('Percentage of males:', male_percentage, '%')) print(paste0('Percentage of fe...
null
Create a REST API with Python and Flask for managing a movie database. This API should include endpoints to create a new movie record, retrieve a movie record, update a movie record, and delete a movie record.
Not applicable
from flask import Flask from flask_restful import Api, Resource, reqparse app = Flask(__name__) api = Api(app) movies = {} class Movie(Resource): def get(self, name): return movies[name] def post(self, name): parser = reqparse.RequestParser() parser.add_argument('year') parser.add_argument('rating') args ...
null
Create a simple calculator application in Python 3.
def calculator(): while True: print("Options:") print("Enter 'add' to add two numbers") print("Enter 'subtract' to subtract two numbers") print("Enter 'quit' to end the program") user_input = input(": ") if user_input == "quit": break elif user_in...
null
Edit the following code to return a Promise in the getMessage() function
function getMessage() { const fullName = getName(); // TODO: return a Promise }
function getMessage() { const fullName = getName(); // return a Promise return new Promise ((resolve, reject) => { resolve(fullName); }); }
[HI Wikipedia] शास्त्रीय संगीत भारतीय शास्त्रीय संगीत या मार्ग, भारतीय संगीत का अभिन्न अंग है। शास्त्रीय संगीत को ही ‘क्लासिकल म्यूजिक भी कहते हैं। शास्त्रीय गायन सुर-प्रधान होता है, शब्द-प्रधान नहीं। इसमें महत्व सुर का होता है (उसके चढ़ाव-उतार का, शब्द और अर्थ का नहीं)। इसको जहाँ शास्त्रीय संगीत-ध्वनि विषयक साधना के ...
null
null
null
null
Could you write a program that does linear regression with two variables in Python?
import numpy as np from sklearn.linear_model import LinearRegression # Create data x = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) # Create target y = np.dot(x, np.array([1, 2])) + 3 # Create a linear regression model model = LinearRegression() # Fit the model model.fit(x, y) # Make prediction x_test = np.array([3, 5...
null
Generate a Python program to perform matrix multiplication.
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [[7, 8, 9], [4, 5, 6], [1, 2, 3]]
def matrixMultiplication(A,B): return [[sum(a*b for a,b in zip(A_row,B_col)) for B_col in zip(*B)] for A_row in A] A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [[7, 8, 9], [4, 5, 6], [1, 2, 3]] C = matrixMultiplication(A,B) for i in range(len(C)): print(C[i])
[EN Wikipedia] List of New York Red Bulls seasons Since its foundation in 1996, the American soccer club New York Red Bulls has played in the Major League Soccer professional league. The team has won 3 Supporters' Shields. Key Key to competitions Major League Soccer (MLS) – The top-flight of soccer in the United State...
null
null
null
null
Create a CSS script to format the text in an h2 element.
h2 { font-size: 22px; font-weight: bold; font-family: Arial, sans-serif; line-height: 1.2; color: #333; text-align: center; }
[DE Wikipedia] Karakurt Als Karakurt werden bezeichnet: Folgende Orte in der Ukraine und der Türkei: Karakurt (Ukraine), Dorf in der ukrainischen Oblast Odessa, Rajon Bolhrad. Karakurt (Türkei), Ortschaft in der türkischen Provinz Kars, Bezirk Sarıkamış. Folgende Schiffsklasse: Die Karakurt-Klasse, Korvettenklasse der...
null
null
null
null
Create a HTML page to display a table in the following format.
<!DOCTYPE html> <html> <head> <title>Table</title> </head> <body> <table> <tr> <th>Name</th> <th>Address</th> <th>Phone</th> </tr> <tr> <td>John</td> <td>123 Fake Street</td> <td>123-456-7890</td> </tr> <tr> <td>Jane</td> <td>456 Real Street</td> <td>098-765-4321</td> </tr> </table> </body> </html>
null
Does the following code fragment pass the test?
def my_func(a, b): return a + b def test_my_func(): assert(my_func(2, 3) == 5)
Yes, the code fragment passes the test since the function "my_func" successfully returns the value 5 when given arguments a=2 and b=3.
null
Write a python program to print the following pattern.
n = 5
def pattern(n): # Outer loop for i in range(0, n): # Inner loop to handle number of columns # values changing according to outer loop for j in range(0, i+1): # Printing stars print("* ",end="") # Ending line after each row print("\r") # Driver C...
null
Write Python code to find the sum of the factorial of a given number.
3
def find_sum_factorial_number(n): sum_num = 0 for i in range(1, n + 1): sum_num += math.factorial(i) return sum_num if __name__ == '__main__': n = int(input('Input a number: ')) print(find_sum_factorial_number(n))
null
Write a JavaScript code to print the characters of a string one by one in an alert message.
str = "Hello World!"
for (let i = 0; i < str.length; i++) { alert(str.charAt(i)); }
[CS Wikipedia] Anthony Quinn Anthony Quinn, vlastním jménem Antonio Rudolfo Oaxaca Quinn, (21. dubna 1915, Chihuahua, Mexiko – 3. června 2001, Boston, USA) byl mexicko-americký herec, malíř a scenárista, dvojnásobný držitel ceny Americké filmové akademie Oscar. Život Narodil se irskému otci a mexické matce aztécké nár...
null
null
null
[EN Wikipedia] Le Fort III osteotomy The Le Fort III Osteotomy for oral and maxillofacial surgery, is used to correct generalised growth failure of the midface involving the upper jaw nose and cheek bones (zygomas). The surgical approach and post operative management is similar as for the Le Fort II procedure. Brow li...
null
null
null
null
Write a Python script to send an email using the smtplib module.
import smtplib sender = 'from@example.com' recipients = ['to@example.com'] message = """Subject: Test Email This is a test email message. """ with smtplib.SMTP('localhost') as server: server.sendmail(sender, recipients, message)
null
Suggest a way to create a linked list in python.
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if not self.head: self.head = new_node return current = self.head while current.next: current = current.next current.next = new_node
null
Write a code to initialize an array with 10 elements of value 0.
int[] array = new int[10]; Arrays.fill(array, 0);
[EN Wikipedia] Ryton River The Ryton River is a river of the Canterbury region of New Zealand's South Island. It flows southwest down a long valley within the Craigieburn Range to reach the northeastern shore of Lake Coleridge. See also List of rivers of New Zealand References Rivers of Canterbury, New Zealand Rivers ...
null
null
null
null
Write a python program to convert a given hexadecimal to binary.
Hexadecimal: 0x56
def hex_to_binary(h): return bin(int(h, 16)) print(hex_to_binary('0x56'))
null
Generate a Python script that outputs the first ten perfect squares from 1 to 100.
for i in range(1, 11): print(str(i**2))
null
Request the average temperature of the city 'Boston' from the Weather API.
import requests def get_average_temperature(city): api_url = 'http://api.openweathermap.org/data/2.5/weather?q='+city+'&APPID=your_api_key' response = requests.get(api_url) data = response.json() temp = data['main']['temp'] return temp - 273.15
null
Design an algorithm to find the two numbers in an array that have the largest sum.
[1,3,4,6,7]
# Finds two numbers in an array that have the largest sum def getMaxSum(arr): # Initialize the sum to the maximum possible value maxSum = -float('inf') # Iterate over all elements of the array for i in range(len(arr)): for j in range(i+1, len(arr)): # Compare the current sum to the maximum sum maxSum = max(maxSum, arr[...
[HI Wikipedia] विश्व व्यापार संगठन विश्व व्यापार संगठन (WTO) एक अन्तर्राष्ट्रीय संगठन है, जिसका ध्येय अन्तर्राष्ट्रीय व्यापार का उदारीकरण है। यह व्यापार से सम्बन्धित नियमों को निर्धारित और प्रतिष्ठित करने के लिए विकसित देशों की पहल पर आरम्भ किया गया था। इसने आधिकारिक रूप से 1 जनवरी 1995 को, 1994 के मराकेश सहमति के अनु...
null
null
null
null
Create an array of the squared values of all elements of the given array.
arr = [2, 3, 6, 8]
def square_arr(arr): return [x**2 for x in arr]
[EN Wikipedia] Yanislav Gerchev Yanislav Gerchev () (born 4 October 1989) is a Bulgarian judoka. He competed at the 2016 Summer Olympics in the men's 60 kg event, in which he was eliminated in the third round by Amiran Papinashvili. References External links 1989 births Living people Bulgarian male judoka Olympic judo...
null
null
null
null
Write a JavaScript to read the following JSON object and print its "name" key value
data = { "name": "John", "age": "33", "city": "New York" }
console.log(data.name);
null
Design a Python program to convert all the characters of a string to upper case.
This is a sample sentence.
def to_upper(s): return s.upper() result = to_upper("This is a sample sentence.") print(result)
null
Design a function to remove duplicates from an array
def remove_duplicates(arr): # Stores the unique elements unique = [] # Iterate through the array for elem in arr: # If the element is not already in the unique list if elem not in unique: # Add it to the unique list unique.append(elem) # Return the array without duplicates return unique
null
Assemble a Python program to measure similarity
Compute the similarity between two strings.
def compute_similarity(s1, s2): len1 = len(s1) len2 = len(s2) max_len = max(len1, len2) count = 0 for i in range(max_len): if i >= len1 or i >= len2: break if s1[i] == s2[i]: count += 1 return count / max_len
[DE Wikipedia] Admiralty Island (Nunavut) Admiralty Island (engl. für „Admiralitäts-Insel“, Inuktitut Qikiqtagafaaluk) ist eine unbewohnte, irregulär geformte arktische Insel in der Kitikmeot-Region des kanadischen Territoriums Nunavut. Sie liegt in der Victoria Strait, südlich der Collinson Peninsula von Victoria Isl...
null
null
null
null
Create a method to checkout the content of dictionary.
def check_dict(dictionary): for key in dictionary: print(key + ": " + str(dictionary[key]))
null
Create a Python function that takes a list of numbers as an argument and sorts it in descending order using quick sort algorithm.
[7, 5, 2, 4, 2, 9, 3, 8]
def quickSort(nums): if len(nums) <= 1: return nums pivot = nums[len(nums) // 2] left = [x for x in nums if x < pivot] middle = [x for x in nums if x == pivot] right = [x for x in nums if x > pivot] return quickSort(right) + middle + quickSort(left) if __name__ == "__main__": number...
null
Create a Python class to represent an employee record with fields name and salary.
class Employee: def __init__(self, name, salary): self.name = name self.salary = salary def get_name(self): return self.name def get_salary(self): return self.salary
null
Write a function in JavaScript to remove all vowels from an input string.
function removeVowels(str) { return str.replace(/[aeiou]/gi, ''); }
null
Print all the elements in the following array in descending order.
[4, 2, 6, 8, 5, 9, 1]
9 8 6 5 4 2 1
null
Create a web scraper in Python for scraping articles from a specific website. The web scraper should save the extracted text, title, and date.
Not applicable
import requests from bs4 import BeautifulSoup url = 'https://example.com/articles.html' page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') # get the title title = soup.find("h1", class_="article-title") title_text = title.text.strip() # get the date date = soup.find("div", class_="article-dat...
null
Create a for loop to iterate through a given list and print the list elements.
list_items = [2, 3, 4, 5, 6, 7, 8]
""" Create a for loop to iterate through a given list and print the list elements """ list_items = [2, 3, 4, 5, 6, 7, 8] for item in list_items: print(item)
null
Create a data structure in Python to store employee name, salary and designation.
emp_dict = { 'name':[], 'salary':[], 'designation':[] };
null
Write a Python program to generate a randomly sized array with random numbers between 0 and 1000.
Not applicable
import random n = random.randint(1, 10) array = [random.randint(0, 1000) for i in range(n)] print(array)
null
Develop a python script for converting an infix expression to postfix notation.
def infix_to_postfix(infix_expr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = [] postfixList = [] tokenList = infix_expr.split() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": ...
[DE Wikipedia] William Mahaney William (Bill) C. Mahaney (* 17. Mai 1941) ist ein US-amerikanischer Geograph und Geologe. William Mahaney lehrte als Dozent am Atkinson College der York University in Toronto (Kanada). Er ist Autor und Herausgeber zahlreicher Fachbücher und Aufsätze. Außerdem schreibt er Novellen und Fi...
null
null
null
[DE Wikipedia] Amt Uecker-Randow-Tal Im Amt Uecker-Randow-Tal sind 13 Gemeinden zur Erledigung ihrer Verwaltungsgeschäfte zusammengeschlossen. Das Amt liegt im Südosten des Bundeslandes Mecklenburg-Vorpommern (Deutschland) und im Süden des Landkreises Vorpommern-Greifswald. Im Süden grenzt das Amt an das Bundesland Br...
null
null
null
null
Create a web scraper in Python to extract all links from a website.
import requests from bs4 import BeautifulSoup def get_all_links(url): # make a GET request to fetch the raw HTML content html_content = requests.get(url).text # parse the html content soup = BeautifulSoup(html_content, "lxml") # extract all links from web page links = soup.find_all("a") return ...
[DE Wikipedia] Hotel Post Sargans Das Hotel Post Sargans ist ein Hotel in Sargans im Schweizer Kanton St. Gallen. Das Hotel wechselte im Lauf seiner Geschichte mehrmals den Namen: von „Schwefelbad“ und „Gast- und Badhaus zum Rössli“ über „Gasthaus zum Rössli“ Anfang des 19. Jahrhunderts, „Gasthaus zum Schwefelbad“ ab ...
null
null
null
[DE Wikipedia] Franz-Heinrich Philipp Franz-Heinrich Philipp (* 28. Juni 1921 in Königsberg; 3. März 1984 in Marburg) war ein deutscher Kirchenhistoriker und Bibliothekar. Leben Franz-Heinrich Philipp studierte nach Arbeits- und Kriegsdienst sowie Gefangenschaft (1938 bis 1950) Evangelische Theologie, Religionswissens...
null
null
null
[DE Wikipedia] Anneliese Bretschneider Anneliese Bretschneider (* 24. August 1898 in Glauchau; † 20. November 1984 in Potsdam) war eine Sprachwissenschaftlerin, die sich besonders mit der Dialektologie des Märkischen beschäftigt hat. Sie war die Begründerin des Brandenburg-Berlinischen Wörterbuchs. Leben und Wirken An...
null
null
null
null
Utilize a regular expression to match all words that begin with 'b' in a given text.
text = "The quick brown fox jumps over the lazy dog."
import re text = "The quick brown fox jumps over the lazy dog." word_list = re.findall(r"\b[bB]\w+", text) print(word_list) # output: ['brown', 'fox', 'b jumps', 'b lazy']
null
Using Java, create a program to find the maximum sum of a sub-array within a given array.
// Java Code public class MaximumSubArraySum { public static int maxSubArraySum(int[] nums) { int maxSum = Integer.MIN_VALUE; int currentSum = 0; for (int num : nums) { currentSum += num; if (currentSum > maxSum) maxSum = currentSum; if (currentSum < 0) currentSum = 0; } return maxSum; } public static void main(String[...
[CS Wikipedia] Vůz WRm812, 813 ČD {{DISPLAYTITLE:Vůz WRm812, 813 ČD}} Vozy WRm812 a WRm813, obě řady shodně číslovány v intervalu 51 54 88-81, byly jídelní vozy provozované Českými drahami. Byly vyrobeny v roce 1978 ve vagónce VEB Waggonbau Bautzen. Technický popis Byly to první vozy typu UIC-Z délky 26 400 mm u tehde...
null
null
null
null
Use the Twitter API to develop a sentiment analysis program in Python.
Not applicable
import tweepy import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer #Twitter credentials consumer_key = 'your_key' consumer_secret = 'your_secret' access_token = 'your_token' access_token_secret = 'your_secret' #Create OAuth authentication auth = tweepy.OAuthHandler(consumer_key, consumer_secret) au...
null
Write a script in PHP for converting a string to lowercase.
<?php $string = "STRING"; $string = strtolower($string); echo($string); // output: string ?>
null
Generate a python program to collect all elements of a given list that are of even length.
list = ["a", "bb", "ccc", "dddd", "eee"]
def even_length_elements(my_list): even_length_list = list() for elem in my_list: if (len(elem) % 2 == 0): even_length_list.append(elem) return even_length_list
[DE Wikipedia] Eastern (Begriffsklärung) Eastern steht für: Eastern, ein Filmgenre Eastern Air Lines, ehemalige US-amerikanische Fluggesellschaft von 1926 bis 1991 Eastern Air Lines (2011), kurzlebige US-amerikanische Fluggesellschaft Eastern Airways, britische Regionalfluggesellschaft Eastern Standard Time, eine Zeit...
null
null
null
null
Write a Python code to implement a list containing at least three dictionaries.
list_of_dicts = [ { "name": "John", "age": 32, "country": "USA" }, { "name": "Peter", "age": 28, "country": "Australia" }, { "name": "David", "age": 30, "country": "Canada" } ]
[DE Wikipedia] Gmina Grodziec Die Gmina Grodziec ist eine Landgemeinde im Powiat Koniński der Woiwodschaft Großpolen in Polen mit etwa mit 5100 Einwohnern. Ihr Sitz ist das gleichnamige Dorf mit 1700 Einwohnern. Geographie Die Gemeinde liegt im Osten den Woiwodschaft, zwanzig Kilometer südlich der Kreisstadt Konin und...
null
null
null
[CS Wikipedia] Anna Rossinelli Anna Rossinelli (* 20. dubna 1987 Basilej) je švýcarská zpěvačka a skladatelka. Spolu s Manuelem Meiselem a Georgem Dillierem vystupuje v pop-soulovém triu. To působí pod jejím jménem.Reprezentovala Švýcarsko na Eurovision Song Contest 2011 v Düsseldorfu, kde jako tamější první zástupce ...
null
null
null
null
Given two equations, predict the range of the output variable.
Equation 1: Y = X + 2 Equation 2: Y = 2X
The range of the output variable is [-2, ∞).
null
Write a Visual Basic Script to add two numbers
Function add(a As Integer, b As Integer) add = a + b End Function MsgBox(add(5, 2))
null
Write a Python function to sort the given array of dictionaries by key value.
arr = [{'name': 'Jose', 'age': 32}, {'name': 'Ravi', 'age': 23}, {'name': 'Paul', 'age': 26}]
def sort_by_key(arr): return sorted(arr, key=lambda i: i['name'])
null
Write a function in Python to convert JSON data into a Python dictionary.
json_data = '{"name":"John","age":30,"city":"New York"}'
import json def json_to_dict(json_data): return json.loads(json_data) data = json_to_dict(json_data) print(data)
[DE Wikipedia] Glatte Glatte ist der Familienname folgender Personen: Adolf Glatte (1866–1920), deutscher Landschafts- und Porträtmaler Jessica Glatte (* 1973), deutsche Operettensängerin (Sopran) Reinhard Glatte (* 1938), deutscher Bauingenieur und Hochschullehrer Siehe auch: Klatte Kladde
null
null
null
null
Create a program in Python that removes duplicates from a given array.
[1,1,2,3,4,5,5,5]
def remove_duplicates(array): new_array = [] for element in array: if element not in new_array: new_array.append(element) return new_array
null
Given a string and an integer, write a program to compare the string with the integer and return the longer string.
my_string = "Hello" my_int = 1
def compare_str_int(str, num): if len(str) > num: return str else: return "{i} is greater than {s}".format(i=num, s=str) my_string = "Hello" my_int = 1 print(compare_str_int(my_string, my_int))
null
Construct a for loop to print the integer from 0 to 50.
for i in range(51): print(i)
null
Compress the following string using a Huffman algorithm.
"aaaaaaaaabccddddee"
import heapq def huffman_encode(string): freq = {} for c in string: freq[c] = freq.get(c, 0) + 1 heap = [[weight, [char, ""]] for char, weight in freq.items()] heapq.heapify(heap) while len(heap) > 1: low = heapq.heappop(heap) high = heapq.heappop(heap) for pair in low[1:]: pair[1] = '0' + pair[1] for pair in high[1:]:...
[DE Wikipedia] Harzelt Harzelt ist ein Ortsteil der Gemeinde Gangelt im Kreis Heinsberg in Nordrhein-Westfalen. Geographie Lage Harzelt liegt ca. 4 km nördlich von Gangelt an der Kreisstraße 3. In der Nähe des Ortes befindet sich am Saeffeler Bach das Naturschutzgebiet Höngener- und Saeffeler Bruch. Der Ort Harzelt gr...
null
null
null
null
Create a Python script which connects to a MySQL database, runs a query and outputs the results in JSON format.
Database name: test Query: SELECT * FROM users
import mysql.connector import json db = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="test" ) cursor = db.cursor() sql = "SELECT * FROM users" cursor.execute(sql) results = cursor.fetchall() json_data = [] for result in results: json_data.append(result) ...
null
Generate a python function to convert an array to a dictionary
['a', 1, 'b', 2, 'c', 3]
def array_to_dict(lst): output = {} for i in range(0, len(lst), 2): output[lst[i]] = lst[i+1] return output # main program my_list = ['a', 1, 'b', 2, 'c', 3] result = array_to_dict(my_list) print(result)
[CS Wikipedia] Gustáv Plavec Gustáv Plavec (4. dubna 1904 – 5. listopadu 1971) byl slovenský evangelický farář, spisovatel a publicista. Byl redaktorem časopisu evangelické mládeže Prameň. Slovenští protestantští duchovní Slovenští spisovatelé Narození v roce 1904 Úmrtí v roce 1971 Muži
null
null
null
null
Create some code that iterates through a list and prints out each element.
my_list = [1, 4, 6, 8]
for item in my_list: print(item)
null
Fix the following JavaScript bug.
function helloWorld() { console.log('Hello' + 'World')
function helloWorld() { console.log('Hello' + ' ' + 'World')
null
Code a function in Python to generate random numbers within a given range.
import random def random_num_gen(start, end): return random.randint(start, end)
[HI Wikipedia] भीष्म साहनी रावलपिंडी पाकिस्तान में जन्मे भीष्म साहनी (८ अगस्त १९१५- ११ जुलाई २००३) आधुनिक हिन्दी साहित्य के प्रमुख स्तंभों में से थे। १९३७ में लाहौर गवर्नमेन्ट कॉलेज, लाहौर से अंग्रेजी साहित्य में एम ए करने के बाद साहनी ने १९५८ में पंजाब विश्वविद्यालय से पीएचडी की उपाधि हासिल की। भारत पाकिस्तान विभाजन ...
null
null
null
[HI Wikipedia] परवेज़ मुशर्रफ़ परवेज़ मुशर्रफ़ (उर्दू: پرويز مشرف; जन्म अगस्त 11, 1943) पाकिस्तान के राष्ट्रपति और सेना प्रमुख रह चुके हैं। इन्होंने साल 1999 में नवाज़ शरीफ की लोकतान्त्रिक सरकार का तख्ता पलट कर पाकिस्तान की बागडोर संभाली और 20 जून, 2001 से 18 अगस्त 2008 तक पाकिस्तान के राष्ट्रपति रहे। 5 फरवरी 2023 को ...
null
null
null
null
Improve the following code in order to create a balanced binary search tree.
Node insert(int x, Node root) { if (root == NULL) { root = new Node; root->key = x; root->left = root->right = NULL; } else if (x < root->key) root->left = insert(x, root->left); else root->right = insert(x, root->right); return root; }
Node insert(int x, Node root) { if (root == NULL) { root = new Node; root->key = x; root->left = root->right = NULL; } else if (x < root->key) root->left = insert(x, root->left); else root->right = insert(x, root->right); root = balance(root); return root; } Node balance(Node root) { int left_height = height(root->left...
null
Create an AI chatbot in Python to answer simple user questions about a specific topic.
# import libraries import random import nltk from nltk.corpus import wordnet # define a function to find the synonym of a given word def get_synonym(word): synonyms = set() for syn in wordnet.synsets(word): for l in syn.lemmas(): synonyms.add(l.name()) if word in synonyms: syn...
null
Write a function to convert the given list of integers into a dictionary of lists.
my_list = [1, 2, 3, 4]
def list_to_dict(lst): my_dict = {} for i in lst: my_dict[str(i)] = [i] return my_dict if __name__ == '__main__': my_list = [1, 2, 3, 4] print(list_to_dict(my_list))
null
Create a function in Python that takes an array of integers as input, checks if the array is sorted, and, if not, sorts it.
[3, 1, 4, 2, 5]
def is_sorted(arr): sorted_arr = sorted(arr) if arr == sorted_arr: return True else: arr.sort() return arr
null
Generate an algorithm in Python that can take in a list of integers and sort them in ascending order.
Example list: [4, 9, 1, 6, 5]
def sort_ascending(nums): n = len(nums) for i in range(n): for j in range(0, n-i-1): if nums[j] > nums[j+1] : nums[j], nums[j+1] = nums[j+1], nums[j] return nums
[HI Wikipedia] एल्यूमीनियम पिघलने भट्ठी एल्यूमिनियम पिघलने फर्नेस एल्यूमीनियम भट्ठी के लिए विभिन्न औद्योगिक उद्देश्यों की सेवा करने के लिए बनाया गया है। यह अल जो कई अन्य उपकरणों से बेहतर गर्मी की गर्मी तत्व का वितरण और अब जीवन के लिए समर्थन कर रहे हैं जैसे विभिन्न तत्वों के होते हैं। इन एल्यूमिनियम पिघलने भट्ठी मिश्र ...
null
null
null
null
Construct a Python code that accepts a string as an input and returns the total number of vowels in the string
def count_vowels(string): vowels = "aeiou" count = 0 for s in string: if s.lower() in vowels: count += 1 return count
null
Print the character at the specified index in a given string.
s = "Hello World!" index = 5
s = "Hello World!" index = 5 print("Character at index", index, "is:", s[index]) Output: Character at index 5 is: W
null
Formulate a statement using Python that will return the value 'True' when the user's age is equal to 21.
userage = 21
if userage == 21: print(True)
null
Write a Python code that generates an array of 20 random integers between 1 and 10.
import random random_numbers = [random.randint(1, 10) for i in range(20)]
null
Write a python code to perform the task of bubble sorting in a list.
arr = [1, 10, 5, 4, 8]
def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] bubble_sort(arr)
[EN Wikipedia] 1837 in Denmark Events from the year 1837 in Denmark. Incumbents Monarch – Frederick VI Prime minister – Otto Joachim Events 7 April - C.A. Reitzel publishes Hans Christian Andersen's Fairy Tales Told for Children. First Collection. Third Booklet (Eventyr, fortalte for Børn. Første Samling. Tredie Hefte...
null
null
null
null
Design a webpage with a given template.
Template: Pink and Purple with three-column layout
<html> <head> <title>Pink and Purple Layout</title> <style> body { background-color: pink; } #container { display: flex; } #container > div { flex: 1; background-color: purple; } </style> </head> <body> <div id="container"> <div></div> <div></div> <div></div> </div> </body> </html>
null
Generate a Python code to create a class which creates an empty dictionary with the given keys.
"name, age"
class EmptyDictionary: def __init__(self, keys): self.keys = [k.strip() for k in keys.split(",")] self.dictionary = {k: None for k in self.keys} def get_dictionary(self): return self.dictionary
null
Write a JavaScript function that takes two numbers and a mathematical operator as parameters and returns the result of the specified operation.
x = 6, y = 3, operator = '*'
function calculate(x, operator, y) { switch (operator) { case '+': return x + y; case '-': return x - y; case '*': return x * y; case '/': return x / y; case '%': return x % y; default: return NaN; } } let result = calculate(6, '*', 3); console.log(result); // 18
null
Create a class called "Person" using Python, with attributes "name", "age" and "country".
class Person: def __init__(self, name, age, country): self.name = name self.age = age self.country = country def get_name(self): return self.name def get_age(self): return self.age def get_country(self): return self.country
null
Transform this code fragment to use the appropriate data structure.
word = "apple" for i in range(len(word)): print(word[i])
word = "apple" for letter in word: print(letter)
null
Write a code snippet in Python to print Pascal’s triangle for a given value of n.
4
def printPascalTriangle(n) : for line in range(1, n + 1) : C = 1 for i in range(1, line + 1) : print(C, end = "") C = int(C * (line - i) / i); print("") n = 4 printPascalTriangle(n)
null
Express the following SQL query in a pythonic way.
SELECT id,name FROM users WHERE gender = 'M' AND age >= 20
def select_users_male_age_above_20(users): output = [] for user in users: if user['gender'] == 'M' and user['age'] >= 20: output.append({'id':user['id'], 'name':user['name']}) return output
null
Create a Python program to interpret a user command from a given set of instructions and execute it.
Taking a break
command = input("Please enter your command: ") if command == "Taking a break": print("Taking a five minute break") # code to execute the taking a break command else: print("Invalid command")
null
Create a Migration Script in Node.js for creating a table for customers.
customer_id, first_name, last_name, email
const { Client } = require('pg'); const client = new Client({ connectionString: process.env.DATABASE_URL }); async function createCustomerTable() { await client.connect(); const query = ` CREATE TABLE customers ( customer_id SERIAL PRIMARY KEY, first_name VARCHAR(255) NOT NULL, last_name VARCHAR(255) NOT NULL, email VA...