text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Create a loop in Python to print the fibonacci sequence of the given number.
n = 10
def fibonacci(n): a = 0 b = 1 print("Fibonacci Series:") for i in range(n): print(a, end = " ") c = a + b a = b b = c fibonacci(n)
null
Using the given class, write a constructor that creates an instance with age 10.
class Person: def __init__(self,age): self.age = age
class Person: def __init__(self,age=10): self.age = age
null
Create an ios app to display the content of a given RSS feed
Url: https://www.nytimes.com/svc/collections/v1/publish/https://www.nytimes.com/section/world/rss.xml
You will need to use an API like RSS API which can help you fetch the contents of the given URL. The API can be used for displaying the content of the RSS feed in a UI. Once you have setup the API, you will then need to create a UI which uses the API and display the RSS feed content on the iOS app.
null
Write a Python script to reduce an array of integers by their GCD.
[30, 20, 45]
def gcd(a, b): while a != 0: a, b = b % a, a return b def reduce_by_gcd(arr): gcd_val = arr[0] for i in range(len(arr)): gcd_val = gcd(gcd_val, arr[i]) return [a // gcd_val for a in arr] reduced_arr = reduce_by_gcd([30, 20, 45]) print(reduced_arr) # [2, 3, 5]
null
Explain what is a non-deterministic algorithm.
A non-deterministic algorithm is an algorithm that can produce different results when run multiple times with the same inputs. This is because the algorithm may make use of randomness or take different paths based on the input, and the result of each run will be different. Non-deterministic algorithms are useful in sol...
null
Optimize the following Python program to run faster.
def remove_duplicates(lst): s = set() for item in lst: if item in s: pass else: s.add(item) return s lst = [1, 2, 4, 2, 5, 6, 3, 3] new_list = remove_duplicates(lst) print(new_list)
def remove_duplicates(lst): return list(set(lst)) lst = [1, 2, 4, 2, 5, 6, 3, 3] new_list = remove_duplicates(lst) print(new_list)
null
Add the following comment to the following piece of code.
def func_name(val1): val2 = val1 * 5
def func_name(val1): # Multiply the value by 5 val2 = val1 * 5
null
Write a Rust program to find the lowest common ancestor in a given tree.
fn lowestCommonAncestor(root: &TreeNode, p: &TreeNode, q: &TreeNode) -> i32 { if root == nil { return -1; } if root == p || root == q { return root.val; } let left = lowestCommonAncestor(root.left, p, q); let right = lowestCommonAncestor(root.right, p, q); if left != -1 && right != -1 { return root.val; } return left !...
[DE Wikipedia] Hato-Lau Hato-Lau (Hatu-Lau) ist eine osttimoresische Aldeia im Suco Mau-Ulo (Verwaltungsamt Ainaro, Gemeinde Ainaro). 2015 lebten in der Aldeia 134 Menschen. Geographie Die Aldeia Hato-Lau bildet den Westen des Sucos Mau-Ulo. Östlich befindet sich die Aldeia Dagamessa. Im Süden grenzt Hato-Lau an den S...
null
null
null
null
Design an algorithm in Python that takes a list of integers and returns a new list of integers such that the difference between every two adjacent elements in the new list is greater than 3.
[1, 2, 4, 5, 8, 14, 15]
def solution(list): result = [] for i in list: if len(result) == 0: result.append(i) elif i - result[-1] > 3: result.append(i) return result list = [1, 2, 4, 5, 8, 14, 15] print(solution(list)) # Result: [1, 4, 8, 14]
null
Compress the following string using LZW compression.
Input: ‘ABBBCDCDEFFG’
The compressed string would be ‘A1B3C1D1E1F2G1’.
null
Write Python code to normalize the values of a list of numbers by subtracting each number from the maximum value in the list and dividing it by the maximum value.
[7, 8, 10],
def normalize(lst): max_num = max(lst) normalized_lst = [(num-max_num)/max_num for num in lst] return normalized_lst lst = [7,8,10] normalized_values = normalize(lst) print(normalized_values)
null
Create a web scraper in Python using the Requests library that can scrape information from a Wikipedia page.
https://en.wikipedia.org/wiki/Python_(programming_language)
import requests from bs4 import BeautifulSoup def scrape_wiki(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # find all headlines headers = soup.find_all('h1', {'id': 'firstHeading'}) for header in headers: print(header.get_text()) # find all li...
null
Construct a MongoDB query to retrieve all documents where the field 'name' contains the letter 'y'.
db.collection.find({ "name": { "$regex": /.*y.*/i } })
null
Design an algorithm to add two given binary numbers
def add_binary(b1, b2): # initalize result result = "" carry = 0 # iterate over the bits for i in range(max(len(b1), len(b2))): a = int(b1[-i-1]) if i < len(b1) else 0 b = int(b2[-i-1]) if i < len(b2) else 0 #calculate sum sum = carry ^ a ^ b result = str(sum) + result # calculate the carry carry = (carry&a) | (carry&b...
null
Edit the following code so it prints out a message when the condition is true.
if condition:
if condition: print("Condition is true!")
null
Produce a single Python statement that multiplies the values of the variables x, y, and z, and stores the result in the variable result.
x = 5, y = 10, z = 20
result = x * y * z
null
Create a basic web scraper in Python. The scraper should take a website URL as an input and extract all hyperlinks from it.
Not applicable
# import libraries import requests from bs4 import BeautifulSoup # define the scrape_page function def scrape_page(url): # make the request response = requests.get(url) # parse the response using BeautifulSoup soup = BeautifulSoup(response.text, 'html.parser') # an empty list to store the hyperlinks links = [] ...
null
Create a function to print out a numbered list of items from an array.
array = [‘apple’, ‘banana’, ‘orange’]
def print_numbered_list(array): """Prints out a numbered list based on an array of items.""" for i, item in enumerate(array, start=1): print(f"{i}. {item}")
null
Write a web scraper in Python that is able to collect the top 5 news headlines from your local news website.
Not applicable
import requests from bs4 import BeautifulSoup # We can use requests to get the webpage data webpage = requests.get('http://localnewwebsite.com') # Parse the HTML using BeautifulSoup soup = BeautifulSoup(webpage.content, 'html.parser') # Find the div containing the headlines headlines_div = soup.find('div', class_='h...
null
Create an algorithm to encourage work balance and productivity in remote work.
One algorithm to encourage work balance and productivity in remote work is a scheduling algorithm that assigns workloads over manageable working windows with rest periods in between to allow for breaks and recovery. This algorithm can be designed to set maximum and minimum limit for each allocated workload and for dura...
[EN Wikipedia] UCL Faculty of Life Sciences The UCL Faculty of Life Sciences is one of the 11 constituent faculties of University College London (UCL). History The roots of UCL’s Faculty of Life Sciences can be traced back to 1826, when the Chairs of Botany and Comparative Anatomy were established; with the Department...
null
null
null
null
Add code to make an API call using a library to a given JSON endpoint and retrieve the data.
API URL: https://example.com/endpoint/data
import requests url = "https://example.com/endpoint/data" response = requests.get(url) data = response.json()
null
Design a Python program to print out all prime numbers in a range
Number Range between 1 and 10
def is_prime(n): for i in range(2, n): if n%i == 0: return False return True for num in range(1, 10): if is_prime(num): print(num)
null
Create an object in JavaScript that performs a task given a condition.
const myObject = { doTask: (condition) => { if(condition) { // code to perform the task } } }
[CS Wikipedia] The Boston News-Letter The Boston News-Letter byly noviny vydávané v Britské Severní Americe, jedné z kolonií britského impéria po ukončení americké války za nezávislost, v letech 1704 až 1776. Noviny byly vydávány v týdenní periodicitě a byly silně kontrolovány britskou vládou, taktéž měly omezený nákl...
null
null
null
null
How do you create a namespace in Java?
In Java a namespace is created by declaring a package statement at the top of a source file. For example: package com.example.myapp; This will create a namespace named "com.example.myapp" and all class and interfaces declared within the source file will be under this namespace.
[EN Wikipedia] Ytterøy Church Ytterøy Church () is a parish church of the Church of Norway in Levanger municipality in Trøndelag county, Norway. It is located on the island of Ytterøya, just north of the village of Hokstad. It is the church for the Ytterøy parish which is part of the Stiklestad prosti (deanery) in the...
null
null
null
[CS Wikipedia] Andrej Končalovskij Andrej Končalovskij, rodným jménem Andrej Sergejevič Michalkov-Končalovskij (* 20. srpna 1937, Moskva, Sovětský svaz) je ruský scenárista a režisér. Pochází ze známé umělecké rodiny, jeho děd Petr Končalovskij a praděd Vasilij Surikov byli malíři, otec Sergej Michalkov byl spisovatel...
null
null
null
[EN Wikipedia] Noel Davis Noel Davis (born Edgar Davis; 1 March 1927 – 24 November 2002) was a British film and television actor; and latterly, a film and television casting director. Partial filmography Darling (1965) - Shop Assistant (uncredited) Fahrenheit 451 (1966) - Charles (uncredited) Two a Penny (1967) - Denn...
null
null
null
null
Write a JavaScript program to create a random string of 10 characters.
function getRandomString() { var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var randomstring = ''; for (var i=0; i<10; i++) { var rnum = Math.floor(Math.random() * chars.length); randomstring += chars.substring(rnum,rnum+1); } return randomstring; }
null
How can you sort a list of integers by their absolute value in Python?
You can sort a list of integers by their absolute value using the sort() method. For example: numbers = [2, -1, 5, 0, -4] numbers.sort(key = lambda x: abs(x)) print(numbers) # Output: [0, -1, 2, -4, 5]
null
How can you access the value of a key from a JavaScript object?
You can access a value from a JavaScript object using either dot notation or square bracket notation. Using dot notation, you can do something like "object.key", where the key is the name of the property you want to access. Using bracket notation, you can do something like "object["key"]", where the key is a string con...
[CS Wikipedia] Synnøve Lieová Synnøve Lieová (22. srpna 1908 – 9. července 1980) byla norská rychlobruslařka. Závodila od roku 1932, v roce 1933 se zúčastnila prvního neoficiálního ženského Mistrovství světa (2. místo). Podobných umístění dosáhla i na neoficiálních mistrovstvích v letech 1934 (2. místo) a 1935 (3. mís...
null
null
null
[EN Wikipedia] Marjorie Silliman Harris Marjorie Silliman Harris (June 6, 1890 – March 27, 1976) was an American philosopher who wrote on the problem of determining meaningfulness in life. Influenced by Auguste Comte, Henri Bergson, and Francisco Romero, she addressed questions related to individual experience and its...
null
null
null
null
Find the position of the substring "is" in the string.
string = "This is an example"
string = "This is an example" print(string.find("is"))
null
Implement a regression algorithm in Python to predict housing prices.
Not applicable
import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression # Load the data data = pd.read_csv('data.csv') # Define the inputs and labels X = data[['square_feet', 'beds', 'baths']] y = data['price'] # Create and train the model model = LinearRegression() model.fit(X, y) # Test the model...
null
Create a Java program that reads in two strings and outputs their longest common substring.
myCodingSkillzz and AnotherCodingSkill
CodingSkill
null
Generate a C++ code to filter out an array containing odd numbers.
#include <iostream> // Function to filter out odd numbers void filter_odd(int arr[], int n) { int i, k; k = 0; // Traversing the given array // from first to last for (i = 0; i < n; i++) { // If arr[i] is even then // store it at current index if (arr[i] % 2 == 0) { arr[k++] = arr[i]; } } // Modifying original array //...
null
Write a JavaScript function to check if a given input number is perfect or not. A perfect number is a number whose sum of divisors equals the number itself.
function isPerfect(n) { let sum = 0; for (let i = 1; i < n; i++) { if (n % i == 0) { sum += i; } } return sum === n; }
[CS Wikipedia] František Lašek František Lašek (30. března 1883 Duchcov – 13. března 1957 Praha) byl český divadelní a filmový herec. Život Narodil se v rodině duchcovského horníka Václava Laška a jeho ženy Kateřiny rozené Kosmatové, začal studovat na odborné keramické škole v Teplicích. Studium nedokončil, utekl k di...
null
null
null
null
Given a list of integers and a target value, calculate two integers in the list that add up to the target value.
target = 6 list = [1, 2, 3, 4, 5]
(1, 5)
null
Design a data structure to store user information such as username, password, date of birth and email address.
The information can be stored in a user class using the following structure: class User { string username; string password; string dateOfBirth; string emailAddress; } The information can then be accessed and modified using getter and setter methods.
null
Create a code to create a userid from the given firstname and lastname.
Firstname: John Lastname: Smith
def create_userid(firstname, lastname): userid = firstname[0] + lastname[:5] return userid userid = create_userid("John", "Smith") print(userid) # Output: JSmith
null
Create a JavaScript function to return the greatest value from the following array of numbers.
[2, 4, 8, 10, 15]
function getGreatestValue(arr) { let greatest = arr[0]; for(let i = 0; i < arr.length; i++) { if(arr[i] > greatest) { greatest = arr[i]; } } return greatest; }
null
Write a Python program to find the longest common prefix among all strings in the list.
strings = ["code", "coder", "coding"]
def find_longest_common_prefix(strings): first_str = strings[0] longest_prefix = "" for i in range(len(first_str)): current_prefix = first_str[:i] flag = True for string in strings[1:]: if not string.startswith(current_prefix): flag = False break if flag: longest_prefix = current_prefix return...
null
Write an HTML element to create a checkbox in a form.
<input type="checkbox" name="checkboxname" />
null
Replace the character at the second index with "X".
s = "Hello!"
s = "Hello!" new_str = s[:1] + "X" + s[2:] print(new_str) # Output: HXllo!
null
Given a person's name and the current time, print the difference in time from the person's birthday.
name = "John" time = datetime.datetime(2021, 3, 25, 10, 0, 0)
birthday = datetime.datetime.strptime(name + " birthdate", "%Y-%m-%d") time_diff = time - birthday print("The difference in time from " + name + "'s birthday is " + str(time_diff))
null
Edit the following C code so that an infinite loop is created:
#include <stdio.h> int main() { int i = 0; while(i<10) { printf("%d\n",i); i++; } return 0; }
#include <stdio.h> int main() { int i = 0; while(1) { printf("%d\n",i); i++; } return 0; }
null
Write a Python function to generate a sequence of numbers of a given length which contain prime numbers only.
8
def generate_prime_sequence(length): prime_sequence = [] prime_number = 2 while len(prime_sequence) < length: is_prime = True for i in range(2, int(prime_number/2) + 1): if prime_number % i == 0: is_prime = False break if is_prime: prime_sequence.append(prime_number) prime_number += 1 re...
null
Modify a Python program to encrypt a string using the XOR Cipher.
current program: def xor_strings(xs, ys): return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys)) password = "TestPassword" string = "TopSecret" print(xor_strings(password, string))
def xor_strings(xs, ys): output = "" for i in range(0, len(xs)): output += format(ord(xs[i]) ^ ord(ys[i]), '02x').upper() return output password = "TestPassword" string = "TopSecret" print(xor_strings(password, string))
null
Use the 'requests' library to retrieve the HTML content of a website.
url = "https://www.example.com"
import requests html = requests.get(url).text
[EN Wikipedia] Okurköy, Hani Okurköy () is a neighbourhood in the municipality and district of Hani, Diyarbakır Province in Turkey. It is populated by Kurds and had a population of 144 in 2022. References Neighbourhoods in Hani District Kurdish settlements in Diyarbakır Province
null
null
null
null
Write a JavaScript program to create an array of elements, representing the Fibonacci sequence, up to the given number n.
function fibonacci_array(n) { let sequence = [0, 1]; while (sequence.length <= n) { let lastIndex = sequence.length - 1; sequence.push(sequence[lastIndex] + sequence[lastIndex - 1]); } return sequence; }
null
Create a Python function to find the probability of an event using the binomial distribution.
n = 10 p = 0.5 x = 6
from math import factorial def binomial_probability(n, p, x): """Find the probability of an event using the binomial distribution. Args: n (int): The number of trials. p (float): The probability of success of the event. x (int): The number of successes. Returns: float: The...
null
Generate an HTML page with a table containing all the elements of an array in JavaScript.
[1, 2, 3, 4]
<html> <head> <title>Array Table</title> </head> <body> <table> <tr> <th>Element Value</th> </tr> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> <tr> <td>4</td> </tr> </table> </body> </html>
null
Create a SQL query to join two tables with the condition that the result should include all rows from the first table, even if there is no match in the second table.
Table1: id | name | addresses 1 | Alice | 123 street 2 | Bob | 456 avenue Table2: id | name 2 | Bob
SELECT * FROM Table1 LEFT JOIN Table2 ON Table1.id = Table2.id
null
Come up with a creative way to optimise the given code in Python.
# This code filters a list of numbers and prints out only the even ones numbers = [1,2,3,4,5,6,7,8] for num in numbers: if num % 2 == 0: print(num)
# This code filters a list of numbers and prints out only the even ones numbers = [1,2,3,4,5,6,7,8] # Use list comprehension to filter the list even_numbers = [x for x in numbers if x % 2 == 0] # Print out the even numbers for num in even_numbers: print(num)
null
How can you move an element from one array to another in JavaScript?
let array1 = [1, 2, 3]; let array2 = [4, 5, 6];
let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; let el = array1.pop(); array2.push(el); console.log(array2);
null
Generate a list of valid HTML tags used to structure content in a page.
- <html> - <title> - <head> - <body> - <header> - <nav> - <main> - <article> - <section> - <aside> - <footer> - <h1>, <h2>, <h3>, ... <h6> - <p> - <ul>, <ol> - <li> - <div> - <span> - <img> - <table> - <tr>, <th>, <td>
null
Calculate the mean of the following list of numbers using a for loop.
numbers = [3, 5, 8, 11, 15]
total = 0 for number in numbers: total += number mean = total / len(numbers) print(mean) # Output: 8.4
null
Write a Python program to print the day of week for a specific date.
Date: "21 October 2020"
import datetime date_str = "21 October 2020" date = datetime.datetime.strptime(date_str, "%d %B %Y") print(date.strftime("%A"))
null
Create a Java program to check for a palindrome.
public class Palindrome { public static boolean isPalindrome(String str){ // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters toc compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment...
null
Write a python program to which given a list of numbers, will calculate the mean value
def mean(nums): total = 0 for num in nums: total += num # Return the mean by dividing by the number of elements return total / len(nums)
null
Create a function in Java that takes two numbers as arguments and prints their product.
10 and 8
public static void printProduct(int n1, int n2){ System.out.println(n1 * n2); }
null
Create a new array containing the numbers from 10 to 100 in increments of 5.
[10, 15, 20, 25, 30, ..., 95, 100]
int[] array = new int[19]; int num = 10; for (int i=0; i<19; i++){ array[i] = num; num += 5; }
null
Create a function in Python that returns the longest increasing subsequence in a given array.
[3,4,2,1,6,7]
# Return the longest increasing subsequence def lis(arr): n = len(arr) # Initialize LIS values for all indexes lis = [1]*n # Compute LIS values from left to right for i in range (1, n): for j in range(0, i): # lis[i] = max(lis[i], lis[j] + 1) if arr[i] > arr[j] if arr[i] > arr[j] ...
null
Read a given time-series dataset in Python and build a forecast model to predict future values.
import pandas as pd from sklearn.linear_model import LinearRegression # Load data df = pd.read_csv('data.csv') # Split data into train and test sets X_train = df.loc[:2000, ['time']].values y_train = df.loc[:2000, ['value']].values X_test = df.loc[2000:, ['time']].values y_test = df.loc[2000:, ['value']].values # Tr...
null
Write an SQL query to display the first name and last name of all employees in the Employees table.
SELECT first_name, last_name FROM Employees;
null
Edit the following Java program and make it compile without any errors.
public class Main { public static void main(String[] args) { System.print("Hello, World!"); } }
public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } }
[HI Wikipedia] वज्रच्छेदिकाप्रज्ञापारमितासूत्र वज्रच्छेदिका प्रज्ञापारमिता सूत्र (या वज्र सूत्र) महायान बौद्ध धर्म सूत्र है जो प्रज्ञापारमिता ('ज्ञान की पूर्णता') सूत्रों की शैली से है। एक व्यापक भौगोलिक सीमा में विभिन्न भाषाओं में अनुवादित, वज्र सूत्र पूर्वी एशिया में सबसे प्रभावशाली महायान सूत्रों में से एक है, और य...
null
null
null
null
Create a Python code that takes two strings and combine them into a single string.
str1 = "Hello" str2 = "World"
combinedString = str1 + ' ' + str2 print(combinedString) # Hello World
null
The given code is a Python script that performs various natural language processing tasks on Twitter data. To use this script, you need to import the required libraries such as json, sklearn, nltk, wordcloud, matplotlib, and db. Then, you can define the DATASET_PATH variable to point to the location of the Twitter data...
import json from sklearn.feature_extraction.text import TfidfVectorizer import nltk from nltk.corpus import stopwords from wordcloud import WordCloud import matplotlib.pyplot as plt import db import os DATASET_PATH = os.environ['HOME'] + '/nltk_data/corpora/twitter_samples/tweets.20150430-223406.json' def calc_frequen...
null
Write a Python program to calculate the sum of two integers without using the ‘+’ operator.
3, 4
def add_without_plus_operator(a, b): # Iterate till there is no carry while (b != 0): # Carry now contains common set bits of x and y carry = a & b # Sum of bits of x and y where at least one of the bits is not set a = a ^ b # Carry is shifted by one so that adding it t...
null
Create a program in Python to generate a Random Password of length 8 characters, which contains at least one of each character type (lowercase, uppercase, digits, special characters).
Not applicable
import string import random # length of password length = 8 # special characters special_characters = "!#$%&'()*+,-./:;<=>?@[\]^_`{|}~" # generating password password = random.choice(string.ascii_lowercase) password += random.choice(string.ascii_uppercase) password += random.choice(string.digits) password += random....
null
Design a program that outputs the average value of a list in Python.
[1, 4, 10, 6]
# Given a list of numbers nums = [1, 4, 10, 6] # Calculate the average total = 0 for num in nums: total += num average = total/ len(nums) # Output the average print(average)
null
Edit a given HTML page and add a new link.
<html> <head> <title>My webpage</title> </head> <body> Welcome to my webpage! </body> </html>
<html> <head> <title>My webpage</title> </head> <body> Welcome to my webpage! <a href="https://example.com">Link</a> </body> </html>
null
In a Python list, swap the items at index 3 and 4.
List: [10, 20, 30, 40, 50]
def swap(arr, idx1, idx2): arr[idx1], arr[idx2] = arr[idx2], arr[idx1] arr = [10, 20, 30, 40, 50] swap(arr, 3, 4) print(arr)
null
Implement a Python Script that prints out all the prime numbers between 0 and a given number.
def find_primes(number): for num in range(1, number + 1): # prime numbers are greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) find_primes(20)
null
Create a SQL query that returns the records with the highest salary from the Employees table.
Employees table columns: id | name | salary 1 | John | 120000 2 | Jane | 150000 3 | Jack | 160000
SELECT * FROM Employees ORDER by Salary DESC LIMIT 1;
null
Generate CNN-LSTM model in Keras.
# define CNN model model_cnn = Sequential([ Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), MaxPool2D(), Flatten(), Dense(100, activation='relu'), Dense(10, activation='softmax') ]) # define RNN model model_lstm = Sequential() model_lstm.add(LSTM(128, input_shape=(28, 28, 32))) model_lstm.add(Dense(100,...
null
Create a new class called "Rectangle" with two properties: width and height
class Rectangle { int width; int height; public Rectangle (int width, int height){ this.width = width; this.height = height; } }
null
Write Python code to implement this logic: if the number is even, then double the value; otherwise, subtract 1 from the value.
def modify_number(number): if number % 2 == 0: return number * 2 else: return number - 1
null
Create a Python program to determine if a given string is a palindrome and if so, print it.
String = "racecar"
# Function to check if a string is a palindrome def isPalindrome(s): # Reverse the string rev_s = s[::-1] # Check if the string is the same as its reverse if (s == rev_s): return True return False # Driver code s = 'racecar' # Check if the given word is a palindrome if (isPalindrome(s)): print(s)
null
Create a while loop to iterate over the elements in the given list
my_list = [1, 2, 3, 4]
i = 0 while i < len(my_list): print(my_list[i]) i += 1
null
Sort these integers in ascending order.
6, 5, 10, 1
[1, 5, 6, 10]
null
Write a web page using HTML, CSS, and JavaScript that displays the following text: "Welcome to my website!".
<!doctype html> <html> <head> <title>My website</title> </head> <body> <div class="container"> <h1>Welcome to my website!</h1> </div> <script> console.log('Welcome to my website!'); </script> </body> </html>
null
Write a Python code that takes a given list of numbers and returns the mode of that list.
List = [1,2,3,4,2,2,2,5]
def find_mode(List): max_count = 0 modes = [] for num in List: current_count = List.count(num) if current_count > max_count: max_count = current_count modes = [num] elif current_count == max_count: modes.append(num) return modes
null
Generate a Python program that calculates standard deviation of a set of numbers.
[20, 25, 30, 35, 40]
def std_dev(data_set): mean = sum(data_set) / len(data_set) total_sum = 0 for i in data_set: total_sum += (i - mean) ** 2 variance = total_sum / len(data_set) std_dev = variance ** (1/2) return std_dev data_set = [20, 25, 30, 35, 40] print("Standard Deviation: " + str(std_dev(data_set))...
null
Create a Python program to check if given inputs are anagrams.
Input 1: 'listen' Input 2: 'silent'
def is_anagram(input1, input2): # turn the strings into sets s1 = set(input1) s2 = set(input2) # Compare the size of the sets if len(s1) != len(s2): return False # Iterate through the sets and compare the contents for element in s1: if element not in s2: return False # If all the ...
null
Write a function in Python for sorting a given list of numbers.
[29, 11, 46, 7, 248, 1724]
def sort_list(numbers): return sorted(numbers)
null
Generate a batch of 10 code samples for a classification task that takes a piece of code as input and outputs its programming language.
Not applicable
Java // package com.example; public class Example { public static void main(String[] args) { System.out.println("Hello World!"); } } Python # This program prints "Hello World" print("Hello World") Swift // This program prints "Hello World" print("Hello World") C #include <stdio.h> int main() { ...
[HI Wikipedia] सरमक्का जिला सरमक्का सूरीनाम का जिला है, यह देश के उत्तर में स्थित है। जिले की राजधानी ग्रोनिंजन है। 2004 में हुई राष्ट्रीय जनगणना के अनुसार जिले की आबादी 16,135 है। इसका कुल क्षेत्रफल 3,636 वर्ग किलोमीटर है तथा घनत्व 4.4 प्रति वर्ग किलोमीटर है। जनसंख्या के अनुसार यह देश का आठवाँ सबसे बड़ा जिला है तथा क...
null
null
null
[DE Wikipedia] Helene Pflugshaupt Helene Pflugshaupt, geborene Helene Huber (* 17. Juli 1894 in Bern; † 12. November 1991 in Thun) war eine Schweizer Malerin und Zeichnerin. Leben Helene Pflugshaupt Huber verbrachte ihre Kindheit in Bern. Sie nahm von 1911 bis 1914 Unterricht bei Theodor Volmar. Von ihm lernte sie das...
null
null
null
null
Identify the bug in the following code and provide a solution.
def calculate_average(numbers): sum = 0 for number in numbers: sum += numbers return sum/len(numbers)
The bug in the code is that the variable "number" is not used inside the for loop. Instead, the variable "numbers" is used. To fix this, the line "sum += numbers" should be replaced with "sum += number". This will ensure that the correct variable is used inside the loop and the code will execute as expected.
null
Create a vector in R to count the occurrences of a given number in an array
arr = c(1,1,2,2,2,2,3,3,4,4,4)
vector <- c() for (i in arr) { count <- length(which(arr == i)) vector <- c(vector, count) }
null
Generate a Java code snippet for declaring an empty list
List list = new ArrayList<>();
null
Write an HTML page including the given text.
This is a test page
<html> <head> <title>Test Page</title> </head> <body> <h1>This is a test page</h1> </body> </html>
[CS Wikipedia] Architektura Paříže Ve městě Paříž se nachází velké množství světských a církevních stavebních památek od dob římské Galie po současnost zastupující všechny architektonické slohy. Památky jako Eiffelova věž, bazilika Sacré-Cœur, Louvre, katedrála Notre-Dame, Invalidovna nebo Vítězný oblouk a Champs-Élys...
null
null
null