text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Generate a code snippet to calculate the sum of an array
arr = [1, 23, 4, 3, 5]
def summation(arr): sum = 0 for i in arr: sum += i return sum print(summation(arr)) # Output: 36
null
Using python, implement a method to find the longest common subsequence in two strings
str1 = "AGGTAB" str2 = "GXTXAYB"
def lcs(str1, str2, n, m): if n == 0 or m == 0: return 0 elif str1[n-1] == str2[m-1]: return 1 + lcs(str1, str2, n-1, m-1) else: return max(lcs(str1, str2, n, m-1), lcs(str1, str2, n-1, m))
null
Design a data structure for efficiently finding the closest input to a given input in a set of inputs.
An efficient data structure for finding the closest element to a given element in a set of elements is the KD Tree. The KD Tree is a space-partitioning data structure for organizing points in a k-dimensional space and taking advantage of their spacial locality. A KD Tree is a binary tree with each node containing a set...
[CS Wikipedia] Cesta do hlubin študákovy duše Cesta do hlubin študákovy duše je česká filmová komedie režiséra Martina (Maca) Friče z roku 1939 natočená v prostředí českého gymnázia. Film ukazuje komické příhody vyplývající z různosti studentů (Ladislav Pešek, Rudolf Hrušínský, František Filipovský, Richard Strejka, V...
null
null
null
null
Given a string, convert it to a list of words.
The quick brown fox jumped over the lazy dog
string = "The quick brown fox jumped over the lazy dog" words_list = string.split()
[EN Wikipedia] Alf Brown (footballer, born 1907) Alfred Brown (22 February 1907 – 1994) was an English professional footballer who played in the Football League for Mansfield Town, Northampton Town, Oldham Athletic. References 1907 births 1994 deaths English men's footballers Men's association football wing halves Eng...
null
null
null
null
Generate a script in Python that takes a list of numbers and prints out the smallest number in the list.
[5, 12, 3, 1, 8]
# Function to print the minimum number in a list def min_in_list(list): # Inialise minimum to first element in the list min = list[0] # Traverse through the list from 1st index # and update minimum if found for i in range(len(list)): if list[i] < min: min = list[i] ...
null
Write a Python program that multiplies all even numbers in a given list.
def multiplyEvens(numbers): # Initialize result result = 1 # Multiply all even elements for x in numbers: if x % 2 == 0: result = result * x return result # Driver code assert multiplyEvens([2, 3, 4, 5, 6]) == 48
null
Write MySQL code to create a table with the following columns
CREATE TABLE table_name ( id INT NOT NULL, first_name VARCHAR(255) NOT NULL, last_name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, age INT NOT NULL );
null
Default a neural network architecture to classify the handwritten digit from 0 to 9.
# Define the architecture def model(input_shape): model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=input_shape), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']...
null
Calculate the total sum of a given list using an accumulator pattern.
numbers = [2, 3, 4]
numbers = [2, 3, 4] total_sum = 0 # iterate through the list and add each element to the total sum for n in numbers: total_sum += n print(total_sum)
null
Write a function that collects elements from two given arrays and creates a new array.
array1 = [1, 2, 3] array2 = [4, 5, 6]
def collect(array1, array2): result = array1 + array2 return result
null
Write a Python function to detect patterns in a sequence of numbers.
sequence = [8, 5, 6, 4, 9, 3, 7, 8, 5, 6, 4, 9]
def detect_patterns(sequence): distinct_numbers = set(sequence) # Distinct sequence numbers # Initialize variables count_flag = 0 # Number of instances for a certain consecutive sequence max_seq_len = 0 # Max length of a consecutive sequence max_seq_number = 0 # The number which had the max consecutive seque...
null
Write a Python program to randomly select a number of elements from a list without any repeat
[1,2,3,4,5]
import random def random_select(arr, k): new_arr = random.sample(arr,k) return new_arr
null
Rewrite the code to be more concise and efficient.
def find_min(arr): min_val = float('inf') for i in arr: if i < min_val: min_val = i return min_val
def find_min(arr): return min(arr)
null
Create a program that takes in a numeric value, X, and prints all the positive divisors of that number.
X = 8
def print_divisors(x): divisors = [] for i in range(1, x + 1): if(x % i == 0): divisors.append(i) print(divisors)
null
How to reverse a list in C++?
You can reverse a list in C++ using the std::reverse algorithm. To reverse the list, pass the list as the first parameter and the beginning and end of the list as the second and third parameter, respectively. Alternatively, you can also reverse the list using a for loop and the operator [] to access each element of the...
null
Create a program in python to fulfill the following requirement:
Given a binary tree, print it in level order (also known as breadth-first search).
def levelOrder(node): # Base Case if node is None: return # Create an empty queue for level order tarversal queue = [] # Enqueue Root and initialize height queue.append(node) while(len(queue) > 0): # Print front of queue and remove it from queue ...
[DE Wikipedia] Byhleguhrer See Der Byhleguhrer See, , ist ein natürlich entstandener See im gleichnamigen Naturschutzgebiet in der Gemeinde Byhleguhre-Byhlen im Landkreis Dahme-Spreewald in Brandenburg. Der See ist Teil des Biosphärenreservats Spreewald. Der See liegt nördlich von Byhleguhre und südwestlich von Byhlen...
null
null
null
null
Write code to find the longest word in the given list and output it.
words_list = ["apple", "mango", "banana", "blueberry"]
def find_longest_word(lst): longest_word = "" for word in lst: if len(word) > len(longest_word): longest_word = word return longest_word
null
Change the following Java code to Swift.
public static int addTwoIntegers(int a, int b) { return a+b; }
func addTwoIntegers(a: Int, b: Int) -> Int { return a + b }
null
How would you design a system to store and access the stored data when a user makes a request?
To design a system to store and access the stored data when a user makes a request, we could use a client-server model, where the server provides the user with the requested data. The server would use a database to store the data, and when a user makes a request, the server would retrieve the requested data from the da...
null
Implement an algorithm in Python to find the GCD (Greatest Common Divisor) of two numbers
def gcd(a, b): if (a == 0): return b if (b == 0): return a if (a == b): return a if (a > b): return gcd(a-b, b) return gcd(a, b-a)
null
Create an AI agent in Python that learns to play Tetris and maximizes its score.
Not applicable
import gym import numpy as np from stable_baselines.common.policies import MlpPolicy from stable_baselines.common.vec_env import DummyVecEnv from stable_baselines import PPO2 # Training hyperparameters n_timesteps = 500000 # Create the environment env = gym.make('Tetris-v0') env = DummyVecEnv([lambda: env]) # Creat...
null
Debug the following code for finding the median of three numbers.
def find_median(a, b, c): if a > b: if b > c: return b elif a > c: return c else: return a elif b > c: return b elif a > c: return a else: return c
def find_median(a, b, c): # Calculate the maximum of the three numbers max_num = max(a, b, c) # Calculate the minimum of the three numbers min_num = min(a, b, c) # Calculate the median value as the sum of the three numbers minus the maximum and minimum median = a + b + c - max_num - min_num return median median_value =...
null
Implement a neural network for regression
import tensorflow as tf # create input layer inputs = tf.keras.Input(shape=(2,)) # create the first layer of the network with 16 neurons fc1 = tf.keras.layers.Dense(16, activation="relu")(inputs) # create the second layer of the network with 8 neurons fc2 = tf.keras.layers.Dense(8, activation="relu")(fc1) # create the ...
[EN Wikipedia] Muscari macrocarpum Muscari macrocarpum is a perennial bulbous flowering plant in the asparagus family Asparagaceae. It is one of a number of species known as Grape Hyacinth, in this case Yellow Grape Hyacinth. Originally from eastern Crete, Amorgos and south-west Turkey, where it grows in rocky places,...
null
null
null
null
Write a short class in Python that will print a custom message when created.
class CustomMessage: def __init__(self): print("This is a custom message!")
null
Write a PHP script to fetch data from an API.
<?php //Initialize cURL $curl = curl_init(); //Set cURL parameters curl_setopt_array($curl, array( CURLOPT_URL => "http://path.to/api/", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array("Content-type: application/json") )); //Execute cURL $response = curl_exec($curl); //Close cURL curl_close($curl); //Decode...
null
Create a Node.js server that responds with "Hello World!" when the URL "/" is accessed.
const http = require('http'); const server = http.createServer(function (req, res) { if(req.url == '/'){ res.writeHead(200); res.end('Hello World!'); } }); server.listen(3000);
null
Find any two numbers in an array such that their sum is equal to a given value.
array = [3, 4, 5, 6, 7, 8] value = 11
for i in range(len(array)): for j in range(i+1, len(array)): if array[i] + array[j] == value: print(array[i], array[j])
[CS Wikipedia] Oblastní hokejové soutěže 1955/1956 Československé oblastní soutěže ledního hokeje 1955/1956 byla třetí nejvyšší hokejovou soutěží na území Československa. Systém soutěže Soutěž se měla skládat ze 6 skupin po 4 účastnících. Ve skupinách se všechny kluby utkaly každý s každým (celkem 6 kol). Vítězové jed...
null
null
null
null
Edit a JavaScript function to perform an action based on another action in the code.
function myFunction(arr) { return arr.reverse(); }
function myFunction(arr) { arr.reverse(); return arr; }
null
Create a TensorFlow program to implement a multi-layer neural network
import tensorflow as tf # create the model model = tf.keras.models.Sequential() # add layers to the model model.add(tf.keras.layers.Dense(128, activation='relu')) model.add(tf.keras.layers.Dense(64, activation='relu')) model.add(tf.keras.layers.Dense(32, activation='relu')) model.add(tf.keras.layers.Dense(16, activatio...
null
Using the Java collections API, create a data structure such as a HashMap to store key-value pairs.
import java.util.HashMap; HashMap<String, Integer> myMap = new HashMap<>(); // adding key-value pairs to the HashMap myMap.put("Key1", 5); myMap.put("Key2", 8); myMap.put("Key3", 10); // retrieving values by keys int val1 = myMap.get("Key1"); int val2 = myMap.get("Key2"); int val3 = myMap.get("Key3"); // etc.
null
Create a function to print out the Fibonacci numbers starting from 0 to the nth number.
n = 7
def print_fibonacci(n): a = 0 b = 1 for i in range(n): print(a, end=' ') temp = a a = b b = temp + b # The output of the function would be # 0 1 1 2 3 5 8
null
Which sorting algorithm should you use for a nearly sorted array?
For a nearly sorted array, insertion sort is the best sorting algorithm because it only shifts elements up to one position and has a best-case time complexity of O(n) which makes it suitable for nearly sorted arrays.
[DE Wikipedia] Liste der Wappen im Kreis Nordfriesland Diese Liste zeigt die Wappen des Kreises Nordfriesland (Schleswig-Holstein) mit seinen Städten, Gemeinden und Ämtern. Kreiswappen Amtsfreie Städte und Gemeinden Ämter Amt Eiderstedt Amt Föhr-Amrum Amt Landschaft Sylt Amt Mittleres Nordfriesland Amt Nordsee-Treene ...
null
null
null
null
Create a Python program to generate a random password which satisfies the following criteria: • Must contain 8 – 16 characters. • Must contain upper and lowercase letters, numbers, and special characters such as *, #, @, etc
import random import string def generate_random_password(length): # String of characters to choose from chars = string.ascii_letters + string.digits + '!@#$%^&*()' # Randomly choose 4 characters from the list of characters random_chars = ''.join(random.choice(chars) for i in range(length)) # Gene...
[CS Wikipedia] Roger Bernard Roger Bernard (10. srpna 1907 – 10. srpna 1997) byl francouzský spisovatel a stylista. Psal v esperantu, jeho původní díla jsou básně Almenaŭ bukedeto a další původní dílo Raymond Schwartz, lia vivo kaj verkaro. Dále přeložil Bela la indiferentulo a Homa voĉo od Jeana Cocteaua, a komedie L...
null
null
null
null
Create a C# method that takes a string and counts the number of times a given character appears.
"Mississippi", 'i'
public static int countCharacter(string text, char character) { int count = 0; foreach (char c in text) { if(c == character) { count++; } } return count; }
[HI Wikipedia] हँस हंस एक पक्षी का नाम है। हंस पक्षी देखें। हंस जिसके संपादक राजेन्द्र यादव हैं। हंस ऐतिहासिक पत्रिका जिसके संपादक प्रेमचंद थे।
null
null
null
null
Write a Python program to add two matrices.
matrix1 = [[3, 5], [6, 2]] matrix2 = [[1, 2], [3, 4]]
def add_matrices(mat1, mat2): """ This function takes two 2D matrices and adds them, returning a new 2D matrix. """ output = [] for i in range(len(mat1)): row_m1 = mat1[i] row_m2 = mat2[i] row_sum = [] for j in range(len(row_m1)): row_sum.append(row_m1[j] + row_m2[j]) output.append(row_sum) return output result = add_m...
null
Create a Python program that accepts an integer and displays its factorial.
num=5
def factorial(num): result = 1 for i in range(1, num+1): result *= i return result n = int(input("Enter an Integer: ")) print(factorial(n))
null
Write a Node.js program to create a server.
const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}...
[CS Wikipedia] Socialistická republika Slovinsko Socialistická republika Slovinsko (zkráceně SR Slovinsko; slovinsky Socialistična republika Slovenija, SR Slovenija) byla socialistickou republikou, jež byla součástí Socialistické federativní republiky Jugoslávie. Součástí AVNOJské Jugoslávie se země stala v roce 1944....
null
null
null
null
Create a program to print a binary tree in reverse level order.
# Python program to print reverse level # order traversal # Binary Tree Node class Node: def __init__(self, data): self.data = data self.left = None self.right = None #reverse Level Order Traversal def reverseLevelOrder(root): # Base Case if root is None: return ...
[EN Wikipedia] Motor neuron diseases Motor neuron diseases or motor neurone diseases (MNDs) are a group of rare neurodegenerative disorders that selectively affect motor neurons, the cells which control voluntary muscles of the body. They include amyotrophic lateral sclerosis (ALS), progressive bulbar palsy (PBP), pse...
null
null
null
null
Create a class in C++ to store the rolling average of a stream of numbers.
class RollingAverage { private: int windowSize; int currentIndex; double total; std::vector<double> data; public: RollingAverage(int windowSize) : windowSize(windowSize) , currentIndex(0) , total(0.0) , data(windowSize) { for (int i = 0; i < windowSize; ++i) { data.push_back(0.0); } } void add(double value) { int prevI...
null
Design a function in Python to find the most repeated character in a string.
my_string="Hello world"
def most_repeated_character(my_string): counts = Counter(my_string) max_char = max(counts, key=counts.get) return max_char print("Most repeated character:", most_repeated_character(my_string))
null
Design and implement a Bubble Sort algorithm for sorting an array of numbers in Python.
[64, 34, 25, 12, 22, 11, 90]
def bubble_sort(l): for i in range(len(l)): for j in range(0, len(l)-i-1): if l[j] > l[j+1]: l[j], l[j+1] = l[j+1], l[j] # Test code l = [64, 34, 25, 12, 22, 11, 90] bubble_sort(l) print(l)
null
Write a shell command to switch to a given directory
Dirpath=/Users/username/Documents
cd /Users/username/Documents
null
Create a class in Python that calculates the total and average of 3 numbers.
class Calculator: def __init__(self, num1, num2, num3): self.num1 = num1 self.num2 = num2 self.num3 = num3 def total(self): return self.num1 + self.num2 + self.num3 def average(self): return self.total() / 3
null
Create a recursive algorithm to sum the numbers between 1 and n (inclusive).
n = 5
function recSum(n) { if (n === 1) return 1; return n + recSum(n-1); } // Usage console.log(recSum(5)); // 15
null
Create a program to subtract the two numbers from the following input.
first_num = 4 second_num = 2
first_num = 4 second_num = 2 # Program to subtract two numbers diff = first_num - second_num print(f"The difference between {first_num} and {second_num} is {diff}.")
null
Using any programming language, write a program which takes a number as an input and outputs the first two prime numbers after it.
7
def find_next_prime_numbers(num): """This function takes a number as an input and returns the first two prime numbers after it""" prime_numbers = [] # Increment num to the first prime number while not is_prime(num): num += 1 # Append num to prime_numbers (first prime after input) prime_numbers.append(num) # Increment n...
[HI Wikipedia] माथेरान माथेरान (Matheran) भारत के महाराष्ट्र राज्य के रायगढ़ ज़िले की कर्जत तालुका में स्थित एक नगर और हिल स्टेशन है। परिचय माथेरान मुंबई से मात्र ११० किलोमीटर दूर प्राकृतिक खूबसूरती से भरा छोटा-सा हिल स्टेशन है। यह पश्चिमी घाट पर्वत शृंखला में समुद्र तल से ८०० मीटर (२६२५ फीट) की उँचाई पर बसा है। मुंबई...
null
null
null
null
Which CSS style would you use to center align a <div> element?
div { margin: 0 auto; }
null
Write an SQL query to update the column 'name' to 'John' in the table 'employees'.
UPDATE employees SET name = 'John';
null
Compute the sum of two integers without using the "+" operator.
x = 5 y = 7
sum = x ^ y + (x & y) << 1 # using bitwise operators
null
Perform a linear search in a list named 'mylist' and return the index of the first occurrence of a target value.
mylist = [1, 2, 3, 4, 5, 6, 7] target = 4
def linear_search(mylist, target): for i in range(len(mylist)): if mylist[i] == target: return i return -1
null
Write a SQL query that selects a specific name from user table.
User table has columns (id, name, age)
SELECT name FROM user WHERE id = <specific id>
[CS Wikipedia] Amerika Amerika je souvislá pevnina na Zemi, která se skládá ze tří patrných částí – Severní Ameriky, Střední Ameriky a Jižní Ameriky. Severní a Jižní Amerika jsou považovány za dva samostatné kontinenty, zatímco Střední Amerika je považována za součást kontinentu Severní Ameriky. Z geomorfologického hl...
null
null
null
null
Create a class in Python that implements the __len__ method to return the length of a given string.
class StringLength: def __len__(self, string): return len(string)
null
Write a query in MySQL to display the top 3 highest salaries.
SELECT salary FROM employees ORDER BY salary DESC LIMIT 3
[DE Wikipedia] William Stukeley William Stukeley, FRS, FRCP, FSA, (* 7. November 1687 in Holbeach, Lincolnshire; † 3. März 1765 in London) war ein britischer Altertumsforscher („Antiquar“) aus Yorkshire. Leben Er wurde in Stukeley Hall in Holbeach in Lincolnshire als Sohn eines Rechtsanwalts geboren. Er erhielt seinen...
null
null
null
null
What data structure could you use to keep track of the list of items purchased by each customer?
A dictionary is a suitable data structure for keeping track of the list of items purchased by each customer. The key would be the customer name and the value would be a list of items purchased by the customer.
[EN Wikipedia] Islands Regulation of the Netherlands Antilles The Islands Regulation of the Netherlands Antilles (, ERNA; , RIAH) described the autonomy of the island territories of the Netherlands Antilles. It was enacted on 3 March 1951 by royal decree and remained in force, in a consolidated form, until the dissolu...
null
null
null
null
Design a SQL query to get the salary of employee who has the maximum salary in each department.
SELECT emp.name, emp.salary FROM employees emp JOIN (SELECT dept, MAX(salary) max_salary FROM employees GROUP BY dept) temp ON emp.dept = temp.dept AND emp.salary = temp.max_salary;
null
Create a c++ class to store data for a student including their name, age, and address.
class Student { private: string name; int age; string address; public: void setName(string name); void setAge(int age); void setAddress(string address); string getName(); int getAge(); string getAddress(); };
null
Create a function in R to get the last seven characters of a string.
substr_last7 <- function(string) { return (substr(string, nchar(string)-6, nchar(string))) }
[CS Wikipedia] Anderson Paak Anderson Paak, rodným jménem Brandon Paak Anderson, (* 8. února 1986) je americký rapper a zpěvák. Hudbu začal produkovat ze svého domova v době, kdy docházel na střední školu. Později hrál na bicí v kostele, kde potkal svou budoucí manželku. Jejich manželství se po několika letech rozpadl...
null
null
null
[EN Wikipedia] Thomas Mathis (sport shooter) Thomas Mathis (born 25 April 1990) is an Austrian sports shooter. He competed in the men's 50-metre rifle prone event at the 2016 Summer Olympics. References External links 1990 births Living people Austrian male sport shooters Olympic shooters for Austria Shooters at the 2...
null
null
null
null
Create a function in C to replace all the given characters in a string with a given character.
String1 = "Hello World", Character1 = 'o', Character2 = '*'
char *replaceCharacter(char *str, char o, char *) { int i = 0; while (str[i] != '\0') { if (str[i] == o) str[i] = *; i++; }return str; } // Driver Program int main() { char str[] = "Hello World"; printf("%s", replaceCharacter(str, 'o', '*')); return 0; }
null
Write a Python program to print a Welcome message for the user.
Username: John
print("Welcome John!")
null
Suggest a Python code for sorting a list of dictionaries based on ascending order of a given key.
original_list = [{'name':'John', 'age': 25}, {'name':'Jim', 'age': 18}, {'name':'Lisa', 'age': 20}]
def sort_by_age(original_list): Return sorted(original_list, key = lambda i: i['age'])
null
In CSS, how can the width of a div element be set to 100% of its parent's width?
In CSS, the width of a div element can be set to 100% of its parent's width by using the "width: 100%;" property.
[EN Wikipedia] WRGN WRGN (88.1 FM) is a Christian radio station licensed to Sweet Valley, Pennsylvania, serving Northeastern Pennsylvania. The station is owned by Good News for Life. WRGN's programming includes Christian Talk and Teaching and Christian music. Christian Talk and Teaching shows heard on WRGN include; In...
null
null
null
[CS Wikipedia] Dietrich Ziemssen Dietrich Ziemssen (26. srpna 1911–17. března 1978) byl důstojník Waffen-SS v hodnosti SS-Obersturmbannführer (podplukovník) za druhé světové války. Mimo jiné byl držitelem německého kříže ve zlatě. Narodil 26. srpna roku 1911 v Heilbronnu v Württembersku. Absolvoval pět tříd lidové ško...
null
null
null
null
Compose a code in Python that counts the number of positive integers in a list.
numbers = [1, -2, 3, -4, 5]
def count_positive_numbers(numbers): count = 0 for num in numbers: if num > 0: count += 1 return count
null
Rewrite the following code so that it is easier to read and understand.
def is_string_palindrome(str): revstr=str[::-1] if revstr==str: return true else: return false
def is_string_palindrome(str): reverse_str = str[::-1] if reverse_str == str: return True else: return False
null
Develop a function in Python that sorts a dictionary by value in descending order.
dictionary = {'a': 10, 'b': 20, 'c': 5}
def sort_dict_by_value(dict): sorted_dict = dict(sorted(dict.items(), key = lambda kv: kv[1], reverse = True)) return sorted_dict sorted_dict = sort_dict_by_value(dictionary) print(sorted_dict)
[DE Wikipedia] Liste der Monuments historiques in Puyrolland Die Liste der Monuments historiques in Puyrolland führt die Monuments historiques in der französischen Gemeinde Puyrolland auf. Liste der Bauwerke |} Liste der Objekte |} Literatur Le Patrimoine des Communes de la Charente-Maritime. Flohic Editions, Band 2, ...
null
null
null
[EN Wikipedia] String bag A string bag, net bag, or mesh bag is an open netted bag. Mesh bags are constructed from strands, yarns, or non-woven synthetic material into a net-like structure. String bags are used as reusable shopping bags and as packaging for produce. History Bags of net-like material have been used by ...
null
null
null
null
In MongoDB, what does the command 'db.collection.aggregate()' do?
The aggregate command in MongoDB is used to group values from multiple documents together and perform a variety of aggregate operations such as computing averages, sums of values, finding distinct values, etc. It takes an array of aggregation pipeline stages as its first argument and outputs an array of computed result...
null
Develop a Python program to find the maximum sum of a subarray of size K.
arr = [100, 200, 300, 400] K = 2
def maximum_sum_subarray(arr, K): max_sum = 0 window_sum = 0 # Compute the window sum for i in range(K): window_sum += arr[i] # Replace max_sum if current window sum is greater max_sum = max(window_sum, max_sum) # Slide the window for i in range(K, le...
null
Write a Python program that calculates the monthly payments of a loan given its amount, interest rate, and term.
Amount = 2000, interest rate = 10%, term = 3 years
def calculate_monthly_payment(amount, interest, term): monthly_interest_rate = interest / 12 number_of_payments = term * 12 monthly_payment = (amount * monthly_interest_rate) / (1 - pow((1 + monthly_interest_rate), (-number_of_payments))) return monthly_payment amount = 2000 interest_rate = 10 term = 3 p...
null
Format this JSON data as per a specific schema.
{ "name": "John", "age": 20, "height_cm": 178, "weight_kg": 73 }
{ "name": "John", "age": 20, "info": { "height_cm": 178, "weight_kg": 73 } }
null
Write a Python code snippet to calculate the sum of the first 100 prime numbers.
def is_prime(num): for i in range(2, num): if num % i == 0: return False return True prime_sum = 0 count = 0 num = 2 while count < 100: if is_prime(num): prime_sum += num count += 1 num += 1 print(prime_sum)
null
Create an object that adds two integers and returns their sum.
const adder = { add: (a, b) => a + b };
null
Write a code to create a FizzBuzz game, that prints the numbers from 1 to 50, replacing all the numbers divisible by 3 with the word "Fizz" and the numbers divisible by 5 with the word "Buzz".
""" Write a code to create a FizzBuzz game """ def fizz_buzz(): for i in range(1, 51): if i % 3 == 0 and i % 5 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i) if __name__ == '__main__': fizz_buzz()
[DE Wikipedia] Wycoller Beck Der Wycoller Beck ist ein Wasserlauf in Lancashire in England. Er entsteht aus dem Zusammenfluss von Smithy Clough und Turnhole Clough südlich des Ortes Wycoller, fließt in nördlicher Richtung und bildet bei seinem Zusammentreffen mit dem River Laneshaw das Colne Water. Weblinks Gewässer i...
null
null
null
null
Write code using Python to generate a random password of given length.
Length: 8
import string import random def generate_password(length): chars=string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.choice(chars) for i in range(length)) print(generate_password(8))
null
Design a function in Python that takes a list of strings as input and returns a new list of strings that contains only the string with the longest length.
['cat', 'kitten', 'puppy']
def get_longest_strings(string_list): longest_strings = [] longest_length = 0 for string in string_list: if len(string) > longest_length: longest_length = len(string) for string in string_list: if len(string) == longest_length: longest_strings.append(string) ...
null
Add a class attribute to the given Python class.
class Student: def __init__(self, name, age): self.name = name self.age = age
class Student: def __init__(self, name, age): self.name = name self.age = age self.grade = None
[DE Wikipedia] Deutsche Gesellschaft für Klinische Neurophysiologie und Funktionelle Bildgebung Die Deutsche Gesellschaft für Klinische Neurophysiologie und Funktionelle Bildgebung (DGKN) e. V. ist eine medizinische Fachgesellschaft für Ärzte und Wissenschaftler auf dem Gebiet der klinischen und experimentellen Neurop...
null
null
null
[DE Wikipedia] Delicate Delicate steht für: Delicate (Taylor-Swift-Lied) Delicate (Terence-Trent-D’Arby-Lied) Delicate Arch, Felsbogen in den USA Siehe auch Delicata Delikat Violently Delicate The Delicate Prey Delicate Sound of Thunder
null
null
null
[HI Wikipedia] विशनसर विशनसर (Vishansar, ) भारत के जम्मू व कश्मीर राज्य के गान्दरबल ज़िले के सोनमर्ग क़स्बे के पास स्थित एक स्वच्छ पर्वतीय झील है। ३,७१० मीटर पर स्थित यह झील प्रसिद्ध किशनगंगा नदी का स्रोत है। इसकी लम्बाई १.० किमी और चौड़ाई ०.६ किमी है। विवरण विशनसर श्रीनगर से २०० किमी पूर्वोत्तर में और सोनमर्ग से २० क...
null
null
null
null
Implement a priority queue.
class PriorityQueue(): def __init__(self): self.elements = [] def is_empty(self): return len(self.elements) == 0 def enqueue(self, item, priority): self.elements.append((item, priority)) def dequeue(self): max_priority_index = 0 for index, element in enumerate(self.elements): if element[1] > self.elements[max_priority_...
[HI Wikipedia] रूस के नगरों की सूची यह सूची रूस के नगरों की है। 2002 रूसी जनगणना के आंकड़ों के अनुसार, रूस में शहरों और कस्बों की कुल संख्या 1,108 हैं। मास्को लेनिनग्राद सेंट पीट्सबर्ग वोल्गाग्राद रूस के नगर
null
null
null