text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Output the first 20 prime numbers
The first 20 prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71.
null
Edit this HTML code to add the Google Font “Roboto”.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My First Web Page</title> </head> <body> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet"> <title>My First Web Page</title> <style> body { font-family: 'Roboto', sans-serif; } </style> </head> <body> </body> </html>
[EN Wikipedia] Odessa Filmworks Odessa Filmworks is a Canadian film production company, based in Ottawa, Ontario founded by film director/producer Lee Demarbre. Odessa produced the internationally distributed feature film Jesus Christ Vampire Hunter. Productions 1998: Harry Knuckles (short film, trailer spoof) 1999: H...
null
null
null
null
Develop a program to delete all nodes of a linked list at a given position.
[3, 9, 1, 5], position to delete: 2
# Node class class Node: def __init__(self, data): self.data = data self.next = None # Linked List class class LinkedList: def __init__(self): self.head = None # function to add a node at the given position def deleteNode(self, pos): # if list is empty if self.head == None: return # store head node temp = self.head # i...
[HI Wikipedia] मलिक मलिक (मह्ल: މަލިކު ; ) भारतीय द्वीपसमूह लक्षद्वीप का सबसे दक्षिण में स्थित एटोल है। प्रशासकीय दृष्टि से यह केन्द्रशासित प्रदेश लक्षद्वीप का कस्बा है। यहां मौसम बेधशाला एवं प्रकाश स्तम्भ स्थित है। शब्द व्युत्पत्ति मलिक (मिनिकॉय) का प्राचीन नाम महिलादू था जो महिला और दू (द्वीप) की सन्धि से बना है अर्...
null
null
null
null
Design a "rock, paper, scissors" game using Python.
""" Design a "rock, paper, scissors" game using Python. """ import random OPTIONS = ["rock", "paper", "scissors"] def play_game(): # Player selection print("Choose your weapon: rock, paper, or scissors") player_choice = input().lower() # Computer selection computer_choice = random.choice(OPTIONS...
null
Create a feature in Python to extract the category information from a given URL.
No input
def extract_category_from_url(url): # Extract the hostname from the URL hostname = urlparse(url).hostname # Split the hostname on '/' categories = hostname.split('/') return categories
null
Implement the merge sort algorithm to sort a given array ascending.
given_array = [7,9,3,8,1]
def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] #calling merge sort function on left and right arrays merge_sort(L) merge_sort(R) i = j = k = 0 # Copying data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i+=1 else: arr[k] = R[j] j+=1 k+=...
[EN Wikipedia] Gmina Kozienice Gmina Kozienice is an urban-rural gmina (administrative district) in Kozienice County, Masovian Voivodeship, in east-central Poland. Its seat is the town of Kozienice, which lies approximately south-east of Warsaw. The gmina covers an area of , and as of 2006 its total population is 30,2...
null
null
null
null
Create a SQL query to count the total number of movies for every genre in the database.
SELECT genre, COUNT(*) as total_movies FROM Movies GROUP BY genre
[EN Wikipedia] Teresa and Maria Milanollo Teresa Milanollo (1827–1904) and her younger sister, Maria Milanollo (1832–1848), were Italian violin-playing child prodigies who toured Europe extensively to great acclaim in the 1840s. After Maria died at age 16, Teresa, who was also a composer, had a long solo career. The n...
null
null
null
[EN Wikipedia] Al Lewis (singer-songwriter) Al Lewis (born 1984 in Pwllheli, Wales) is a Welsh singer and songwriter. He became known in the Welsh language media after his song came second in the Cân i Gymru contest in 2007. Biography Lewis attended Ysgol y Creuddyn in Conwy, where he formed a cover band called Bluewo...
null
null
null
[HI Wikipedia] नॉरबॉत्तेन लैन नॉरबॉत्तेन लैन (स्वीडी: Norrbottens län, अंग्रेज़ी: Norrbotten) स्वीडन का एक लैन है। 'लैन' स्वीडन का उच्च-स्तरीय प्रशासनिक विभाग होता है, जिसे कभी-कभी 'काउंटी' भी कहते हैं। इन्हें भी देखें स्वीडन की काउंटियाँ सन्दर्भ नॉरबॉत्तेन लैन स्वीडन की काउंटियाँ स्वीडन
null
null
null
null
Write a function in Python to sum all the positive integers of n numbers.
[1,2,3,4,5]
def sum_numbers(arr): total = 0 for num in arr: if num > 0: total += num return total print(sum_numbers([1,2,3,4,5])) # 15
null
Write an algorithm in Python that takes a string of characters and prints out the frequency of each character.
"Hello, world!"
""" Write an algorithm in Python that takes a string of characters and prints out the frequency of each character. """ def count_frequency(text): freq = {} for c in text: if c in freq: freq[c] += 1 else: freq[c] = 1 for key,value in freq.items(): print(key +...
null
Build a MapReduce job with Hadoop to find the 99th percentile of a given data set.
//Mapper Code import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class MapperClass extends Mapper<LongWritable, Text, Text, LongWritable> { LongWritable one = new LongWritable(1); Text data = new Text(); @Override pro...
null
Write a JavaScript program to create a class 'Shape' and create an object 'circle' of this class.
class Shape { constructor() { this.type = "Shape"; } } let circle = new Shape(); circle.type = "Circle"; console.log(circle.type);
null
Write a Python program to validate a given telephone number.
import re def validate_telephone_number(number): pattern = '^[0-9]{10}$' if re.match(pattern, number): return True else: return False
null
Create a Python code snippet to identify the root cause of a Software Bug.
def find_causes(data): # identify the root cause of the bug causes = set() for line in data: for cause in line.get('causes', []): causes.add(cause) # filter insignificant causes causes = [cause for cause in causes if cause not in insignificant_causes] return causes
null
Modify the given Python code to calculate the sum of the given list and print the output.
list = [1,2,3,4,5]
def sumList(list): sum = 0 for i in list: sum = sum + i return sum print(sumList(list))
null
Write a function in Python to sort this dictionary by values.
my_dict = {"Jerry": 10, "Marcus": 3, "Hanna": 5}
def sort_dict_by_values(d): sorted_dict = dict(sorted(d.items(), key=lambda x: x[1])) return sorted_dict print(sort_dict_by_values(my_dict)) # Output: {'Marcus': 3, 'Hanna': 5, 'Jerry': 10}
null
Develop a C program for swapping two variables.
#include <stdio.h> void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } int main() { int x = 10, y = 20; // Call swap function to swap 'x' and 'y' swap(&x, &y); printf("x = %d, y = %d", x, y); return 0; }
null
Create a python script that takes 2 arguments - an array and an integer - and prints the sum of the array multiplied by the integer.
Array: [3, 5, 8] Integer: 5
def sum_arr(arr, num): total = 0 for i in arr: total += i total *= num return total # Output 95
null
Create a program in Python that prints out the first 10 prime numbers.
"<noinput>"
import math def is_prime(n): if n == 1: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True prime_nums = [] for i in range(2, 1000): if is_prime(i): prime_nums.append(i) if len(prime_nums) == 10: ...
[HI Wikipedia] शेरपुर शेरपुर (Sherpur) या शेरपुर उपरवार (Sherpur Uparwar) भारत के उत्तर प्रदेश राज्य के भदोही ज़िले (संत रविदास नगर ज़िले) के डीघ मंडल में स्थित एक गाँव है। यह गंगा नदी के किनारे स्थित है। जनसांख्यिकी भारत की 2011 जनगणना के अनुसार इस गाँव की आबादी 383 थी जिसमे महिलाये 160 और पुरुष 223 थे। इन्हें भी देख...
null
null
null
null
Create a Kubernetes pod setup that publishes a tweet every 5 minutes.
Not applicable
apiVersion: v1 kind: Pod metadata: name: tweet-publisher spec: containers: - name: tweet-publisher image: <INSERT_PUBLIC_PULLABLE_IMAGE_PATH_HERE> command: - sh - -c - 'crontab -lcrontab && while true; do python publish-tweet.py && crontab -l | { cat; echo "*/5 * * * * python...
null
Create multiple classes in Java with the provided input.
class Player { String name; int age; String club; String position;
class Player { String name; int age; String club; String position; // Constructors public Player(String name, int age, String club, String position) { this.name = name; this.age = age; this.club = club; this.position = position; } // Getters and Setters public String getName() { return this.name; } public void setName(...
null
Create a linear regression model in Python to predict house prices based on geographic features such as rooms, square footage, and zip code.
Rooms: 3 Square Footage: 2000 Zip Code: 92101
import pandas as pd import numpy as np data = pd.DataFrame({'Rooms': [3], 'Square_Footage': [2000], 'Zip_Code': [92101] }) # Split the input data into independent and dependent variables X = data.iloc[:, :-1] y = data.iloc[:, -1] # Build the model from sklearn.linear_model import LinearRegression regressor = Lin...
null
Generate a python program to alphabetically sort the following list.
["Paul", "John", "George", "Ringo"]
my_list = ["Paul", "John", "George", "Ringo"] my_list.sort() print(my_list)
null
Write a function in Python to print out the most common words in a given text.
This is a test text. It can be used to test a function for the most common words.
def most_common(text): text_list = text.lower().split() results = {} for word in text_list: if word not in results: results[word] = 1 else: results[word] += 1 sorted_words = sorted(results.items(), key=lambda kv: kv[1], reverse=True) for word, count in sorted_words[:10]: print(word, count)
[EN Wikipedia] Jenštejn Jenštejn () is a municipality and village in Prague-East District in the Central Bohemian Region of the Czech Republic. It has about 1,500 inhabitants. Administrative parts The village of Dehtáry is an administrative part of Jenštejn. Etymology The original name of the village and the local cas...
null
null
null
null
Declare a C++ structure that stores data about employees including their name and employee id.
struct employee { string name; int id; };
null
Write a MySQL query to select the names and phone numbers of people whose age is greater than 30
SELECT Name, Phone FROM People WHERE Age > 30
[CS Wikipedia] Žulebino (stanice metra v Moskvě) Žulebino () je stanice moskevského metra na Tagansko-Krasnopresněnské lince. Stanice byla zprovozněna spolu s celým úsekem Vychino - Žulebino. Nachází se mezi stanicemi Lermontovskij prospekt a Kotělniki, do 21. září 2015 byla konečnou stanicí linky. Je pojmenována po p...
null
null
null
null
Insert a code line in the existing program to fix a syntax error.
int main() { printf("Hello World!); }
int main() { printf("Hello World!"); // added missing closing quotation mark }
null
Write a function to start a timer with the specified duration.
def start_timer(duration): start_time = time.time() end_time = start_time + duration while time.time() < end_time: time.sleep(1) print("Timer finished!")
null
Create a Python dictionary with three elements and print the key-value pairs.
my_dict = { 'name': 'John', 'age': 30, 'city': 'New York' } for key, value in my_dict.items(): print(f'{key}: {value}')
null
Create a basic query using two variables.
sky, blue
SELECT * FROM table WHERE sky = 'blue';
null
Write a script in Java for printing the first n Fibonacci numbers.
public class Fibonacci { static int fib(int n) { int f[] = new int[n+2]; // 1 extra to handle case, n = 0 int i; /* 0th and 1st number of the series are 0 and 1*/ f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { f[i] = f[i-1] + f[i-2]; } return f[n]; } public static void main (String args[]) { int n = 5; System.out.print...
null
Build a python program to search for an element in a matrix
A matrix of size 3x4 and search for the element 6
def searchMatrix(mat, ele): row = len(mat) col = len(mat[0]) # Traverse the matrix i = 0 j = col - 1 while i < row and j >= 0: if mat[i][j] == ele: return True if mat[i][j] > ele: j -= 1 else: i += 1 return...
null
Write a Python program to convert a given list to a dictionary with each item as a key-value pair.
list = [("a", 1), ("b", 2), ("c", 3), ("d", 4)]
list = [("a", 1), ("b", 2), ("c", 3), ("d", 4)] d = dict(list) print(d) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
null
Modify the following Python code to generate more random numbers.
import random x = random.randint(1, 10)
import random x = random.randint(1, 10) y = random.randint(1, 10) z = random.randint(1, 10)
null
Write a C++ function that takes an array of strings and prints them out in reverse order.
myArray = ["cat","apple","dog"]
void print_reverse (string arr[], int size) { if (size > 0) { print_reverse (arr, size - 1); cout<<arr[size-1]<<" "; } }
null
Generate an array of length n with random numbers in the range 0 - 100
import random def gen_num_arr(n): output = [] for i in range(n): output.append(random.randint(0, 101)) return output
null
Generate a list of 10 random numbers between 0 and 500 in Python.
import random numbers = [random.randint(0,500) for i in range(10)] print(numbers)
null
Write a Python program to generate a simple Maze game where the player starts at position (0,0) and needs to find the goal position (4,4) by navigating the maze.
Not applicable
# Maze Class class Maze: # Maze constructor def __init__(self): self.n = 5 self.maze = [[ 1, 0, 0, 0, 1 ], [ 1, 1, 1, 0, 1 ], [ 0, 0, 0, 0, 0 ], [ 0, 1, 1, 1, 1 ], [ 0, 1, 0, 0, 1 ]] # functio...
[CS Wikipedia] Svatý Jan pod Skalou Svatý Jan pod Skalou ( je obec ve Středočeském kraji, okrese Beroun, asi 30 km JZ od Prahy a necelých 5 km východně od Berouna. Leží v srdci Chráněné krajinné oblasti Český kras a společně s Karlštejnem a starodávným Tetínem patří mezi nejzajímavější turistické lokality okresu. Žije...
null
null
null
null
Write a function in Python for sorting a list of objects by an attribute 'name'.
list_of_objects = [{"name": "John", "age": 35}, {"name": "Liz", "age": 25}, {"name": "Max", "age": 28}]
def sort_by_name(lst): return sorted(lst, key=lambda item: item["name"])
null
Write a function in Python that takes in two strings and concatenates them together with a space in between.
def my_concat(string1, string2) return string1 + ' ' + string2
[CS Wikipedia] Literatura Literatura (z latinského littera, písmeno) neboli písemnictví, někdy také slovesnost, je v širším slova smyslu souhrn všech písemně zaznamenaných textů, v moderních definicích někdy včetně ústně tradovaných projevů (například ústní lidová slovesnost). Kromě umělecké literatury se k ní v tomto...
null
null
null
[DE Wikipedia] Turnhole Clough Der Turnhole Clough ist ein Wasserlauf in Lancashire, England. Er entsteht an der Nordseite des Boulsworth Hill aus dem Zusammenfluss von Butter Leach Clough und Stack Hill Clough. Er fließt in nördlicher Richtung und bildet bei seinem Zusammentreffen mit dem Smithy Clough den Wycoller B...
null
null
null
null
Write a Python program that takes in a list of values and returns the maximum value.
[1, 5, 2, 9, -2]
def get_maximum_value(lst): return max(lst) print(get_maximum_value([1, 5, 2, 9, -2]))
[CS Wikipedia] Jon Hamm Jonathan Daniel „Jon“ Hamm (* 10. března 1971, St. Louis, Missouri, Spojené státy americké) je americký herec a režisér. Kariéra Po většinu devadesátých let žil v Los Angeles jako neúspěšný herec, ale později se objevil v řadě televizních seriálů jako Providence, The Division, What About Brian ...
null
null
null
null
Construct a python program to copy an array.
def copyArray(arr): res = [] for i in range(len(arr)): res.append(arr[i]) return res
null
Create a program in Python that will take in a list of strings and print out each unique string in the list.
mylist = ["Hello", "World", "Hello", "WDI", "Class"]
uniquelist = [] for string in mylist: if string not in uniquelist: uniquelist.append(string) print(uniquelist)
null
What is the best way to store user input in JavaScript?
The best way to store user input in JavaScript is to use the localStorage object. The localStorage object is part of the web storage API and provides a way to store data on the user's computer. The data is stored in key/value pairs and is accessible even after the browser is closed and reopened. The syntax to set the v...
null
Compile this Java code to run on a JVM.
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world!"); } }
javac HelloWorld.java
null
Apply K-means clustering to a 3-dimensional dataset given a certain number of clusters.
Number of Clusters = 4
from sklearn.cluster import KMeans # prepare the data X = [... the 3-dimensional dataset ...] # define the clustering model kmeans_model = KMeans(n_clusters=4) # fit the model kmeans_model.fit(X) # get the cluster centers cluster_centers = kmeans_model.cluster_centers_ # get the labels for each point labels = kmeans_mo...
null
Create a function in Python that takes a sentence as an argument and returns the formatted sentence with the first letter of each word capitalized.
sentence = "this is a sentence"
def capitalize_sentence(sentence): words = sentence.split() capitalized_words = [word.capitalize() for word in words] return " ".join(capitalized_words)
null
Write a Python program to identify all words in the given paragraph.
paragraph = "Thomas Jefferson was an American statesman, diplomat, lawyer, architect, philosopher and Founding Father who served as the third president of the United States from 1801 to 1809."
paragraph = "Thomas Jefferson was an American statesman, diplomat, lawyer, architect, philosopher and Founding Father who served as the third president of the United States from 1801 to 1809." words = paragraph.split() print(words) # ["Thomas", "Jefferson", "was", "an", "American", "statesman,", "diplomat,", "lawyer,...
null
Given a list of integers, write a program to convert it into a list of strings.
integers = [1, 2, 3, 4]
def convert_to_string(integers): string_list = [] for item in integers: string_list.append(str(item)) return string_list
[HI Wikipedia] निर्वात अपशिष्ट संग्राहक वाहन निर्वात अपशिष्ट संग्राहक वाहन या मलजल टैंकर एक निर्वात ट्रक है जिसका प्रयोग किसी नाबदान या मलजल टैंक को निर्वात द्वारा साफ करने के लिए किया जाता है। इस प्रकार यह नाबदान से अपजल को निकाल कर उसका अन्यत्र निपटान करता है। वाणिज्यिक विमानन और अन्य उद्योगों में, इस प्रकार के वाहन...
null
null
null
null
Add the two given integer variables using a Python script.
a = 5 b = 10
sum = a + b print(sum)
null
Write a function that takes an array of integers and multiplies them together.
arr = [3, 5, 4]
def multiplyArray(arr): result = 1 for x in arr: result = result * x return result
null
Write a function in PHP that takes in two integers and prints the smallest one.
$num1 = 5; $num2 = 10;
function smallest($num1, $num2) { if ($num1 < $num2) { echo "$num1 is smaller"; } else if ($num2 < $num1) { echo "$num2 is smaller"; } else { echo "Both numbers are equal"; } }
null
How can you check the memory used by a Python object?
You can use the sys module’s "getsizeof()" function to check the memory used by an object. The getsizeof() method returns the memory size of the specified object in bytes. For example, sys.getsizeof(data) will return the size of the data object in bytes.
null
Please provide Python code to print out all the prime numbers in a list of numbers.
list_of_numbers = [2, 3, 4, 5, 6, 7, 8, 9, 11]
def is_prime(num): for i in range(2, num): if num % i == 0: return False return True list_of_numbers = [2, 3, 4, 5, 6, 7, 8, 9, 11] for i in list_of_numbers: if is_prime(i): print(i)
null
Develop a data analysis tool in Python that finds the correlation between two variables in a dataset.
Not applicable
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Load the data set data = pd.read_csv('./data.csv') # Get the variables to analyze X = data['variable1'] Y = data['variable2'] # Calculate the correlation correlation = np.corrcoef(X, Y) # Print out the result print('The correlation between Var...
null
Find the missing number in the following array: [16, 3, 2, 11, 15, 5, 4, 14].
The missing number is 12.
null
Given a sorted array of size n, create a program to return the kth smallest element.
def findKthSmallestElement(arr, n, k): # To return kth smallest element in # the given array return arr[k-1]
[CS Wikipedia] Golem Golem (: גֹּלֶם) je v židovské mystice člověkem oživená socha. Takových golemů je známo poměrně dost. Většina lidí si Golema představuje jako oživenou sochu v podobě člověka, ale je to postava mytická, a proto může mít různé podoby. Slovo golem ve tvaru galmi (גָּלְמִי, doslova „golema mého“, v če...
null
null
null
[CS Wikipedia] Zdeněk Janík Zdeněk Janík (7. října 1923, Brno – 3. dubna 2022, Praha) byl český básník. Původním povoláním byl pedagog a redaktor; za normalizace pracoval jako korektor. Byl členem Obce spisovatelů, PEN klubu a Syndikátu novinářů. Zdeněk Janík publikoval taktéž pod pseudonymem Tomáš Šobr. Jeho krédem b...
null
null
null
null
Provide an example of a query to find all users whose age is 16 or over.
SELECT * FROM Users WHERE age >= 16;
[CS Wikipedia] Josef Vrba Josef Vrba je bývalý český fotbalista, obránce a záložník. Fotbalová kariéra V československé lize hrál za SK Plzeň. Nastoupil ve 141 ligových utkáních. Gól v lize nedal. Ligová bilance Literatura JEŘÁBEK, Luboš: Český a československý fotbal: lexikon osobností a klubů 1906-2006, Praha, Grada...
null
null
null
[EN Wikipedia] Lillemor Rachlew Ingebjørg Lillemor Rachlew (née Enger; 7 January 1902 – 14 May 1983) was a Norwegian polar explorer. She was one of four Norwegians who were the first women to set foot on the Antarctic mainland. After their landing in 1937 the Four Ladies Bank in Prydz Bay was named after them. On an e...
null
null
null
null
Optimize this Python code to reduce its run-time complexity.
def foo(l1, l2): result = [] for i in l1: for j in l2: result.append(i + j) return result
def foo(l1, l2): result = [i + j for i in l1 for j in l2] return result
null
Analyze the following code and explain what it does: def func(n): if n == 0: return 0 else: return n + func(n - 1)
This code implements a recursive function to compute the sum of numbers from 1 to n. Specifically, the base case is when n is 0, and the recursive case is when n is greater than 0. In the recursive case, the function will call itself with n-1 as the argument, and then adds n to the result of that call. Thus, each recur...
null
Create a for loop to traverse a list and print each element in the list in sequence.
list_to_traverse = [1,2,3,4,5]
for item in list_to_traverse: print(item)
null
Complete the following code to delete the item at a given index from a list.
index = 4 list_items = [2, 3, 4, 5, 6, 7, 8]
""" Complete the following code to delete the item at a given index from a list """ index = 4 list_items = [2, 3, 4, 5, 6, 7, 8] # remove the item at index 4 del list_items[index] # print the list print(list_items)
null
Create a function in Python to check if a given string contains two of the same characters next to each other.
def check_for_two_same_chars(string): for i in range(len(string)-1): if string[i] == string[i+1]: return True return False
[CS Wikipedia] Dopady globálního oteplování Jako dopady globálního oteplování jsou označovány mnohé změny ovlivňující lidstvo i Zemi. Globální oteplování je pozorovaný a předpokládaný trend směrem k vyšší globální průměrné teplotě ve srovnání s předindustriální úrovní, s důsledky, jako je vzestup hladiny oceánů, tání ...
null
null
null
null
Generate a URL to search the desired content on Google using Python.
Search Keyword: Covid-19 Pandemic
import urllib url = 'https://www.google.com/search?q=Covid-19+Pandemic' urllib.request.urlopen(url)
null
Construct a for loop to print all the elements of a list numbered in sequence, as shown in the output.
list_elements = ["apple", "banana", "cherry"]
for index, element in enumerate(list_elements,start=1): print(index, element) #Output: #1 apple #2 banana #3 cherry
null
Design a program in Python that takes 4 numbers as input and prints out the product of the first three numbers.
1, 2, 3, 4
def product(nums): product = 1 for i in range(3): product *= nums[i] return product nums = [int(x) for x in input().split(",")] print(product(nums))
[CS Wikipedia] Americká hokejbalová reprezentace Americká hokejbalová reprezentace je výběrem nejlepších amerických hráčů v hokejbale. Od roku 1998 se účastní mistrovství světa. Tým je řízen Americkým hokejbalovým institutem, který je členem ISBHF. Největším úspěchem amerického výběru je druhé místo z mistrovství svět...
null
null
null
null
Optimize a Python function to calculate the square of a number for maximum performance.
Not applicable
def square(x): return x * x # Using the exponentiation operator def square_op(x): return x ** 2 # Using bit-shift operator def square_shift(x): return x << 1 # Using multiplication def square_mul(x): return (x + x) * x # Using pow() built-in def square_builtin(x): return pow(x, 2)
null
Implement a web scraper in Python that downloads the contents of a given URL.
url = 'https://en.wikipedia.org/wiki/Web_scraping'
import requests from bs4 import BeautifulSoup url = 'https://en.wikipedia.org/wiki/Web_scraping' r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') html = str(soup) with open("output.html", "w") as file: file.write(html)
null
You need to implement a function that finds the longest string inside an array.
array = ["cherry", "apple", "applepie", "strawberry", "raspberry"]
def find_longest_str(arr): longest_str = "" for s in arr: if len(s) > len(longest_str): longest_str = s return longest_str result = find_longest_str(array) print(result) # prints "applepie"
null
Rewrite the following Bash program to print only even numbers between 0 and 100.
#!/bin/sh for i in $(seq 0 100) do echo $i done
#!/bin/sh # loop from 0 to 100 for i in $(seq 0 2 100) do echo $i done
null
Create a UI component in ReactJs to render a list of items from an array of objects.
const items = [ { name: "Apple", price: 12.99 }, { name: "Orange", price: 5.99 }, { name: "Banana", price: 3.99 }, ];
const ItemList = ({ items }) => ( <ul> {items.map(item => ( <li>{`${item.name}: ${item.price}`}</li> ))} </ul> );
null
Write code that removes spaces from a given string.
string = " A B C D "
def remove_spaces(string): return "".join(string.split())
null
How to define an array in PHP?
An array in PHP is defined using the array() function. The syntax is as follows: $array = array($element1, $element2, ...); The elements can be of any type, such as strings, numbers, Booleans, objects, or even other arrays.
null
How would you write a for loop to iterate over an array of integers in Bash?
for i in $(seq 0 $((${#array[@]} - 1))); do echo "${array[$i]}" done
null
Create a function that takes a 2D array of numerical values and returns the number of times the maximum value appears.
my_array = [[1, 2, 4, 1], [2, 3, 3, 2], [3, 4, 3, 3]]
def count_max(arr): max_val = 0 count = 0 for row in arr: max_val = max(max_val, max(row)) for row in arr: if max(row) == max_val: count += 1 return count
null
Determine the average of 3 numbers.
30, 20, 60
The average of the 3 numbers is 36.
null
Design a Python class to define a person.
class Person: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def get_name(self): return self.name def get_age(self): return self.age def get_gender(self): return self.gender
null
Create a Python program that generates a random number between 5-15.
import random x = random.randint(5,15) print(x)
null
Replace the given SQL query with a Python program to calculate the sum of all the column values.
SELECT SUM(column) FROM table;
import pandas as pd data = pd.read_sql query = "SELECT * FROM table" df = pd.read_sql(query, conn) sum_column = df['column'].sum() print(sum_column)
null
Create a simple chatbot in Python using NLTK
Not applicable
import nltk from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() import json import pickle import numpy as np from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD words=[] classes = [] documents = [] ignore_words = ['?', '!'] data...
null
Create a Python program that takes in two strings and compares them. It should output the number of common characters between them.
"My cat", "Tasty snacks"
def compare_str(str1, str2): common_count = 0 for char in str1: if char in str2: common_count += 1 return common_count str1 = "My cat" str2 = "Tasty snacks" print("Number of common characters between '{}' and '{}': {}".format( str1, str2, compare_str(str1, str2))) # Output: Number of common characters between '...