text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Create a function that returns the sum of two numbers passed as arguments.
def add_numbers(a,b): return a + b # Testing x = 3 y = 4 sum = add_numbers(x, y) print("Sum of {0} and {1} is {2}".format(x, y, sum))
null
Write a Python program to calculate the entropy of a given dataset.
Dataset: [1,1,1,1,1,1,2,2,2,2,3,3]
def entropy(dataset): counts = {} entropy = 0 for i in dataset: if i in counts: counts[i] += 1 else: counts[i] = 1 for i in counts: p = counts[i]/len(dataset) entropy -= p*np.log2(p) return entropy entropy([1,1,1,1,1,1,2,2,2,2,3,3])
null
Design a game controller class that stores and updates game state in Python
class GameController: def __init__(self): self.state = {'lives': 3, 'score': 0, 'level': 1} def update_game_state(self, lives, score, level): self.state['lives'] = lives self.state['score'] = score self.state['level'] = level def get_game_state(self): return sel...
[EN Wikipedia] Atlas (disambiguation) An atlas is a collection of maps. Atlas may also refer to: Mythology Atlas (mythology), an Ancient Greek Titanic deity Atlas, the first legendary king of Atlantis Atlas of Mauretania, a legendary king Places United States Atlas, California Atlas, Illinois Atlas, Texas Atlas, West ...
null
null
null
[CS Wikipedia] Mistrovství světa v atletice 2009 – Muži hod diskem Závod v hodu diskem mužů na Mistrovství světa v atletice 2009 se uskutečnil 18. a 19. srpna. Zvítězil v něm německý diskař Robert Harting výkonem 69,43 m. Mezi 30 startujícími nechyběl žádný z aktuálně nejvýkonnějších diskařů. Do finálové dvanáctky z k...
null
null
null
null
Write a Python program to determine if a number provided by the user is prime or not.
17
# Ask the user for a number num = int(input('Enter a number: ')) # Set initial values is_prime = True # Check for prime for i in range(2, num): if num % i == 0: is_prime = False break # Output result if is_prime: print(f'{num} is a prime number.') else: print(f'{num} is not a prime number.')
null
Using regular expressions, separate the below string into three parts.
"a=1,b=2,c=3"
regex = "\w=(\d+)" a, b, c = re.findall(regex, "a=1,b=2,c=3")
null
Suggest an efficient way to find the longest word in a string.
The most efficient way to find the longest word in a string is to use the split() method to convert the string into a list of words, then use the max() method to find the longest word in the list. For example: string = "The quickest way to find the longest word" longest_word = max(string.split(), key=len)
null
Create two classes, "Animal" and "Dog", in which the "Dog" class inherits from the "Animal" class.
class Animal: pass class Dog(Animal): pass
[HI Wikipedia] युक्रेन {{ज्ञानसन्दूक देश | native_name = युक्रेन | conventional_long_name = | common_name = युक्रेन | image_flag = Flag of Ukraine.svg | image_coat = Lesser Coat of Arms of Ukraine.svg | image_map = Europe-Ukraine (disputed territory).svg | map_caption = | national_anthem = (Ukrainian) युक्रेन पूर्वी य...
null
null
null
null
Create a function to print a multiline message in Python
message = "This is a multiline message."
def print_multiline_message(message): print(message)
null
Create a Python function to print out a string in reverse order.
"This is a string"
def reverse_string(input_str): return input_str[::-1] print(reverse_string("This is a string"))
null
Develop a code that implements linear regression in Python.
import numpy as np # define the data # X = [1, 2, 3, 4, 5] # Y = [2, 4, 5, 4, 5] X = np.array([1, 2, 3, 4, 5]) Y = np.array([2, 4, 5, 4, 5]) # calculate the mean of x and y xmean = np.mean(X) ymean = np.mean(Y) # calculate the equations num = 0 den = 0 for i in range(len(X)): num += (X[i] - xmean)*(Y[i] - ymean...
null
Create an HTML page demonstrating the application of "for" loop in JavaScript
<html> <head> <script> for(let i=0; i<5; i++){ console.log('loop ' + i); } </script> </head> <body> </body> </html>
null
Correct the following code and generate an output:
list_of_ints = [2, 3, 4, 8] for x in list_of_ints print(x)
list_of_ints = [2, 3, 4, 8] for x in list_of_ints: print(x) # Output: 2 3 4 8
null
Generate a random string with 10 characters.
let randomString = Math.random().toString(36).substring(2, 12);
[EN Wikipedia] HD 111395 HD 111395 is a single, variable star in the northern constellation of Coma Berenices. It has the variable star designation LW Com, short for LW Comae Berenices; HD 111395 is the Henry Draper Catalogue designation. The star has a yellow hue and is just bright enough to be barely visible to the ...
null
null
null
null
Generate a classifier in Python using the Random Forest algorithm.
Features: Weight, Size Label: Type
from sklearn.ensemble import RandomForestClassifier X = [[Weight, Size]] y = [Type] model = RandomForestClassifier(random_state=0) model.fit(X, y)
null
Create a Bash script to print the argument provided.
echo "This is the argument: $1"
null
Convert the given JSON data into Python dictionary.
{"name": "John", "age": 30, "hobby": "running"}
import json data = '{"name": "John", "age": 30, "hobby": "running"}' dict_data = json.loads(data) print(dict_data)
null
Write a Java program to find the element that appears maximum number of times in an array.
int [] arr1 = {2, 8, 7, 2, 8, 2, 6}
public class MaxElement { public static void main(String[] args) { int[] arr1 = {2, 8, 7, 2, 8, 2, 6}; int count = 1; int max_element=arr1[0]; int temp_count; for (int i = 0; i < arr1.length; i++) { temp_count = 1; for (int j = i+1; j < arr1.length; j++) { if(arr1[i] == arr1[j]){ temp_count++; } } if(temp_count > count...
null
Given an array of numbers, write a Python function to remove even numbers from the array.
[1, 2, 3, 4, 5, 6, 7, 8, 9]
def remove_even_numbers(arr): return [x for x in arr if x % 2 != 0]
null
Develop a function in Python to calculate the circumference of a circle.
def calculate_circumference(radius): circumference = 2 * 3.14 * radius return circumference if __name__ == '__main__': radius = 10 circumference = calculate_circumference(radius) print(circumference)
null
Generate prime numbers between two given numbers
start = 8 end = 20
The prime numbers between 8 and 20 are 11, 13, 17, 19
[CS Wikipedia] Na samotě u lesa Na samotě u lesa je česká komedie režiséra Jiřího Menzela z roku 1976. Byla natáčena poblíž Radešic (chalupa) a ve Svatém Janu (pohřeb, rvačka v hospodě) v okrese Příbram. Obsah Film vypráví o obyčejné pražské rodince Lavičkových a její snaze výhodně získat domek na venkově. Lavičkovi s...
null
null
null
null
Create a class in Python named "MyCalculator" with a method "sum" that calculates the sum of two numbers.
class MyCalculator: def __init__(self): pass def sum(self, a, b): return a + b
null
Determine the type of an object.
"Hello"
type(“Hello”)
null
Modify the following CSS code to change the background color of the element to "#FFC0CB"
.main-page { background-color: #FFF; }
.main-page { background-color: #FFC0CB; }
null
Create a SELECT query in MySQL to find the records in a given table that satisfy a certain condition.
Table Name: orders Condition: quantity > 20
SELECT * FROM orders WHERE quantity > 20;
null
Construct a deep neural network in Python to perform sentiment analysis on a collection of movie reviews.
import tensorflow as tf from tensorflow.keras.layers import Embedding, Dense, Dropout, LSTM from tensorflow.keras.models import Sequential #Create the network model = Sequential() #Add embedding layer model.add(Embedding(1000, 64)) #Add two LSTM layers model.add(LSTM(32, return_sequences = True)) model.add(LSTM(32))...
null
Create a question-answering system using Python and Natural Language Processing.
import nltk, numpy from nltk.stem.lancaster import LancasterStemmer stemmer = LancasterStemmer() # importing our intents file import json with open('intents.json') as json_data: intents = json.load(json_data) # tokenizing patterns words = [] classes = [] documents = [] ignore_words = ['?'] # loop through each s...
[DE Wikipedia] Stéphane Simian Stéphane Simian (* 8. Juni 1967 in Le Pontet, Département Vaucluse) ist ein ehemaliger französischer Tennisspieler. Karriere Simian wurde 1991 Tennisprofi und stand bereits im darauf folgenden Jahr in seinem ersten Einzelfinale auf der ATP World Tour. In Tel Aviv unterlag er jedoch in dr...
null
null
null
null
Generate a Python class to define a complex number and an operator overloading function to add two complex numbers.
class ComplexNumber: def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def __add__(self, other): return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)
null
Write a function to remove a given element from an array of integers.
arr = [2, 3, 4, 5, 6] remove_element = 4
def remove_element(arr, remove_element): new_arr = [] for item in arr: if item != remove_element: new_arr.append(item) return new_arr
null
Write a code to extract data from a web page using python requests.
""" Extract data from a web page using python requests """ import requests # Define the url url = 'https://example.com' # Get the data from the url response = requests.get(url) # Extract the data data = response.text # or response.json() for JSON data # Print the data print(data)
null
Code a function that takes a dictionary as a parameter and prints out the key-value pairs.
def print_dict(dictionary): for key, value in dictionary.items(): print(f"{key}: {value}")
null
Develop a Python script to generate an array of given size filled with random numbers.
int size = 10
import random def arr_of_random_numbers(size): arr = [] for i in range(size): arr.append(random.randint(1, 100)) return arr size = 10 arr = arr_of_random_numbers(size) print(arr)
[EN Wikipedia] E.J. White Elyse White is an English professor at Stony Brook University, and author of You Talkin' to Me?: The Unruly History of New York English. White is a Fellow of the Society for the Humanities. During an interview on WSHU about her 2020 book You Talkin' To Me?: The Unruly History of New York Engl...
null
null
null
null
Write a Python program to find the nth term of Fibonacci Series.
def nth_term_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
[HI Wikipedia] उशोजी भाषा उशोजी (Ushoji, ), जिसे उशोजो (Ushojo, ) भी कहते हैं, शीना शाखा की एक दार्दी भाषा है जो पाकिस्तान के ख़ैबर​-पख़्तूनख़्वा प्रान्त के कोहिस्तान और स्वात ज़िलों में बोली जाती है। सन्दर्भ हिन्द-आर्य भाषाएँ दार्दी भाषाएँ पाकिस्तान की भाषाएँ
null
null
null
null
Implement a Java class that encapsulates a basic for loop.
public class loop { public void forLoop(int start, int end){ for(int i=start; i<end; i++){ System.out.println(i); } } }
[HI Wikipedia] मथुरा मथुरा (Mathura) भारत के उत्तर प्रदेश राज्य के मथुरा ज़िले में स्थित एक नगर है। मथुरा ऐतिहासिक रूप से कुषाण राजवंश द्वारा राजधानी के रूप में विकसित नगर है। लोगों की मान्यता है की उससे पूर्व भगवान कृष्ण के समय काल से भी पूर्व अर्थात लगभग 7500 वर्ष से यह नगर अस्तित्व में है.यह धार्मिक पर्यटन स्थल के ...
null
null
null
null
Explain how to use functions in Python to perform operations on dictionaries.
Python dictionaries are mappings between keys and values, allowing for efficient retrieval of values using its associated key. Various functions can be used to manipulate the data in the dictionaries, such as the get() function to retrieve the value for a given key, the clear() function to delete all values, the keys()...
null
Write a function to validate an email address in Python.
def validate_email(email): """This function validates an email address. It returns True if the email address is valid, False otherwise. """ if len(email) > 7: if re.match('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', email) is not None: return True return False
null
Create an Android function to get the current battery level.
public float GetBatteryLevel(Context context){ Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); if(level == -1 || scale == ...
null
Create a Java program that prints out the sum of the numbers in the array.
int[] numbers = {1, 2, 3 , 4, 5};
public class SumOfArray { public static void main(String[] args) { int[] numbers = {1, 2, 3 , 4, 5}; int sum = 0; for(int i=0; i < numbers.length;i++) { sum = sum + numbers[i]; } System.out.println("The sum of numbers in the given array is: " + sum); } }
null
Write a code in which the values in the dictionaries will be swapped.
dic = {'x': 10, 'y': 20}
def swap_dictionary_values(dic): """Function to swap the values in the dictionaries""" dic['x'], dic['y'] = dic['y'], dic['x'] return dic if __name__ == '__main__': dic = {'x': 10, 'y': 20} swapped_dic = swap_dictionary_values(dic) print(swapped_dic) # {'x': 20, 'y': 10}
[CS Wikipedia] Senoni Senoni (starořecky: Σήνωνες) byl starověký keltský kmen, který v druhé polovině tisíciletí př. n. l. obýval Apeninský poloostrov a je známý také z období galských válek. Senoni v Itálii Podle legendy se tento kmen připojil k Bellovesově migraci do Itálie, společně s Aedui, Ambarry, Arverny, Auler...
null
null
null
null
Write a JavaScript function for finding the biggest element in an array.
[2, 4, 5, 6, 8, 10]
function findMax(arr) { let max = arr[0]; for (let i = 0; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; } return max; }
null
Can you generate a sytax tree of a given Python statement?
statement = "x = 5;"
Syntax Tree: Assign(targets=[Name(id='x', ctx=Store())], value=Num(n=5))
[DE Wikipedia] Reichsgerichtsgebäude Das Reichsgerichtsgebäude ist als Gerichtsgebäude für das Reichsgericht entworfen und gebaut worden und dient seit 2002 dem Bundesverwaltungsgericht als Sitz. Es liegt in unmittelbarer Nähe des Neuen Rathauses im Leipziger Musikviertel. Architektur Dem Bau ging 1884/1885 ein Archit...
null
null
null
null
Format the following code according to PEP 8 style guidelines.
def function1( a, b, c): d = a+b*c return d
def function1(a, b, c): d = a + b * c return d
null
Construct a Python code to combine the elements of two given list and return a sorted union list.
input_list_1: [4, 10, 2] input_list_2: [10, 2, 15]
def union_list(list1, list2): list3 = list1 + list2 list3.sort() return list3 union_list(input_list_1, input_list_2)
null
Given the following array, delete all occurrences of the number 4.
list1 = [4, 3, 4, 2, 3, 4, 4]
list1 = [4, 3, 4, 2, 3, 4, 4] def delete_four(arr): """This function deletes all occurrences of the number 4 in the given array""" for i in range(len(arr)): if arr[i] == 4: arr.pop(i) i -= 1 return arr print(delete_four(list1))
null
Write a Python program to create a Caesar Cipher encryption for a given string.
def encrypt(text,s): result = "" # traverse text for i in range(len(text)): char = text[i] # Encrypt uppercase characters if (char.isupper()): result += chr((ord(char) + s-65) % 26 + 65) # Encrypt lowercase characters else: r...
null
Develop a Python Class that retrieves and displays web page content.
import requests class WebPageContent: def __init__(self, url): self.url = url def get_content(self): response = requests.get(self.url) if response.status_code == 200: return response.text def display_content(self): content = self.get_content() if co...
null
Create a linked list from the given array of numbers.
[2, 4, 5, 6, 7]
Head -> 2 -> 4 -> 5 -> 6 -> 7 -> None
null
Create a Python program to tokenize a sentence and calculate the frequency of each word in the sentence.
The quick brown fox jumps over the lazy dog
import nltk sentence = "The quick brown fox jumps over the lazy dog" words = nltk.word_tokenize(sentence) word_freq = {} for word in words: if word in word_freq: word_freq[word] += 1 else: word_freq[word] = 1 print(word_freq)
null
Write a Python program to find the four letter words from a given list.
["tree", "door", "apple", "ball", "house", "cat", "wood"].
""" A Python program to find the four letter words from a given list """ # Initializing the list words = ["tree", "door", "apple", "ball", "house", "cat", "wood"] # Using list comprehension to extract four letter words four_letter_words = [word for word in words if len(word) == 4] # Printing the four letter words print...
null
Write an algorithm to calculate the average of a list of integers given as input.
def average(nums): """ Takes a list of numbers and returns the average. """ total = 0 for num in nums: total += num return total / len(nums)
null
Split the following string into words in Python
string = 'this_is_a_string_in_python'
# Split the string by '_' separator words = string.split('_') # Print each word separately for word in words: print(word)
null
Create a basic graphical user interface in Python using tkinter.
Not applicable
import tkinter as tk root = tk.Tk() frame = tk.Frame(root) frame.pack() button = tk.Button(frame, text="Click Me!", fg="blue", command=lambda: print("Hello World!")) button.pack(side=tk.LEFT) close = tk.Button(frame, text="Exit", ...
null
Generate a python class for a linked list.
class LinkedList: def __init__(self, value=None): self.value = value self.next = None def append(self, value): if self.value is None: self.value = value return temp = self while temp.next is not None: temp = temp.next t...
null
Develop a machine learning model in Python to predict the survival rate of a passenger in the Titanic dataset.
Not applicable
import pandas as pd import matplotlib.pyplot as plt from matplotlib import style from sklearn import preprocessing from sklearn.model_selection import cross_validate, train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score style.use("seaborn-whitegrid") # Load t...
null
Write a Python program that takes two strings and returns the longest common subsequence between the two strings.
String1 = "ABCDAF" String2 = "ACBCF"
def lcs(string1, string2): n = len(string1) m = len(string2) dp = [[0 for x in range(m + 1)] for x in range(n + 1)] # fill dp table in bottom up manner for i in range(n + 1): for j in range(m + 1): if i == 0 or j == 0: dp[i][j] = 0 elif string1[i-1] == string2[j-1]: dp[i][j] = dp[i-1][j-1] + 1...
null
Explain the difference between .push(), .pop(), .shift() and .unshift() methods in JavaScript arrays.
The .push() method adds an element to the end of an existing array. It takes a single argument, the element to be added, and returns the new length of the array. The .pop() method removes an element from the end of an existing array. It does not take any arguments and returns the element that was removed. The .shift() ...
null
Write a JavaScript expression to generate a random integer between 1 and 25.
var randNumber = Math.floor(Math.random() * 25) + 1;
null
Write a Ruby function that reverses a string.
def reverse_string(str) return str.reverse end
[HI Wikipedia] यूनिकोड यूनिकोड प्रत्येक अक्षर के लिए एक विशेष संख्या प्रदान करता है, चाहे कोई भी कम्प्यूटर प्लेटफॉर्म, प्रोग्राम अथवा कोई भी भाषा हो। यूनिकोड स्टैंडर्ड को एपल, एच.पी., आई.बी.एम., जस्ट सिस्टम, माइक्रोसॉफ्ट, ऑरेकल, सैप, सन, साईबेस, यूनिसिस जैसी उद्योग की प्रमुख कम्पनियों और कई अन्य ने अपनाया है। यूनिकोड ...
null
null
null
null
Create a function in HTML to display a blinking text on the webpage.
<script> function blink() { var text = document.getElementById('blink'); text.style.visibility = (text.style.visibility == 'hidden' ? '' : 'hidden'); setTimeout("blink()", 500); } blink(); </script> <span id="blink">Text to blink</span>
null
Write a loop in Python that accumulates the sum of the numbers in an array.
[1, 2, 3]
sum = 0 for num in [1, 2, 3]: sum += num print(sum)
null
Write a CSS rule to center a container with class "main".
.main { margin: 0 auto; width: 100%; display: block; text-align: center; }
null
Create an PHP script to display the current date and day.
<?php echo date("l, F jS") ?>
[DE Wikipedia] Val Trebbia Das Val Trebbia ist ein Tal in den norditalienischen Regionen Ligurien, Lombardei und Emilia-Romagna. Vom gleichnamigen Fluss geformt, erstreckt es sich vom Monte Prelà in der Metropolitanstadt Genua bis in die Provinz Piacenza und das Oltrepò Pavese bei Brallo di Pregola. Nach einem Verlauf...
null
null
null
null
Build a Python function that normalizes a given array.
array = [4, 8, 15, 23, 42]
def normalize(array): min_val = min(array) max_val = max(array) normalized = [ (x-min_val) / (max_val-min_val) for x in array] return normalized
null
Suggest a programming language and a library for text classification.
Python is a great language for text classification tasks and there are several libraries that could be used, including scikit-learn and NLTK. Additionally, pytorch provides a number of utilities for text classification.
null
Create a binary search tree in JavaScript.
class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } } class BinarySearchTree { constructor() { this.root = null; } insert(data) { let newNode = new Node(data); if(this.root === null) { this.root = newNode; } else { this.insertNode(this.root, newNode); } } insertNode(node, newNode) ...
[DE Wikipedia] SMAW Die SMAW (Shoulder-Launched Multipurpose Assault Weapon, deutsch: schultergestützte Mehrzwecksturmwaffe) ist eine amerikanische Panzerabwehrhandwaffe, die vom United States Marine Corps verwendet wird und eine Weiterentwicklung der israelischen B-300 darstellt. Sie wird von einem Infanteristen auf ...
null
null
null
[DE Wikipedia] George R. Lawrence George Raymond Lawrence (* 24. Februar 1868 in Ottawa, Illinois; † 15. Dezember 1938) war ein Fotograf aus Nordillinois. Er wuchs auf im Kankakee County und zog 1890 nach Chicago, wo er bei seinem Arbeitgeber eine Erfindung bezüglich Befestigung von eisernen Felgen auf Holzrädern mach...
null
null
null
null
Explain how a quicksort algorithm works.
Quicksort is an efficient comparison-based sorting algorithm that works by taking a pivot element and partitioning the list/array into two parts: elements smaller than the pivot element and elements larger than the pivot element. The quicksort algorithm then sorts both sublists recursively until the list is fully sorte...
null
Program a function in Python that will recognize if a given number is even.
def is_even(num):     if num % 2 == 0:         return True     else:         return False
null
To create a Reddit bot that scans a subreddit for new posts containing a specific string in the title, and sends a welcome message to new users who have not posted before, follow the steps below: 1. Install the PRAW library and import it into your Python script. 2. Import the datetime and sqlite3 libraries. 3. Define ...
#/u/GoldenSights import praw import time import datetime import sqlite3 '''USER CONFIGURATION''' APP_ID = "" APP_SECRET = "" APP_URI = "" APP_REFRESH = "" # https://www.reddit.com/comments/3cm1p8/how_to_make_your_bot_use_oauth2/ USERAGENT = "" #This is a short description of what the bot does. For example "/u/GoldenS...
null
Create a basic Python application to fetch data from an SQL database and display it in the console.
Not applicable
import sqlite3 conn = sqlite3.connect('example.db') cursor = conn.cursor() cursor.execute('SELECT * FROM users') rows = cursor.fetchall() for row in rows: print(row) conn.close()
null
पायथन में लिस्ट क्या होती है?
पायथन में लिस्ट एक क्रमबद्ध, परिवर्तनशील (mutable) संग्रह है जो विभिन्न प्रकार के तत्वों को रख सकती है, जैसे [1, 'a', 3.5]।
null
Create a Python program to generate a new dictionary from an existing dictionary given a set of key-pair values.
dct = { "name": "John", "age": 20, "species": "Human" } desired_pairs = {"name": "Alex", "species": "AI"}
dct = { "name": "John", "age": 20, "species": "Human" } desired_pairs = {"name": "Alex", "species": "AI"} # Generate the new dictionary new_dct = {**dct, **desired_pairs} print(new_dct) # Output: {'name': 'Alex', 'age': 20, 'species': 'AI'}
null
Create a function in JavaScript that takes a string as an argument and returns the number of times that string is repeated in the input string.
string = "HelloHello"
function countString(str) { let count = 0; for (let i = 0; i < str.length; i++) { if (str.substring(i, i + 5) == "Hello") { count++; } } return count; }
null
Suggest a way of preserving the order of elements in a JavaScript array using a set data structure.
A Set data structure can be used for preserving the order of elements in a JavaScript array. To achieve this, the Set can be initialized with an array which contains the elements in the desired order. When adding elements to the Set, they will be added in the same order as they appear in the original array. This ensure...
null
Edit the code to make sure that the sum is printed in the console.
function add(a, b) { let result = a+b; return result; }
function add(a, b) { let result = a+b; console.log('The sum is: ', result); return result; }
[DE Wikipedia] One Ok Rock/Diskografie Diese Diskografie ist eine Übersicht über die musikalischen Werke der japanischen Band One Ok Rock. Den Schallplattenauszeichnungen zufolge hat sie bisher mehr als 2,5 Millionen Tonträger verkauft. Ihre erfolgreichsten Veröffentlichungen sind die Studioalben Niche Syndrome, Jinse...
null
null
null
[EN Wikipedia] Ignas Budrys Ignas Budrys (1933, Grigaičiai – 1999) was a Lithuanian painter. See also List of Lithuanian painters References 1933 births 1999 deaths People from Vilnius District Municipality 20th-century Lithuanian painters
null
null
null
null
Generate a valid C++ code to implement a linked list with basic operations.
#include<iostream> using namespace std; class Node { public: int data; Node* next; }; class LinkedList { Node* head; public: LinkedList(){ head = NULL; } void append(int data) { Node* newNode = new Node; newNode->data = data; newNode->next = NULL; if (head == NULL) { head = newNode; } else { Node* temp = head; while (t...
[EN Wikipedia] Legson Kayira Legson Didimu Kayira ( – 14 October 2012) was a Malawian novelist. An ethnic Tumbuka, he received an education at Skagit Valley College, University of Washington and St Catharine's College, Cambridge. His early works focused on Malawi's rural life, while his later writings satirised the Ha...
null
null
null
null
Create a program in Python to detect outlier points within an array of data.
A numpy array of numerical data `[-6.2, 11.9, 5.7, 7.3, 2.5, 8.4, 14.0, 9.2, 7.4, 11.6]`
import numpy as np def detect_outlier(data): # Calculate the median and the inter-quartile range q75, q25 = np.percentile(data, [75 ,25]) iqr = q75 - q25 # Calculate the upper and lower bound lower_bound = q25 - (iqr * 1.5) upper_bound = q75 + (iqr * 1.5) # Calculate outlier points outlier_points...
null
Implement a function in Python that generates a random password with a minimum length of 10 characters.
No input
import random import string def generate_random_password(n=10): chars = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.choice(chars) for _ in range(n))
null
Write a C++ function that takes two strings as parameters and returns the length of the longest common subsequence between them.
string1 = "python" string2 = "honor"
#include <iostream> #include <algorithm> int longestCommonSubsequence(std::string s1, std::string s2) { int s1len = s1.length(); int s2len = s2.length(); int LCS[s1len+1][s2len+1]; for (int i = 0; i <= s1len; i++) { for (int j = 0; j <= s2len; j++) { if (i == 0 || j == 0) LCS[i][j] = ...
null
What is the result of x = 2 and y = 3 in this function, f(x,y) = x^3 + 2y^2?
The result of x = 2 and y = 3 in the function f(x,y) = x^3 + 2y^2 is 19.
[CS Wikipedia] SC Herisau SC Herisau (celým názvem: Schlittschuhclub Herisau) je švýcarský klub ledního hokeje, který sídlí v obci Herisau v kantonu Appenzell Ausserrhoden. Založen byl v roce 1942. Poslední účast v nejvyšší soutěži je datováno k sezóně 1997/98. Od sezóny 2017/18 působí v 1. lize, čtvrté švýcarské nejv...
null
null
null
null
How can we use the set() method to find the unique elements in a given list of integers in C#?
var listOfIntegers = [1,2,3,3,2,2,3]; var uniqueElements = new HashSet<int>(listOfIntegers); foreach (var element in uniqueElements) { Console.WriteLine(element); }
null
Write Python code to fill missing values in a Pandas dataframe with a given value.
import pandas as pd df = pd.DataFrame([ [8, 'B', 'G'], [28, 'B', np.nan], [22, np.nan, 'G'], [2, 'A', np.nan] ])
import pandas as pd df = pd.DataFrame([ [8, 'B', 'G'], [28, 'B', np.nan], [22, np.nan, 'G'], [2, 'A', np.nan] ]) df.fillna(value='NA', inplace=True)
null
Design a chaos-based Python program to simulate the predator–prey interactions between a fox and a rabbit.
Two species: fox and rabbit Number of rabbits: 10 Number of foxes: 3
import random def fox_and_rabbit_simulator(num_of_rabbits, num_of_fox): # Initialize the population rabbit_population = [num_of_rabbits] fox_population = [num_of_fox] # Simulation of Fox and Rabbit interaction for i in range(365): # For every day, the numbers of rabbi...