text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Write an HTML web page from scratch that displays a list of 10 different CSS colors randomly.
<html> <head> <title>Random Colors</title> <style> .random-color { background-color: #9b024a; } </style> </head> <body> <h1>Random Colors</h1> <ul> <li class="random-color">#9b024a</li> <li class="random-color">#f06f56</li> <li class="random-color">#ffb003</li> <li class="random-color">#37478d</li> <li class="random-co...
null
Design a program in Python to delete an element from the give list.
List: [1,2,3,4,5] Element to delete: 3
def delete_element(arr, element): new_arr = [i for i in arr if i!=element] return new_arr
null
Edit the following Python program to accept a list of numbers as input and find the second largest number from the list.
[12, 23, 45, 22, 50]
# Find the second largest number from a given list numbers = [12, 23, 45, 22, 50] # Sort the list in ascending order numbers.sort() # Get the second largest number second_largest_num = numbers[-2] print('The second largest number in the list is:', second_largest_num)
null
Write a Python function that takes a list of numbers and prints out a list of their squares.
[1, 2, 3]
def squares(arr): res = [] for i in arr: res.append(i**2) return res arr = [1, 2, 3] res = squares(arr) print(res)
null
Generate a random code string with each character from A-Z and 0-10.
import random def random_code_string(length): chars = [chr(i) for i in range(65, 91)] + [str(digit) for digit in range(10)] code_string = "" for _ in range(length): random_char = random.choice(chars) code_string += random_char return code_string
[EN Wikipedia] Klíčany Klíčany is a municipality and village in Prague-East District in the Central Bohemian Region of the Czech Republic. It has about 600 inhabitants. References Villages in Prague-East District
null
null
null
null
Create a PHP script to store data in a MySQL database.
<?php $db_host = "localhost"; $db_user = "username"; $db_pass = "password"; $db_name = "database"; $con = mysqli_connect($db_host, $db_user, $db_pass, $db_name); if( mysqli_connect_errno() ){ die("Failed to connect to MySQL: ".mysqli_connect_error()); } $sql = "INSERT INTO table (name, age) VALUES ('John', 25)"; if( my...
[DE Wikipedia] Middleton Island Middleton Island ist der Name mehrerer Inseln Middleton Island (Alaska), Insel in Alaska, Vereinigte Staaten Middleton Island (Illinois), Insel in den Vereinigten Staaten Middleton Island (Nunavut), Insel in Kanada Middleton Island (Saskatchewan), Insel in Kanada Middleton Island (Manit...
null
null
null
null
Use PHP to create a web page redirect script.
<?php header("Location: http://www.example.com"); die(); ?>
[EN Wikipedia] Bill Carr (American football) William Curtis Carr, III (born November 29, 1945) is an American retired college football player, coach, and athletics administrator. Carr was born in Gainesville, Florida, raised in Pensacola, Florida, and attended the University of Florida, where he was an All-American ce...
null
null
null
null
Write a Python program to create a function that takes two numbers as arguments and returns a list of all odd numbers between them.
start_range = 2 end_range = 10
def get_odds(start_range, end_range): return [num for num in range(start_range, end_range+1) if num % 2 != 0]
null
Write a Python program to shuffle the items of a given list in random order.
list_elements = [1, 2, 3, 4, 5]
from random import shuffle def shuffle_list(list_elements): shuffle(list_elements) return list_elements
null
Create a CSS class with border radius and a background colour.
.rounded-box { border-radius: 8px; background-color: #f5f5f5; }
null
Write a function in Python that will take two integers as inputs and compute their average.
int1 = 10 int2 = 15
def calculate_average(int1, int2): return (int1 + int2) / 2 print(calculate_average(int1, int2))
null
Extract words starting with 's' in this sentence.
Sentence: I send a package to Steve.
send, Steve.
[HI Wikipedia] जॉर्जिया (देश) जॉर्जिया (საქართველო, "साखार्थ्वेलो") — पूर्वी यूरोप में स्थित एक देश है। ट्रांसकाकेशिया क्षेत्र के केंद्रवर्ती तथा पश्चिमी अंश में कृष्ण सागर के दक्षिण-पूर्वी तट पर स्थित एक राज्य है। सन् 1991 तक यह जॉर्जियाई सोवियत समाजवादी गणतंत्र के रूप में सोवियत संघ के 15 गणतंत्रों में से एक था। जॉर...
null
null
null
[EN Wikipedia] Governor Rodrigues Governor Rodrigues may refer to: Diogo Rodrigues (died 1577), Governor of Salsette from 1535 to 1548 Sarmento Rodrigues (1899–1979), Governor of Portuguese Guinea from 1946 to 1949, Governor General of Salazar from, 1950 to 1951, Governor General of Portuguese Mozambique from 1961 to ...
null
null
null
[HI Wikipedia] वेनेरा 3 वेनेरा 3 (Venera 3), शुक्र ग्रह के लिए सोवियत संघ का एक लैंडर था। हालांकि शुक्र के वायुमंडलीय मापन के अपने अभियान मे यह विफल हो गया, पर किसी अन्य ग्रह की धरती को छुने वाली यह पहली मानव निर्मित वस्तुं बन गई। दुर्भाग्य से, एक खराबी ने इसे शुक्र के किसी भी वैज्ञानिक डेटा को प्रेषित करने से रोक दिय...
null
null
null
null
Design a Python class that represents a car.
class Car: def __init__(self, make, model, year, color, mileage): self.make = make self.model = model self.year = year self.color = color self.mileage = mileage def get_make(self): return self.make def get_model(self): return self.model ...
null
Create a command-line program in Python which takes in three command-line arguments. The program should add the three arguments and print the result in the console.
1 6 3
import sys if __name__ == '__main__': args = sys.argv[1:] if len(args) != 3: print('Error: Not enough arguments provided') else: result = int(args[0]) + int(args[1]) + int(args[2]) print('Result: ' + str(result))
null
Create a function to evaluate a mathematical expression like "3 + 5 * 4".
def evaluate(expression): result = None try: result = eval(expression) except: pass return result
null
Create a SQL query to get the names and ages of all the users with an age greater than 25.
SELECT name, age FROM users WHERE age > 25;
null
Create a web service in Python that can generate random numbers.
from flask import Flask import random # Create a Flask object app = Flask(__name__) @app.route("/random/<int:min>/<int:max>") def generate_random_number(min, max): # Generate a random number between min and max random_number = random.randint(min, max) return str(random_number) if __name__ == "__main__": ...
null
Estimate the power demand of a computer system using the given time and CPU utilization information using Python.
Utilization = 10% Operating Time = 10 hours Power Consumption = 100 Watts
def calculatePowerDemand(util, time, power): return util * time * power PowerDemand = calculatePowerDemand(0.1, 10, 100) print(PowerDemand)
null
Determine the output of this code snippet in C++: int x = 7; x = x + x + 2;
The output of the code snippet is 22, since the value of x will be incremented twice, from 7 to 16 and then again from 16 to 22.
[CS Wikipedia] Barometr Barometr (tlakoměr) je přístroj k měření atmosférického tlaku (tlaku vzduchu), používaný k určování stavu a předpovědi počasí (při vyšším tlaku bývá obvykle jasno, při nízkém tlaku lze očekávat změnu jasného počasí na deštivé). Barometry mohou být založeny na různém principu: Rtuťový barometr s...
null
null
null
null
Create an if-else statement in C++ to check if an integer number is greater than 0.
if (number > 0) cout << number << " is greater than 0" << endl; else cout << number << " is not greater than 0" << endl;
null
Edit the following Python code to sort a list of numbers in reversed order.
numbers = [15, 2, 5, 12, 8]
numbers.sort(reverse=True)
null
Write an API endpoint to get the average annual temperature of a given city.
@app.route("/get_average_annual_temp/<city>", methods=['GET']) def get_average_annual_temp(city): # Get the average annual temperature of the given city temp = get_average_annual_temperature(city) # Return the average temperature in json format return jsonify({'temp': temp})
null
Change the following code to an ES6 arrow function.
function addTwo(num) { var result; result = num + 2; return result; }
const addTwo = num => num + 2;
null
Write a SQL query to find the most popular product by category.
Table name: Products Columns: category (String), product_id (Integer), rating (Integer)
SELECT category, product_id, MAX(rating) FROM Products GROUP BY category ORDER BY rating DESC
null
Create a neural network in Python to classify crime-related data.
Dataset with 10 variables and 500 observations.
# Import libraries necessary for building the neural network import numpy as np import pandas as pd from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout # Read in the dataset dataset = pd.read_csv('dataset.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values...
null
Generate a function to flatten a nested list.
list = [1, 2, [3, 4, [5]], [[6], 7]]
def flatten_list(list): s=[] for v in list: if isinstance(v, list): s+=flatten_list(v) else: s.append(v) return s
null
Create a program in Python for generating a Fibonacci sequence.
# Generate a Fibonacci sequence # Function to generate Fibonacci sequence def Fibonacci(n): if n < 0: print("Incorrect input") elif n == 1: return 0 elif n == 2: return 1 else: return Fibonacci(n-1) + Fibonacci(n-2) # Print the sequence upto n terms terms = 10 print("Fi...
null
Given an array of strings, write a code snippet in Python that finds the longest string and prints its length.
arr = ["Dog","Cat","Mouse"]
arr = ["Dog","Cat","Mouse"] longest_str = max(arr, key=len) print(len(longest_str))
null
Write a code snippet to display the Fibonacci sequence up to 50 numbers.
def Fibonacci(n): a = 0 b = 1 if n < 0: print("Incorrect input") elif n == 0: return a elif n == 1: return b else: for i in range(2,n): c = a + b a = b b = c return b # Driver Code print("Fibonacci Sequence:") for i in range(50): print(Fibonacci(i), end = ' ')
[EN Wikipedia] Waiatoto River The Waiatoto River is a river of the West Coast of New Zealand's South Island. Formed from several small rivers which are fed by glaciers surrounding Mount Aspiring, it flows north along a valley flanked in the west by the Haast Range before turning northwest to reach the Tasman Sea south...
null
null
null
null
How is the Julia dynamic programming technique different from bottom-up dynamic programming?
Julia's dynamic programming technique uses memoization, which is a method of storing and reusing the result of previous computations. Bottom-up dynamic programming is a type of dynamic programming that begins with the solution to small problem instances and gradually builds up towards larger problem instances. Julia's ...
null
Create a function in Python that takes in a list of words and a target word, and prints out the first word that is alphabetically larger than the target.
words = ["Bob", "Cat", "Happy", "Lemon", "Texas", "Zebra"], target = "Lemon"
# Function to find the first word alphabetically larger than the target def find_next_word(words, target): for word in words: if word > target: return word return None
[CS Wikipedia] Královské hrobky dynastie Čoson Královské hrobky dynastie Čoson slouží jako místo odpočinku příslušníků tohoto panovnického korejské rodu. Z dynastie Čoson pochází 27 korejských panovníků, kteří se na trůně vystřídali mezi roky 1392 a 1910. V souhrnu čítá tato skupina celkem 42 hrobek (+ přilehlé stavby...
null
null
null
null
Edit the following C++ code to print the prime numbers between 1 and 100.
#include <iostream> using namespace std; int main() { int i, j; cout << "The prime numbers between 1 and 100 are:"; for (i = 1; i <= 100; i++) { for (j = 2; j <= (i / 2); j++) { if (i % j == 0) break; } // If the prime number is found if (j > (i / 2)) cout << i << " "; } return 0; }
#include <iostream> using namespace std; int main() { int i, j; cout << "The prime numbers between 1 and 100 are:"; for (i = 1; i <= 100; i++) { int isPrime = 1; for (j = 2; j <= (i / 2); j++) { if (i % j == 0) { isPrime = 0; break; } } if(isPrime == 1) cout << i << " "; } return 0; }
null
Is a valid ISBN-10 number?
isbn = "0478156686"
import re def is_valid_isbn(isbn): pattern = r"^\d{9}[\d|X]$" # ISBN is a string with 10 digits return True if re.match(pattern, isbn) else False is_valid_isbn(isbn) # Returns True
[DE Wikipedia] Yasir Subaşı Karahan Yasir Subaşı (* 1. Januar 1996 in Sakarya) ist ein türkischer Fußballspieler. Karriere Verein Subaşı kam in Sakarya auf die Welt und begann 2008 in der Nachwuchsabteilung von Sakaryaspor mit dem Vereinsfußball. Nach drei Jahren wechselte er in die Jugend von Fenerbahçe Istanbul. Zur...
null
null
null
null
Generate a Python program to convert a string of text into a list where each word is lowercased and each punctuation character is removed.
Not applicable
def textToList(string): words = [] for char in string: if char.isalpha(): words[-1] += char else: words.append('') words = [word.lower() for word in words if word] return words print(textToList('Hi there, how are you?')) # returns ['hi', 'there', 'how', 'are', 'you']
[EN Wikipedia] Donald R. Herriott Donald R. Herriott (February 4, 1928 – November 8, 2007) was an American physicist who is known for his contributions to interferometry, and for his efforts towards perfecting the techniques of high-resolution lithography. Herriott also helped bring the first helium-neon laser into op...
null
null
null
null
Can you make the following string lowercase using Python?
"This is a TEST string!"
""" Make the given string lowercase using Python """ test_string = "This is a TEST string!" lowercase_string = test_string.lower() print(lowercase_string) # prints "this is a test string!"
null
Write an SQL query to select all entries from the "Users" table.
SELECT * FROM Users;
[HI Wikipedia] पिरिडीन पिरिडीन (C5 H5 N) एक विषमचक्रीय कार्बनिक यौगिक है, जिसके चक्र में कार्बन के पाँच और नाइट्रोजन का एक परमाणु रहता है। इसके संरचनासूत्र का प्रतिपादनKorner ने १८६९ ई. में किया था। इस सूत्र से पिरिडीन के रासायनिक व्यवहार की व्याख्या ढंग से हो जाती है। परिचय कोयला, पीट-कोयला, काठ और अन्य बिटॅमिनी पदार...
null
null
null
null
Write a SQL query to find all employees over the age of 30.
SELECT * FROM Employees WHERE age > 30;
null
Modify the following HTML to apply an external style sheet.
<html> <head> <title>This Is a Test</title> </head> <body> <h1>Hello World!</h1> </body> </html>
<!DOCTYPE html> <html> <head> <title>This Is a Test</title> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> <h1>Hello World!</h1> </body> </html>
null
Uses a loop to create a list with the squares of the numbers from 0 to 5.
list1 = [] for i in range(6): list1.append(i**2) print(list1) # Output: [0, 1, 4, 9, 16, 25]
[HI Wikipedia] आल्कुबियेर इंजन आल्कुबियेर​ इंजन (Alcubierre drive) एक प्रस्तावित वैज्ञानिक युक्ति है जिसमें भौतिकशास्त्री मिगेल आल्कुबियेर​ ने आइनस्टाइन​ क्षेत्र समीकरण (फ़ील्ड इक्वेशन​) का एक संभव हल देते हुए यह दिखाया था कि कुछ परिस्थितियों में किसी यान को प्रकाश की गति से भी तेज़ चलाया जा सकता है। सामान्य सापेक्षता...
null
null
null
null
Generate a dynamic HTML table displaying 10 random numbers from 1 to 100.
<html> <head> </head> <body> <div> <table> <tr><th>Random Numbers</th></tr> <tr><td><?php echo rand(1,100); ?></td></tr> <tr><td><?php echo rand(1,100); ?></td></tr> <tr><td><?php echo rand(1,100); ?></td></tr> <tr><td><?php echo rand(1,100); ?></td></tr> <tr><td><?php echo rand(1,100); ?></td></tr> <tr><td><?php echo ...
null
Compile the given C++ code.
#include <iostream> using namespace std; int main() { cout << "Hello World!"; return 0; }
g++ file.cpp -o file
[DE Wikipedia] Paris–Luxemburg 1965 Paris–Luxemburg 1965 war die 3. Austragung von Paris–Luxemburg, einem mehrtägigen Etappenrennen. Das Rennen wurde von Jean Stablinski vor Guido Reybrouck und Edward Sels gewonnen. Teilnehmende Mannschaften Etappenübersicht Ergebnisse Gesamtwertung Weblinks Paris–Luxembourg 1965 Einz...
null
null
null
null
Create a HTML page to show user data from a REST API.
{ "name": "John", "age" : 25, "address" : "123 Main Street" }
<html> <head> <title>User Data</title> </head> <body> <h1>User Data</h1> <p>Name: John</p> <p>Age: 25</p> <p>Address: 123 Main Street</p> </body> </html>
null
Create an algorithm in any language (Python, JavaScript, etc.) that searches for a given value in a binary search tree.
tree = {value: 24, left: {value: 19, left: {value: 12, left: None, right: None}, right: None}, right: {value: 38, left: None, right: None}} search_term = 12
def search(tree, searchTerm): if tree['value'] == searchTerm: return True if tree['left'] != None: if search(tree['left'], searchTerm): return True if tree['right'] != None: if search(tree['right'], searchTerm): return True return False tree = {value: 24, left: {value: 19, left: {value: 12, left: None, ...
null
Create a Python program to take a float input and output its binary equivalent.
25.68
def floatToBin(num): whole, decimal = str(num).split(".") whole = int(whole) decimal = int (decimal) res = bin(whole).lstrip("0b")+"." for x in range(10): decimal *= 2 res += str(decimal//1) decimal %= 1 return res # Driver code number = 25.68 print(floatToBin(number)) # returns '11001.1011'
[EN Wikipedia] Slovenian Book Agency The Slovenian Book Agency ( often abbreviated to JAK or JAKRS) is an autonomous government agency in Slovenia that was created to promote the importance of books and reading in Slovenia and beyond. The Agency was created in 2008 and began to function on 1 January 2009, fulfilling t...
null
null
null
null
Replace the following line of Javascript to appy the data-attribute to the element.
document.getElementById("message").append("My Message");
document.getElementById("message").setAttribute("data-text", "My Message");
null
Perform a search operation to find all the words starting with "th".
Sentence: The big cat ate the small mouse.
['The', 'the', 'that']
[EN Wikipedia] Guy Lafond Guy Lafond was a research scientist for over 30 years with Agriculture and Agri-Food Canada at the Indian Head Research Farm in Saskatchewan. He was instrumental in establishing the Indian Head Agricultural Research Foundation (IHARF) in the early 1990s and had a major impact on cropping prac...
null
null
null
null
Create a Python script to print out only the even numbers from a list of numbers.
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in list: if (num % 2 == 0): print(num, end = ' ')
[EN Wikipedia] Thomas Einwaller Thomas Einwaller (born 25 April 1977) is an Austrian football referee. He has been a FIFA international referee since 2005. He lives in Scheffau am Wilden Kaiser and works as a bank clerk. He has refereed games at the 2008 Olympics (including a bronze medal game), UEFA Champions League,...
null
null
null
null
Create a method to generate a random integer between 1 and 10 in Python.
import random def random_int(): return random.randint(1, 10)
[DE Wikipedia] Tiberius Iulius Candidus Capito Tiberius Iulius Candidus Capito war ein im 2. Jahrhundert n. Chr. lebender römischer Politiker. In den Militärdiplomen wird sein Name als Tiberius Iulius Capito angegeben. Durch Militärdiplome, die auf den 17. Juli 122 datiert sind, ist belegt, dass Capito 122 zusammen mi...
null
null
null
[DE Wikipedia] Thomas Oppermann Thomas Oppermann ist der Name folgender Personen: * Thomas Oppermann (Jurist) (1931–2019), deutscher Rechtswissenschaftler Thomas Oppermann (Politiker) (1954–2020), deutscher Politiker (SPD)
null
null
null
[EN Wikipedia] Dick Stevens Dick Stevens (born February 23, 1948) is a former American football offensive tackle who played five seasons in the National Football League (NFL). Early life and high school Stevens "Tuck" was born and raised in Dublin, Texas, where he attended Dublin High School. He was named All-District...
null
null
null
null
Create an algorithm that checks if a given String is a valid identifier in Python.
def is_valid_identifier(string): if string.isidentifier(): return True else: return False
null
Find the minimum number from the given array in Java.
int arr[]={10, 50, 18, 63, 27};
int min = arr[0]; for (int i = 1; i < arr.length; i++) if (arr[i] < min) min = arr[i]; System.out.println(min);
[EN Wikipedia] Anicet Turinay Anicet Turinay (born 18 April 1945) is a conservative politician from Martinique who served in the French National Assembly from 1993 to 2002. References Anicet Turinay page on the French National Assembly website 1945 births Living people People from Gros-Morne, Martinique Martiniquais p...
null
null
null
null
Write a Python program to check if a given list of strings consists only of unique elements.
my_list = ['cat', 'dog', 'cat']
def check_unique_list(my_list): unique_list =[] for i in my_list: if i not in unique_list: unique_list.append(i) if len(unique_list) == len(my_list): return True else: return False
null
Create an HTML form that can process the user's email address.
<form method="post" action="process.php"> <label>Email address:</label> <input type="email" name="user_email" required> <input type="submit" value="Submit"> </form>
null
Create a python function to extract the largest DNA sequence from a list of sequences.
sequences = ["ATGATATCATCGATTGTA", "ATGCGATATACGATGAT", "ATGGATCGATTATATTA"]
def longest_sequence(sequences): longest_sequence = sequences[0] for sequence in sequences: if len(sequence) > len(longest_sequence): longest_sequence = sequence return longest_sequence print(longest_sequence(sequences)) # ATGATATCATCGATTGTA
[DE Wikipedia] Aleksander Fredro Aleksander Fredro (* 20. Juni 1793 in Surochów bei Jarosław; † 15. Juli 1876 in Lemberg) war ein polnischer Dramatiker und gilt als einer der bedeutendsten Komödienautoren seines Landes. Leben Aleksander Fredro wurde in der Familie eines polnischen Adligen geboren und trug deshalb den ...
null
null
null
null
Break the following string into two pieces.
"HelloWorld"
String s1 = "Hello"; String s2 = "World";
null
Create a program in Python that classifies French text using a pre-trained model.
Not applicable
import torch from transformers import BertTokenizer, BertForMaskedLM tokenizer = BertTokenizer.from_pretrained('bert-base-french-cased') model = BertForMaskedLM.from_pretrained('bert-base-french-cased') text = "J'aime aller au cin_ma." input_ids = tokenizer.encode(text, return_tensors='pt') prediction = model(input_...
null
Create a Python web Crawler to parse a web page and extract the textual content only.
Not applicable
import requests from bs4 import BeautifulSoup url = 'https://example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') text = soup.find_all(text=True) def visible_text(elements): for element in elements: if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:...
null
Create a Python program to generate a report of a user's sales data.
A list of dictionaries containing sales data.
import csv # A list of dictionaries containing sales data sales_data = [ { 'name': 'John', 'quantity': 2, 'price': 10.0 }, { 'name': 'Jane', 'quantity': 3, 'price': 15.0 }, { 'name': 'Mike', 'quantity': 4, 'price':
null
Create a program to parse a given string and return a dictionary with all the words and their frequency
"this is a practice string to learn the parsing of strings"
""" Create a program to parse a given string and return a dictionary with all the words and their frequency """ def parse_string(string): words = string.split() word_dict = {} for word in words: if word in word_dict: word_dict[word] += 1 else: word_dict[word] = 1 return word_dict if __name__ == '__main__': print(parse_...
null
Write a Python program that implements gradient descent to find the minimum of a function.
function = 3x² + 2x - 10
import numpy as np # Define the function def f(x): return (3 * (x**2)) + (2 * x) - 10 def grad_f(x): return (6 * x) + 2 # Gradient Descent x_old = 0 x_new = 4 # Arbitrary initial value epsilon = 0.01 # Stop criteria precision = 0.00001 max_iters = 1000 # Maximum number of iterations iters = 0 while abs(x_n...
null
Parse a JSON response into a Python dictionary.
{ "name": "John Doe", "age": "35" }
import json def parse_json(json_data): data = json.loads(json_data) return data if __name__ == '__main__': json_data = '{"name": "John Doe", "age": "35"}' print(parse_json(json_data))
null
Evaluate the following line of code written in Python and explain what it does.
not any(map(lambda k,v: k in d or v in d, x))
This line of code is written in Python and is using the built-in "any" and "map" functions. The code is checking if none of the key-value pairs in the map "x" are in the dictionary "d". It does so using a lambda function to check if either the key or the value is present in the dictionary. If none are present, it will ...
null
Update a Python program which constructs a list of prime numbers using the Sieve of Eratosthenes algorithm. The program should improve its performance by using an efficient implementation of the algorithm.
Not applicable
def sieve_of_eratosthenes(n): primes = [True for i in range(n+1)] p = 2 while (p * p <= n): if (primes[p] == True): for i in range(p *2, n+1, p): primes[i] = False p += 1 primes[0] = False primes[1] = False prime_numbers = [] for i in range(n+1): if primes[i]: prime_numbers.append(i) return ...
[DE Wikipedia] Rolf Storm (Politiker) Rolf Storm (* 10. August 1945 in Kiel) ist ein Kaufmann und war ein Politiker (FDP, LD) und für die FDP Mitglied der Bremischen Bürgerschaft. Biografie Familie, Beruf Storm war als kaufmännischer Angestellter und ab 1995 bis 2013 als Geschäftsführer in der C. Melchers GmbH in Brem...
null
null
null
[CS Wikipedia] Klín Klín je jednoduchý stroj, jehož jedinou částí je těleso s průřezem ve tvaru trojúhelníku (trojboký hranol, kužel, jehlan). Jedná se o jeden z nejstarších předmětů používaných lidmi. Síla, která působí na podstavu klínu, se rozloží ve směru kolmém na boční stěny, přitom tyto složky jsou větší než pů...
null
null
null
[HI Wikipedia] कटहरी चम्पा कटहरी चम्पा एनोनेसिई (Annonaceae) कुल का पौधा है। इसे हरा, अथवा कटहरी, चंपा कहते हैं। इसका वानस्पतिक नाम चंपा आर्टाबोट्रिस ओडोराटिसियम (Artabotrys odoratissimus) है। यह अरटाबोट्रिस वर्ग के पौधे अफ्रीका तथा पूर्वी एशिया के देशों में पाए जाते हैं। भारत में इस वर्ग की १० जातियाँ पाई जाती हैं। इ...
null
null
null
null
Implement a queue data structure.
class Queue: def __init__(self): self.data = [] def is_empty(self): return not self.data def enqueue(self, element): self.data.append(element) def dequeue(self): return self.data.pop(0) def peek(self): if not self.is_empty(): return self.data[0]
[CS Wikipedia] Kurtzkeho stupnice postižení Kurtzkeho stupnice postižení, známá také jako rozšířená stupnice stavu invalidity (: Expanded Disability Status Scale, EDSS), či také jako Kurtzkeho škála, je metoda kvantifikace zdravotního postižení u pacientů s roztroušenou sklerózou (RS). Stupnice byla vyvinuta americkým...
null
null
null
[EN Wikipedia] Fabio Fognini career statistics This is a list of main career statistics of Italian professional tennis player Fabio Fognini. All statistics are according to the ATP World Tour and ITF websites. Performance timelines Only main-draw results in ATP Tour, Grand Slam tournaments, Davis Cup/ATP Cup/Laver Cup...
null
null
null
null
Implement a function in C++ that takes two strings as parameters and returns the longest common substring between the two.
str1 = "stackoverflow" str2 = "overburning"
#include <iostream> #include <string> using namespace std; //function to find common substring string longestCommonSubstring(string str1, string str2) { int m = str1.length(); int n = str2.length(); int table[m + 1][n + 1]; //fill the lookup table int res_len = 0; string res; for(int i=0; i<=m; i++) { for(int j=0; j<=n...
null
Create a function to check if an input string has unique characters or not.
string = "unique"
def has_unique_characters(string): return len(string) == len(set(string))
null
Develop a classifier in Python that can distinguish between mathematical sentences and scientific sentences.
["The derivative of x^2 is 2x.", "Water is a molecule composed of two hydrogen atoms and one oxygen atom."]
import numpy as np from sklearn.feature_extraction.text import CountVectorizer sentences = ["The derivative of x^2 is 2x.", "Water is a molecule composed of two hydrogen atoms and one oxygen atom."] labels = [1, 0] # Instantiate CountVectorizer vectorizer = CountVectorizer() # Fit the vectorizer to the data vectoriz...
[DE Wikipedia] Volvo ÖV4 Der Volvo ÖV 4 ist der erste Serien-PKW von Volvo. Beschreibung Der erste ÖV4 lief am 14. April 1927 vom Band. Die Abkürzung ÖV steht für „öppen vagn“ (offener Wagen) und 4 für die Anzahl der Zylinder. Aus technischer Sicht war dieses Automobil keine Besonderheit, da es fast vollständig auf be...
null
null
null
null
How can we optimize the performance of the given code?
myList = [1, 2, 3] for item in myList: print(item)
Use list comprehension to reduce the amount of code used, such as: print([item for item in myList])
null
Create a Python dictionary from two given lists.
list1 = ['a', 'b', 'c'] list2 = [1, 2, 3]
dict1 = dict(zip(list1, list2)) print(dict1)
null
Create a class in python, named RoundInstance, that can store radius, diameter, area and circumference coordinates.
class RoundInstance(): def __init__(self, radius, diameter, area, circumference): self.radius = radius self.diameter = diameter self.area = area self.circumference = circumference def get_radius(self): return self.radius def get_diameter(self): return se...
[DE Wikipedia] Pussy Power Pussy Power ist das dritte Studioalbum der deutschen Sängerin und Rapperin Katja Krasavice. Es erschien am 11. Februar 2022. Hintergründe Am 1. August 2021 kündigte Krasavice auf ihrem offiziellen Instagram-Profil ihr drittes Studioalbum Pussy Power an. Aus dem Album erschienen drei Singleau...
null
null
null
[EN Wikipedia] April 12 Events Pre-1600 240 – Shapur I becomes co-emperor of the Sasanian Empire with his father Ardashir I. 467 – Anthemius is elevated to Emperor of the Western Roman Empire. 627 – King Edwin of Northumbria is converted to Christianity by Paulinus, bishop of York. 1012 – Duke Oldřich of Bohemia depos...
null
null
null
null
Compute the modulus of 3 and 4.
3