text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Read an array of integers and sort it in increasing order.
arr = [3, 1, 4, 5, 2]
def sortArray(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] sortArray(arr) print(arr) # Output: [1, 2, 3, 4, 5]
[HI Wikipedia] रतनजी टाटा सर रतनजी टाटा (२० जनवरी १८७१ ई. - ५ सितंबर १९१८ ई.) भारत के सुविख्यात पारसी उद्योगपति और जनसेवी जमशेदजी नासरवान जी टाटा के पुत्र। उन्होने भारत में टाटा समूह के विकास में एक निर्णायक भूमिका निभाई थी। परिचय जन्म २० जनवरी १८७१ ई. को बंबई में हुआ था। बंबई के सेंट जेवियर कालेज में अध्ययन कर पिता क...
null
null
null
[HI Wikipedia] उपसौर और अपसौर उपसौर और अपसौर (Perihelion and Aphelion), किसी ग्रह, क्षुद्रग्रह या धूमकेतु की अपनी कक्षा पर सूर्य से क्रमशः न्यूनतम और अधिकतम दूरी है। सौरमंडल में ग्रह सूर्य की परिक्रमा करते हैं, कुछ ग्रहों की कक्षाएं करीब-करीब पूर्ण वृत्ताकार होती है, लेकिन कुछ की नहीं।| कुछ कक्षाओं के आकार अंडाकार जैस...
null
null
null
null
Create a program in Python that takes a text and tokenizes it into words.
text = "This is an example of tokenization"
import re #Replace special characters with space text = re.sub(r'[^\w\s]',' ',text) #Split text tokens = text.split() print(tokens) #Output: ['This', 'is', 'an', 'example', 'of', 'tokenization']
[DE Wikipedia] Coultas Coultas ist der Familienname folgender Personen: Brenda Coultas (* 1958), US-amerikanische Schriftstellerin Rowan Coultas (* 1997), britischer Snowboarder
null
null
null
[EN Wikipedia] Z-TER (Z 21500) The Z-TER (Z 21500) is a French model of electric multiple unit regional passenger train, manufactured by Alstom and Bombardier Transportation, and operated by SNCF. They are used on regional links, and can be coupled with another Z-TER. They are derived from the French diesel passenger ...
null
null
null
null
Create a Python script to build a machine learning model to predict MPG from an auto dataset.
# Import Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score # Read in the auto dataset df = pd.read_csv('auto.csv') # Get the features and labels X = df.drop(columns='mpg') y = df['mpg'] # Split into ...
null
Using a given dataset, create a visualization in Python to identify how many of each type of fruit has been sold.
The dataset has 24 observations and three variables (fruit type, quantity and price). Fruit Quantity Price Banana 20 5 Orange 30 3 Apple 50 4 Pear 10 2 ... ... ...
import matplotlib.pyplot as plt import pandas as pd # Read data data = pd.read_csv("fruits.csv") # Get fruit types types = data['Fruit'].unique() # Calculate quantity for each type quantity = [sum(data['Quantity'][data['Fruit'] == t]) for t in types] # Plot the bar chart plt.bar(types, quantity) # Add title, x and...
null
Create a Python program that reads in two strings and outputs the longest common substring.
str1 = "GeeksforGeeks" str2 = "Practice"
def longest_common_substring(str1, str2): if len(str1) == 0 or len(str2) == 0: return "" matrix = [[0 for _ in range(0, len(str2)+1)] for _ in range(0, len(str1)+1)] longest_string = "" for i in range(1, len(str1)+1): for j in range(1, len(str2)+1): if str1[i-1] == str2[j-1]:...
null
Generate code to find the sum of all numbers in an array using Python.
def sum_of_array(arr): # Initialize result res = 0 # Iterate through all elements # and add them to result for i in range(0, len(arr)): res = res + arr[i] # return final result return res
null
Create an artificial neural network in Python using TensorFlow to predict stock prices.
Not applicable
import tensorflow as tf # Create a Neural Network model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(4, input_shape=(len(X[0]),), activation='relu')) model.add(tf.keras.layers.Dense(1)) # Compile model model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy']) # Train model model....
null
Write a Python program to find the largest three numbers in a list.
1, 6, 3, 8, 7, 4
my_list = [1, 6, 3, 8, 7, 4] largest_three = sorted(my_list)[-3:] print(largest_three)
[HI Wikipedia] वुद्ध सायमी वुद्ध सायमी नेपाली भाषा के नेपाली कवि हैं। इनका जन्म विक्रम संवत 2001 में झोंछे काठमाण्डू में हुआ। इनका एक कविता संग्रह 'मेरो वर्तमान' प्रकाशित है। ये द्विमासिक पत्रिका 'सिड' के सह संपादक हैं। सन्दर्भ नेपाली साहित्यकार 2001 में जन्मे लोग जीवित लोग
null
null
null
[DE Wikipedia] Filadelfia Oslo Filadelfiakirken Oslo ist eine christliche Gemeinde (Menigheten) der Pfingstbewegung in Norwegen. Sie ist die größte Pfingstkirche des Landes und bietet umfangreiche Angebote im In- und Ausland. Geschichte Die Filadelfia-Gemeinde wurde von Thomas Ball Barratt gegründet. Sie war 1916 die ...
null
null
null
[CS Wikipedia] Stock, Aitken & Waterman Stock, Aitken & Waterman, zkráceně SAW je britské skladatelské a produkční trio skládající se z Mike Stocka, Matta Aitkena a Pete Watermana. Jejich doba slávy nastávala v pozdějších osmdesátých letech. Dohromady prodali 40 milion nahrávek a měli víc než 100 hitů britské Top 40. ...
null
null
null
null
Write a function in Python to convert a given decimal number into its binary form.
def decimal_to_binary(num): binary = [] while num > 0: binary.append(num%2) num //= 2 binary.reverse() return binary
[HI Wikipedia] मधुबनी मधुबनी भारत के बिहार प्रान्त में दरभंगा प्रमंडल अंतर्गत एक जिला है। दरभंगा एवं मधुबनी को मिथिला संस्कृति का द्विध्रुव माना जाता है। मैथिली यहाँ की प्रमुख भाषा है। विश्वप्रसिद्ध मिथिला पेंटिंग एवं मखाना के पैदावार की वजह से मधुबनी को विश्वभर में जाना जाता है। इस जिला का गठन 1972 में दरभंगा जिले के...
null
null
null
[HI Wikipedia] मुहम्मद मुहम्मद 570 ई - 8 जून 632 ई) इस्लाम के संस्थापक थें। इस्लामिक मान्यता के अनुसार, वह एक पैगम्बर और ईश्वर के संदेशवाहक थे, जिन्हें इस्लाम के पैग़म्बर भी कहते हैं, जो पहले आदम , इब्राहीम , मूसा ईसा (येशू) और अन्य पैगम्बर द्वारा प्रचारित एकेश्वरवादी शिक्षाओं को प्रस्तुत करने और पुष्टि करने के लिए भे...
null
null
null
[EN Wikipedia] Aztlan Underground Aztlan Underground is a band from Los Angeles, California that combines Hip-Hop, Punk Rock, Jazz, and electronic music with Chicano and Native American themes, and indigenous instrumentation. They are often cited as progenitors of Chicano rap. Background The band traces its roots to t...
null
null
null
null
Using the provided data, generate a linear regression model using Python.
x | y ---------------- 1 | 1 2 | 2 3 | 4 4 | 8 5 | 16
import numpy as np def generate_model(data): x = np.array([data[0], data[1], data[2], data[3], data[4]]) y = np.array([data[5], data[6], data[7], data[8], data[9]]) A = np.vstack([x, np.ones(len(x))]).T m, c = np.linalg.lstsq(A, y)[0] return m, c x = [1, 2, 3, 4, 5] y = [1, 2, 4, 8, 16] m, c = gen...
null
Add a function to this Python program to maximize the accuracy of the output
def classify_numbers(numbers): if len(numbers) == 0: return 0 total = 0 for n in numbers: total += n if total / len(numbers) > 5: return 1 else: return 0
def classify_numbers(numbers): if len(numbers) == 0: return 0 total = 0 for n in numbers: total += n if total / len(numbers) > 5: return 1 else: return 0 def check_input(numbers): for n in numbers: if not isinstance(n, int): raise ValueError("I...
null
Create a regular expression to validate a URL string.
# Regular expression to validate a URL string ^(http:\/\/|https:\/\/|ftp:\/\/)?(www\.)?([a-zA-Z0-9]+(-?[a-zA-Z0-9])*\.)+[\w]{2,5}(\/\S*)?$
null
Write a JavaScript program to replace all the vowels in a given string with '*'.
function replaceVowels(str) { return str.replace(/[aeiou]/gi, '*'); }
[HI Wikipedia] क़ल्यूबीया मुहाफ़ज़ाह क़ल्यूबीया मुहाफ़ज़ाह (अरबी: , अंग्रेज़ी: Qalyubia) मिस्र का एक मुहाफ़ज़ाह (उच्च-स्तरीय प्रशासनिक विभाग) है। यह राष्ट्रीय राजधानी क़ाहिरा से उत्तर में मिस्र के उत्तरी भाग में नील नदी के नदीमुख (डॅल्टा) क्षेत्र में स्थित है। इसके कुछ हिस्से क़ाहिरा के बाहरी मोहल्लों से मिले-जुले हैं...
null
null
null
[EN Wikipedia] Port Olímpic The Port Olímpic () is a marina located in Barcelona, Catalonia. Located east of the Port of Barcelona, it hosted the sailing events for the 1992 Summer Olympics. It will also be the main venue for the 2024 Americas Cup. The venue was opened in 1991. Gallery References 1992 Summer Olympics ...
null
null
null
null
Write a jQuery script to display a popup box when a web page is loaded.
$(document).ready(function(){ alert("Popup box!"); });
null
Write a Python program that takes a list of strings as input and returns a string containing all the strings joined together in alphabetical order.
['apple', 'banana', 'orange']
def alphabetize_list(arr): arr.sort() return ' '.join(arr) data = ['apple', 'banana', 'orange'] result = alphabetize_list(data) print(result)
null
Write a SQL query to join two tables on a specified conditions.
Table 1: id name age 1 a 15 2 b 18 3 c 20 Table 2: id class marks 1 10 80 2 10 75 3 11 70
SELECT table1.id, table1.name, table1.age, table2.class, table2.marks FROM table1 INNER JOIN table2 ON table1.id = table2.id WHERE table1.age > 18;
null
Write a function to check whether a number is a prime number in JavaScript.
let num = 7;
function isPrime(num) { // Edge cases: if (num <= 1) return false; if (num === 2) return true; if (num % 2 === 0) return false; for (let i=3; i<=Math.sqrt(num); i+=2) { if (num % i === 0) return false; } return true; }
null
Find the probability of a random variable following a normal distribution with a mean of 10 and a standard deviation of 2.
x = 12
# Find the probability of a random variable following a normal distribution with a mean of 10 and a standard deviation of 2. from scipy.stats import norm prob = norm.pdf(x, 10, 2) print(prob) # Output: 0.17603266338214976
[EN Wikipedia] 2016–17 Pepperdine Waves men's basketball team The 2016–17 Pepperdine Waves men's basketball team represented Pepperdine University during the 2016–17 NCAA Division I men's basketball season. This was head coach Marty Wilson's sixth full season at Pepperdine. The Waves played their home games at the Fir...
null
null
null
null
Create a SQL query to find the average length of time for all purchases.
Table structure: Purchase (Customer_ID, Purchase_Date, Purchase_Length)
SELECT AVG(Purchase_Length) as Average_Purchase_Length FROM Purchase;
null
Create a simple Python program that prints the characters of a string in reverse order.
String to be printed: "Hello"
string = "Hello" revString = "" for i in range(len(string)-1,-1,-1): revString = revString + string[i] print(revString)
[HI Wikipedia] जनकला जनकला (public art) किसी भी माध्यम में रची हुई कला की उन कृतियों को बोलते हैं जिन्हें ऐसे खुले वातावरण में प्रदर्शित करने की नियत से बनाया गया हो जहाँ जन-साधारण का बहुत आना-जाना रहे, मसलन किसी नगर का कोई मार्ग, चौराहा या चौक। इसमें मूर्तिकला व ग्रफ़ीटी जैसी कलाएँ शामिल हैं। अक्सर संग्रहालय में रखी ...
null
null
null
null
Print out the number of items in the following list.
my_list = [1, 2, 3, 4, 5, 6, 7]
7
null
Flatten this nested list into a single list.
nested_list = [[1,2], [3,4], [5,6]]
import itertools flattened_list = list(itertools.chain.from_iterable(nested_list)) print(flattened_list) # Output: [1, 2, 3, 4, 5, 6]
null
Create a Python program to replace all instances of a specific character in a string.
string = "Hello World!" character = "o" replacement_character = "_"
def replace_character(string, character, replacement_character): new_string = "" for c in string: if c == character: new_string += replacement_character else: new_string += c return new_string
null
Write a Python program to get the size of an object in bytes
import sys def get_object_size(obj): #Return the size of the object in bytes return sys.getsizeof(obj)
[EN Wikipedia] Badminton at the 2011 SEA Games – Men's team These are the results of the men's team competition in badminton at the 2011 SEA Games in Jakarta. Medalists Draw First round Quarterfinal Semifinal Final References Badminton at the 2011 SEA Games
null
null
null
null
Transform the following code written in Java to code written in Python.
public static int largest(int[] array) { int largest = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > largest) { largest = array[i]; } } return largest; }
def largest(array): largest = array[0] for i in range(1, len(array)): if array[i] > largest: largest = array[i] return largest
null
Create a HTML page with 4 divs, one of them should have text aligned in the center.
<!DOCTYPE html> <html> <head> <title>4 Divs</title> </head> <body> <div> This div does not contain any special styling </div> <div> This div is colored red <style>div { background-color: red; } </style> </div> <div> This div is colored blue <style>div { background-color: blue; }</style> </div> <div style="text-align: c...
null
Write a Python program to find the closest next lower value of a given number in an array of integers.
Array of Numbers: [1, 3, 8, 9, 10, 11, 12]
# Function to find the closest next lower value of a given number in an array def get_next_lower(arr, num): # Initialise a dummy variable to store the closest next lower value closest_low = 0 # Iterate through the array for i in range(len(arr)): # Check if the current number is less than the given number an...
null
Create a function that takes a list of strings as an argument and returns a list containing only non-duplicate strings.
my_list = ["Apple", "Orange", "Grapes", "Apple", "Watermelon"]
def remove_duplicates(arr): final_list = [] for i in arr: if i not in final_list: final_list.append(i) return final_list
null
This code generates rooted trees and writes their adjacency and gamma matrices to files. To use it, run the script with the maximum number of nodes as the first argument and the maximum branching factor (optional) as the second argument. The code will output the number of trees for each number of nodes and write the ma...
import sys # G is the gamma matrix # par is the parent array # n is the number of nodes def writeGammaMatrix(gammaFile, G, par, n): for i in range(n): for j in range(n): G[i][j] = 0 for i in range(n): G[i][i] = 1 j = par[i]-1 while j > -1: G[j][i] = 1 j = par[j]-1 for i in range(n): for j in ra...
[EN Wikipedia] 1849 in Denmark Events from the year 1849 in Denmark. Incumbents Monarch – Frederick VII Prime minister – Adam Wilhelm Moltke Events 12 January – General conscription is introduced in Denmark a few weeks after the First Schleswig War has been resumed after a winter break. 3 February – The Danish Veterin...
null
null
null
null
Design a function with two inputs that returns the maximum of the two.
def maximum(a, b): if a > b: return a else: return b
null
Create a SQL query to sort data from highest to lowest in the column ‘age’.
SELECT * FROM table_name ORDER BY age DESC;
null
Write a POST request to update a user's name in the following JSON format.
{ "id": "123456", "name": "John Doe" }
import requests data = { "id": "123456", "name": "John Doe" } url = "http://example.com/update-user-name" response = requests.post(url, json=data)
null
Create a XML document to store information about books.
Book Title: "The Adventures of Tom Sawyer" Book Author: Mark Twain Book Year: 1876 The Genre: Fiction
<?xml version="1.0" encoding="utf-8"?> <book> <title>The Adventures of Tom Sawyer</title> <author>Mark Twain</author> <year>1876</year> <genre>Fiction</genre> </book>
null
Write the following into python code
for i = 1 to 10 print(i)
for i in range(1,11): print(i)
null
Edit the following Java code to round a number to two decimal places.
double num = 3.14159;
double num = 3.14159; num = Math.round(num * 100.0) / 100.0; System.out.println(num); // Output: 3.14
[DE Wikipedia] Artem Wedel Artem Wedel (, * 1770 in Kiew; † 14. Juli 1808 ebenda) war ein ukrainischer Komponist und Sänger. Seine Eltern waren Kiewer Bürger Lukian und Olena Wedelskij. Sein Vater war Ikonostase-Bauer. Die Familie wohnte in einem Kiewer Vorort. Artem Wedel benutzte die abgekürzte Form des Familienname...
null
null
null
[DE Wikipedia] Reimschema Ein Reimschema ist in der Verslehre eine spezifische Form metrischer Notation und beschreibt in abstrahierender Form die Reimfolge, das heißt die Abfolge und Art der Korrespondenzen in einer Strophe oder einem Gedicht. Dabei entspricht jedem Vers ein (Klein-)Buchstabe, für reimende Verse werd...
null
null
null
null
Create a Python program that searches for a given string in a database and displays the result.
Database: { "users": [ { "name": "John", "age": 26 }, { "name": "Mark", "age": 32 }, { "name": "Alice", "age": 21 } ] } Search term: Alice
import json users = { "users": [ { "name": "John", "age": 26 }, { "name": "Mark", "age": 32 }, { "name": "Alice", "age": 21 } ] } search_term = "Alice" for user in users["users"]: if us...
null
Write a Python code to sort a 5x5 numpy matrix from the lowest to highest values.
np.array([[8, 2, 6, 7, 4], [7, 9, 5, 4, 6], [2, 3, 7, 1, 4], [5, 8, 4, 9, 6], [4, 7, 8, 2, 1]])
import numpy as np # The given array arr = np.array([[8, 2, 6, 7, 4], [7, 9, 5, 4, 6], [2, 3, 7, 1, 4], [5, 8, 4, 9, 6], [4, 7, 8, 2, 1]]) # Sort the array in ascending order sorted_arr = arr.reshape(arr.shape[0] * arr.shape[1]).argsort() # new added lin...
null
Write an SQL query to select all rows from a table where a given column value is higher than 10.
Table: users
SELECT * FROM users WHERE column_name > 10;
null
Write a SQL query to list all unique departments from the employee table.
SELECT DISTINCT department FROM employee
[DE Wikipedia] Radeck (Gemeinde Bergheim) Radeck ist ein im österreichischen Bundesland Salzburg liegendes, zur Gemeinde Bergheim im Bezirk Salzburg-Umgebung (Flachgau) gehörendes Dorf. Der Ort hatte im Spätmittelalter und in der Neuzeit Bedeutung durch das dort befindliche Schloss Radeck, das längere Zeit als Pflegge...
null
null
null
[HI Wikipedia] रशीद उद-दीन हमदानी रशीद उद-दीन (फ़ारसी: , अंग्रेज़ी: Rashīd al-Dīn Tabīb; जन्म: १२४७; मृत्यु: १३१८), जिन्हें रशीद उद-दीन फ़ज़्ल-उल्लाह​ हमदानी (फ़ारसी: , अंग्रेज़ी: Rashīd al-Dīn Fadhl-allāh Hamadānī) भी कहते हैं, एक मध्यकालीन ईरानी चिकित्सक, गणितज्ञ और लेखक थे। उन्होंने इस्लामी इतिहास पर 'जामी अल-तवारी...
null
null
null
null
Develop a shell script to display the information of the current logged in user.
#!/bin/bash echo "The username is: $(whoami)" echo "The home directory is: $HOME" echo "The current shell is: $SHELL"
null
Design a Java class for a Car which has the following attributes: name, model, year, and price.
class Car { private String name; private String model; private int year; private double price; //constructor to initialize Car object public Car(String name, String model, int year, double price) { this.name = name; this.model = model; this.year = year; this.price = price; } //getters and setters public String getName(...
null
Write code to print out the numbers up to and including the provided number, starting at 1.
number = 10
""" Write code to print out the numbers up to and including the provided number, starting at 1. """ def print_numbers_up_to(n): for i in range(1, n+1): print(i) if __name__ == '__main__': print_numbers_up_to(10)
null
Create a Python program that will print the current date and time in the following format:
import datetime date = datetime.datetime.now() print("{:0>2}/{:0>2}/{} {:0>2}:{:0>2}".format(date.day, date.month, date.year, date.hour, date.minute))
[EN Wikipedia] Lionel Chee Lionel Chee (born 4 August 1931) is a Singaporean water polo player. He competed in the men's tournament at the 1956 Summer Olympics. He was given the honour of carrying the national flag of Singapore at the opening ceremony of the 1956 Summer Olympics in Melbourne, becoming the eighth water...
null
null
null
[CS Wikipedia] Ingrid Spieglová Ingrid Spieglová, provdaná Holásková (* 6. srpna 1960 Opava), je bývalá československá krasobruslařka, která spolu se svým bratrem Alanem Spieglem (* 7. srpna 1959) soutěžila v kategorii sportovních dvojic. Sourozenci se stali šestinásobnými mistry Československa a v krasobruslení repre...
null
null
null
null
Calculate the sum of a given list of integers in Python.
[ 7, 15, 23, 5, 9 ]
def sum_list(my_list): total = 0 for num in my_list: total += num return total print(sum_list([7, 15, 23, 5, 9]))
null
Write a Python program that generates a series of Fibonacci numbers.
def fibonacci(n): a = 0 b = 1 for _ in range(n): a, b = b, a + b return a print(fibonacci(10))
null
Create an array with 3 strings, "John", "Sam" and "Anna".
string names[] = {"John", "Sam", "Anna"};
null
Create a Bash script to find the sum of all the numbers divisible by 3 and 5 in a given list.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#!/bin/bash arr=(1 2 3 4 5 6 7 8 9 10) sum=0 for n in ${arr[@]} do if [ $(($n%3)) -eq 0 -o $(($n%5)) -eq 0 ];then let sum=$sum+$n fi done echo $sum
null
Create a loop using Python to print the numbers 1 to 10.
for i in range(1,11): print(i)
null
Can you explain the bubble sort algorithm?
Bubble sort is a simple sorting algorithm which iterates through a list and compares adjacent elements, swapping them if they are in the incorrect order. This process is repeated until the list is sorted in its correct order. It is a slow algorithm as it requires multiple iterations of the list, but it is simple to und...
null
Create a Python script to generate a report of top 5 companies by total revenue.
List of current companies with their respective revenue and profit information
import pandas as pd # Read the input data df = pd.read_csv('company_data.csv') # Select the top 5 companies by total revenue top_5 = df.sort_values(by='revenue', ascending=False).head(5) # Generate the report print("Top 5 Companies by Total Revenue") print("-------------------------------") for index, row in top_5.i...
null
Write a loop to iterate through all elements in an array in JavaScript.
for (let i = 0; i < array.length; i++) { const element = array[i]; // perform operations on element }
null
Write an assembly language program to check if a given number is least in its sequence.
.model small .stack 100h .data num dw 5 .code start: mov ax, @data mov ax, num cmp ax, [num+2] ; compare current number with the next number jbe least ; if current number is lesser or equal jump to least ;code to print least number least: mov ah, 9 mov dx, offset num int 21h mov ah, 4Ch int 21h end start
null
Generate a correct Python program to calculate the linear regression line of a dataset
x_data: [1, 2, 3, 4, 5] y_data: [2, 4, 5, 4, 5]
import numpy as np def linear_reg(x_data, y_data): x_mean = np.mean(x_data) y_mean = np.mean(y_data) numerator = 0 denominator = 0 for i in range(len(x_data)): numerator += (x_data[i] - x_mean) * (y_data[i] - y_mean) denominator += (x_data[i] - x_mean) ** 2 slope = numerator...
null
Display the multiplication table for a given number.
num = 6
def num_mult_table(num): # Iterate through the numbers from 1 to 10 for i in range(1,11): # Print the multiplication table for the given number print("{} x {} = {}".format(num, i, num*i)) num_mult_table(num) # Output # 6 x 1 = 6 # 6 x 2 = 12 # 6 x 3 = 18 # 6 x 4 = 24 # 6 x 5 = 30 # 6 x 6 = 36 # 6 x 7 = 42 # 6 x 8 = 48 ...
[CS Wikipedia] La Roux La Roux je synthpopové duo, pocházející z Velké Británie. Ve své tvorbě se inspirovali především hudbou z 80. let 20. století (respektive elektronickou hudbou). Byli ovlivněni hudebními skupinami jako například Human League, Depeche Mode, Heaven 17 a Yazoo. Členové Ačkoliv se skupina tváří jako ...
null
null
null
[HI Wikipedia] झारखण्ड झारखण्ड भारत का एक राज्य है। राँची इसकी राजधानी है। झारखण्ड की सीमाएँ पूर्व में पश्चिम बंगाल, पश्चिम में उत्तर प्रदेश एवं छत्तीसगढ़, उत्तर में बिहार, और दक्षिण में ओड़िशा को छूती हैं। लगभग सम्पूर्ण प्रदेश छोटानागपुर के पठार पर अवस्थित है। सम्पूर्ण भारत में वनों के अनुपात में प्रदेश एक अग्रणी राज...
null
null
null
[CS Wikipedia] Dvořan (Castiglione) Dvořan (, plným názvem Il Libro del Cortegiano) je kniha italského renesančního autora Baldassara Castigliona, kterou napsal, když byl v diplomatických službách na urbinském dvoře v letech 1504–1518. V renesanci byl tento dvůr považován za nejdokonalejší. V roce 1507 se tu uskutečni...
null
null
null
null
Create a Python program to optimize the running time of a program using memoization.
# k: as an input parameter # f: a recursive function
def memoize(f, k): memo = dict() def helper(x): if x not in memo: memo[x] = f(x) return memo[x] return helper(k)
null
Use the given dictionary to find the value for the key "city".
{"name": "John Smith", "age": 42, "city": "Los Angeles"}
#Use the given dictionary to find the value for the key "city" dictionary = {"name": "John Smith", "age": 42, "city": "Los Angeles"} city = dictionary["city"] print("The value for the key city is: " + city)
null
Can you design an algorithm in Python that takes a string and returns all its possible permutations?
def permutations(string): # base case if len(string) <= 1: return set([string]) # recursive case else: perms = permutations(string[1:]) char = string[0] result = set() for perm in perms: for i in range(len(perm)+1): result.add(perm[:i] + char + perm[i:]) return result pri...
[DE Wikipedia] Lighter Lighter ist ein Lied der US-amerikanischen Sängerin Miley Cyrus, welches auf ihrem fünften Studioalbum Miley Cyrus & Her Dead Petz am 30. August 2015 auf SoundCloud erschien. Am 21. November 2015 wurde ein Musikvideo zu dem Lied veröffentlicht. Cyrus trat mit Lighter bei ihrer Milky Milky Milk T...
null
null
null
null
Develop a Python program to insert a given element into a specific position in a list
2, [1, 3, 4]
# Create a function def insert_element(el, lst): # Insert the element into the specific position lst.insert(2, el) return lst # Test the function print(insert_element(2, [1,3,4])) # Output [1, 3, 2, 4]
null
Design a MySQL Table to store company employees.
CREATE TABLE `employee` ( `employee_id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` varchar(255) NOT NULL, `dob` datetime NOT NULL, `salary` decimal(10,2) NOT NULL, `address` varchar(255) );
null
Write a Python program to automatically format a given source code in standardized way.
import ast import autopep8 # astunparse: https://docs.python.org/3/library/ast.html#ast.unparse def format_source_code(code): root = ast.parse(code) code_ast = ast.unparse(root) code_formatted = autopep8.fix_code(code_ast, options={'aggressive': 1}) return code_formatted
[DE Wikipedia] -leben -leben ist ein in Deutschland vorkommender Bestandteil von Ortsnamen, der besonders im östlichen Niedersachsen, Sachsen-Anhalt und Thüringen gehäuft auftritt. Der hochdeutsche Ortsnamenteil -leben hatte im Mittelniederdeutschen meist die Form -leve, im Ostfälischen gibt es die Varianten -lewwe/-l...
null
null
null
null
Write a regular expression to validate a given string of IP addresses.
^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$
null
Write a Python program to parse a given XML document and insert it into a SQL database.
Not applicable
import xml.etree.ElementTree as et import mysql.connector # Connect to the MySQL database db = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) # Parse the XML tree = et.parse('mytest.xml') root = tree.getroot() # Iterate over each element and add to ...
null
Write a Regular Expression that matches all strings starting with a lowercase 'a' and ending with an uppercase 'Z'.
^a.*Z$
null
Analyze and explain the output of the following C program.
#include<stdio.h> int main(){ int x,y; x=2; y=++x*5; printf("%d\n",y); }
The output of this program is "15". This is because the pre-increment operator (++) is used in the statement "y=++x*5". This means that the value of x is first incremented by 1 and then used in the statement. Therefore, the value of x is 3 and y is assigned the value 3*5 which is 15.
null
Write a Python program to check if a list contains a specific item.
data = [3, 4, 5, 6, 7]
def contains_item(data, item): return item in data
null
Create a Python class called "Person" with attributes "name" and "age".
class Person: def __init__(self, name, age): self.name = name self.age = age
null
Write a Python script to compute the mean of a given set of numbers.
[78.3, 75.1, 76.7, 78.2]
def mean(list_of_numbers): total = 0 for num in list_of_numbers: total += num return total / len(list_of_numbers) list_of_numbers = [78.3, 75.1, 76.7, 78.2] mean_of_list = mean(list_of_numbers) print(mean_of_list)
null
Write a Python function to check if a given number is an Armstrong number.
Not applicable
def is_armstrong_number(num): # Calculate the number of digits n = len(str(num)) # Check whether is an armstrong number sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** n temp //= 10 if num == sum: return True else: ...
null
Create a list comprehension to convert each element to its square root.
my_list = [1, 4, 9, 16, 25]
squared_list = [x**0.5 for x in my_list]
null
Write a SQL query to group the data based on 'category' and counting the number of entries in each category.
SELECT category, COUNT(*) FROM table_name GROUP BY category;
null
Write a lambda expression to select all the strings from a given array whose length is less than 5.
arr = ["Hello", "Bye", "Morning", "Evening", "Hi", "Bye Bye"]
filtered = list(filter(lambda x : len(x) < 5, arr))
null
Create a JavaScript function that can convert miles to kilometers.
function convertMilesToKilometers(miles) { return miles * 1.60934; }
null
Generate a Markov chain model that can generate text. This model should be able to generate realistic natural language sentences when given an input text.
Not applicable
from markov_python.cc_markov import MarkovChain #Creating a Markov Chain mc = MarkovChain() # Generate text text_file = open('input.txt', 'r') mc.add_file(text_file) print(mc.generate_text())