text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Generate a boolean statement in Swift to compare two strings for equality.
String 1: "hello" String 2: "Hello"
let str1 = "hello" let str2 = "Hello" let result = str1.lowercased() == str2.lowercased() print(result)
null
Develop a Sentiment Analysis classifier in Python. The classifier should predict the sentiment (positive or negative) of a given sentence.
The food at this restaurant is terrible
import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.svm import LinearSVC # Load the data data = pd.read_csv('data.csv') # Create the feature vector vectorizer = CountVectorizer() X = vectorizer.fit_transfo...
null
Write a Python program that takes a list of numbers as an argument and prints the count of all even and odd numbers.
[2, 9, 4, 8, 0, 7, 1]
def countNumbers(nums): evenCount = 0 oddCount = 0 for num in nums: if num % 2 == 0: evenCount += 1 else: oddCount += 1 return (evenCount, oddCount) nums = [2, 9, 4, 8, 0, 7, 1] evenCount, oddCount = countNumbers(nums) print("Even numbers:", evenCount) print("Odd numbers:", oddCount) # Even numbers: 4 # ...
[DE Wikipedia] Shinobu Muraki Shinobu Muraki (; * 2. September 1923 in der Präfektur Tokio; † 16. Januar 1997) war eine japanische Szenenbildnerin und Artdirectorin. Leben Muraki begann ihre Karriere im Filmstab 1953 bei Kon Ichikawas Drama Aoiro kakumei. Ab 1955 wirkte sie auch bei einigen Filmen als Artdirector, dar...
null
null
null
null
Construct a JSX expression that renders a <span> element with className "highlight".
<span className="highlight" ></span>
[EN Wikipedia] Trevor Brissett Trevor Anthony Brissett (2 January 1961 – 17 May 2010) was an English footballer. He played in the Football League for Port Vale and Darlington in the early 1980s. He remained involved with football for the rest of his life, playing for Stafford Rangers, Witton Albion, Macclesfield Town,...
null
null
null
null
Create a function in JavaScript that takes two temperatures and returns their average.
function average_temperature(temp1, temp2) { return (temp1 + temp2) / 2; }
null
Construct a for loop in JavaScript to iterate through an array of strings and print out each one.
let strArray = ["Hello", "World", "!"]; for(let i = 0; i < strArray.length; i++) { console.log(strArray[i]); }
null
Write a Python function that takes a list and returns the number of elements that are divisible by 3.
list = [4, 6, 8, 9, 10]
def number_divisible_by_3(list): count = 0 for item in list: if item % 3 == 0: count += 1 return count result = number_divisible_by_3(list) print(result)
[DE Wikipedia] PGC 1924587 LEDA/PGC 1924587 ist eine Galaxie Sternbild Andromeda am Nordsternhimmel, die schätzungsweise 1,5 Milliarden Lichtjahre von der Milchstraße entfernt ist. Vom Sonnensystem aus entfernt sich das Objekt mit einer errechneten Radialgeschwindigkeit von näherungsweise 33.000 Kilometern pro Sekunde...
null
null
null
null
Design a machine learning model to classify an article as either a sports article or a food article.
The machine learning model can be designed as a sequence of layers built with Keras, followed by a dense layer with two units – one for sports and one for food, and a softmax activation function to achieve the final output. We can feed the model with a dataset consisting of article texts labeled as 'sports' or 'food'. ...
null
Write a Python program to extract the text from the webpage.
import requests def extract_text(url): page = requests.get(url) return page.content
[CS Wikipedia] Národní parky v Polsku Polsko má celkem 23 národních parků, nejstarší z nich je Białowieski Park Narodowy na východě Polska, vyhlášený v roce 1947 a naopak zatím nejmladší je Národní park Ústí Warty na západě Polska, vyhlášený roku 2001. Největším polským národním parkem je Biebrzański národní park na s...
null
null
null
null
Edit the following markup so that it becomes valid HTML5.
<body> <div><head>My Website</head></div> </body>
<body> <head>My Website</head> <div></div> </body>
[EN Wikipedia] 1945 Egyptian parliamentary election Parliamentary elections were held in Egypt in January 1945. Boycotted by the Wafd Party, they resulted in a victory for the Saadist Institutional Party, which won 125 of the 264 seats. Results References Egypt Parliamentary elections in Egypt Parliamentary Egypt Elec...
null
null
null
[CS Wikipedia] Měnová krize Měnová krize či krize platební bilance je náhlá devalvace měny, jež často končí spekulativním útokem na devizovém trhu. Měnová krize může být zapříčiněna dlouhodobým deficitem platební bilance nebo nedůvěrou trhu ve schopnost vlády krýt svou vlastní měnu. Měnové krize většinou postihují rež...
null
null
null
null
Write an SQL query to join two tables named 'books' and 'authors' on author_id.
SELECT books.book_title, authors.author_name FROM books INNER JOIN authors ON books.author_id = authors.author_id;
[CS Wikipedia] Acta diurna Acta diurna (latinsky denní akta či denní zprávy), často zvané jen Acta, byly denní římské oficiální zprávy, předchůdci dnešních novin. Informace byly tesány do kamene nebo ryty do kovových desek, které následně byly věšeny na veřejných místech jako například na Forum Romanum. První takovéto...
null
null
null
null
Generate a Python script that prints the numbers from 1 to 10.
# Print numbers 1 to 10 for num in range(1, 11): print(num)
null
Create a Python code to find all uncommon characters between two strings.
string1 = 'green', string2 = 'blue'
def uncommon_chars(string1, string2): uncommon = [] for char in string1: if char not in string2: uncommon.append(char) for char in string2: if char not in string1: uncommon.append(char) return uncommon
null
Create a function 'greet' that takes a string parameter 'name' and returns the string 'Hello name!'
function greet(name) { return 'Hello ' + name + '!'; }
null
In the following code snippet, what will be the output of the print statement ?
x = 10 y = 5 x = x + y print(x)
x = 10 y = 5 x = x + y print(x) # Prints 15
[HI Wikipedia] गुप्त-कलाओं से रक्षा गुप्त-कलाओं से रक्षा (Defense Against the Dark Arts) जे. के. रोलिंग द्वारा अंग्रेज़ी में रचित हैरी पॉटर (उपन्यास) शृंखला में ज़िक्र तन्त्र-मन्त्र और जादू-टोने के विद्यालय हॉग्वार्ट्स में पढ़ाया जाने वाला एक विषय है। इसमें अनैतिक काले जादू, ख़ूँख़ार जीवों और काले जादूगरों से अपनी अत्...
null
null
null
null
Write a Python program to take in a string and reverse the given string using a while loop.
def reverse_string(str): str_rev = '' i = len(str) - 1 while i >= 0: str_rev += str[i] i -= 1 return str_rev
null
Design a program to flatten a given list.
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def flatten_list(lst): res = [] for l in lst: for i in l: res.append(i) return res
null
Sort this array of integers in ascending order using JavaScript.
const array = [26, 4, 11, 56, 23, 39]
const array = [26, 4, 11, 56, 23, 39]; let sortedArray = array.sort(function(a,b){ return a-b; }); console.log(sortedArray);
[CS Wikipedia] Tamara Tichonovová Tamara Ivanovna Tichonovová (: Тамара Ивановна Тихонова), provdaná Volkovová (* 13. června 1964, Kovaljovo, Udmurtská ASSR, Sovětský svaz) je bývalá sovětská a ruská běžkyně na lyžích a biatlonistka. Jako reprezentantka Sovětského svazu vybojovala na ZOH 1988 v Calgary dvě zlaté medai...
null
null
null
null
Create a Python script to calculate the circumference of a circle given its radius.
radius = 5
def calc_circumference(radius): circumference = 2 * 3.14 * radius return circumference circumference = calc_circumference(radius) print(circumference)
null
Generate a Java program that creates a class Student with attributes name and age, and a constructor to initialize the attributes.
public class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
null
Create an application with a Python backend and a React frontend that allows a user to create a list of tasks.
Not applicable
# Python Backend # Web server setup app = Flask(__name__) # Database setup db = SQLAlchemy(app) # Model for tasks class Task(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80), unique=True, nullable=False) is_completed = db.Column(db.Boolean, default=False) def __repr__(s...
null
What HTML element is used to create a table?
The HTML element used to create a table is the <table> element.
null
Construct an array in JavaScript containing five elements.
my_array = [1,2,3,4,5]
null
Create a program which takes a given list and returns a list with only the unique elements.
[3, 5, 7, 9, 5, 3, 7]
my_list = [3, 5, 7, 9, 5, 3, 7] unique_list = list(set(my_list)) print(unique_list) #Output: [3, 5, 7, 9]
null
Implement a function that prints n asterisk characters in a row.
def print_asterisks(n): for i in range(n): print("*", end="") print()
null
Design a class in Python that takes in one input, an integer, and prints out a multiplication table.
class MultiplicationTable: def __init__(self, num): self.num = num def printTable(self): for i in range(1, 11): print(self.num,"*",i,"=",self.num * i)
null
Write a Python code snippet to display a formatted date and time.
import datetime dateandtime = datetime.datetime.now() # print date and time string print(dateandtime.strftime("%d/%m/%Y %H:%M:%S"))
null
Write a code to find the maximum length of the longest consecutive increasing subsequence in the given array.
arr = [2, 3, 1, 10, 5, 6, 8, 7]
def max_length(arr): ans = 1 j = 0 for i in range(len(arr)): if (arr[i+1] - arr[i] > 0): j += 1 ans = max(ans, j+1) else: j = 0 return ans print(max_length(arr))
null
Create an if statement to check if an integer i is between 1 and 10.
if (i >= 1 && i <= 10) { // code to run if the condition is true }
[EN Wikipedia] WIFO WIFO may refer to: WIFO (Nazi company), a former solid fuel research institute in Nazi Germany WIFO-FM, a radio station or the Austrian Institute of Economic Research
null
null
null
null
Explain the basic syntax for a for loop in JavaScript.
The basic syntax for a for loop in JavaScript is as follows: for (initialization; condition; iteration). The initialization statement is run once at the beginning of the loop, and typically initializes one or more loop variables, which are used to track the progress of the loop. The condition statement is used to check...
null
Create a Python function which accepts two numbers then return an array with the Fibonacci sequence starting by the two numbers.
start_1: 1 start_2: 2
def fib_array(start_1, start_2): arr = [start_1, start_2] while True: next_num = arr[-1] + arr[-2] if next_num > 100: break arr.append(next_num) return arr
null
Create a vector in R to store the elements ‘apple’, ‘mango’, ‘banana’ and ‘orange’.
fruits <- c("apple", "mango", "banana", "orange")
null
Write a Python function that takes a list of floats as an argument and returns the sum of all elements.
some_list = [1.5, 5.9, 3.7, 5.2]
def sum_list(some_list): result = 0 for num in some_list: result += num return result print(sum_list(some_list)) # Prints 15.3
[DE Wikipedia] Liddy Holloway Elizabeth Brenda „Liddy“ Holloway (* 27. März 1945 in Wellington; † 29. Dezember 2004 in Auckland) war eine neuseeländische Schauspielerin und Drehbuchautorin. Leben und Karriere Die Tochter des Politikers Phil Holloway war zunächst viele Jahre als Journalistin tätig. Erst nach der Geburt...
null
null
null
null
Create a class in Python that represents a vector in a 3-dimensional space.
class Vec3: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __str__(self): return "({}, {}, {})".format(self.x, self.y, self.z)
null
Change the following code so that it can reverse a list without modifying the original list
[1, 2, 3]
def reverse(lst): return lst[::-1] lst = [1, 2, 3] print(reverse(lst))
null
Using an AI platform, create a sentiment analysis model to predict a sentiment of a given sentence.
model = AIplatform.SentimentAnalysis() model.fit(X, y) prediction = model.predict(sentence)
null
Compute the big-O time complexity for this algorithm.
def factorial(n): if n == 0: return 1 else: return n*factorial(n-1)
The time complexity for this algorithm is O(n).
[EN Wikipedia] Alkali metal The alkali metals consist of the chemical elements lithium (Li), sodium (Na), potassium (K), rubidium (Rb), caesium (Cs), and francium (Fr). Together with hydrogen they constitute group 1, which lies in the s-block of the periodic table. All alkali metals have their outermost electron in an...
null
null
null
null
Specify a quick sort algorithm in Python to sort the given array of numbers.
[9, 6, 5, 3, 4, 7, 4, 1]
def quick_sort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] mid = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort(left) + mid + quick_sort(right) print(quick_sort([9, 6, 5, 3, 4, 7, 4, 1]))
null
Generate a Python program to print all odd numbers from an array of integers.
[3, 5, 7, 10, 15]
def printOddNumbers(array): for number in array: if number % 2 != 0: print(number) array = [3, 5, 7, 10, 15] printOddNumbers(array)
null
Create a program in Python that takes an input string and an integer n, and generates all permutations of the string with length n.
"ABCD", 2
def permutateString(inputStr, n): if n == 0: return [] elif len(inputStr) == 1: return [inputStr] else: result = [] for i in range(len(inputStr)): firstChar = inputStr[i] remainingChars = inputStr[:i] + inputStr[i+1:] for permutation in per...
[EN Wikipedia] Guns for Sale Guns for Sale is a 1998 documentary film about the effect of guns on manhood, raiding, and livelihood in Karamajong, northern Uganda. Synopsis This film starts off with a brief introduction of the Karamajong people in Northern Uganda, Africa. They are one of the most feared tribes in all o...
null
null
null
[EN Wikipedia] Dudua charadraea Dudua charadraea is a moth of the family Tortricidae first described by Edward Meyrick in 1909. It is found in Thailand, Sri Lanka, Taiwan, western Java and western Sumatra. References Moths described in 1909 Olethreutini Moths of Japan
null
null
null
null
Create an object in JavaScript to store a student's information.
name = "John Doe" age = 18
let studentObj = { name: "John Doe", age: 18 }
null
Write a Python program to identify the count of the largest contiguous subarray of numbers in a given array.
arr=[-2, -3, 4, -1, -2, 1, 5, -3]
def max_contiguous_subarray(arr): max_end = 0 max_so_far = 0 for i in range(len(arr)): max_end = max(max_end + arr[i], 0) max_so_far = max(max_end, max_so_far) if max_so_far > 0: return len(arr) - max_so_far else: return 0
null
Suggest a cleaner and more concise way to implement the following code snippet.
def find_matching_number(nums, target): for num in nums: if num == target: return True return False
def find_matching_number(nums, target): return target in nums
null
Create a program in Python that can analyze over a million articles to find the most commonly used words.
A folder containing one million articles in text files.
import os from collections import Counter from nltk import word_tokenize # Specify the directory containing the files directory = 'articles_folder' # Initialize a Counter object word_counts = Counter() # Iterate through all the files in the directory for filename in os.listdir(directory): if filename.endswith('.tx...
null
Write a Python program that prints out all possible words from a collection of letters.
letters = ["a", "b", "t"]
import itertools letters = ["a", "b", "t"] words = [] # we use itertool's permutations to generate all combinations of letters Result = itertools.permutations(letters, 3) # we iterate through the output of itertool's permutation # and append it to result list of words for ele in list(Result): words.append(''.joi...
null
Construct a Python program that can extract the name of an author from a given book title.
title = 'Harry Potter and the Sorcerer's Stone'
def extract_author(title): title_words = title.split() for word in title_words[::-1]: if word[0].isupper(): return word print(extract_author(title)) # Potter
[HI Wikipedia] हरमुख हरमुख भारत के जम्मू व कश्मीर राज्य के गान्दरबल ज़िले में सिन्द नदी (सिन्धु नदी से भिन्न) और किशनगंगा नदी के बीच स्थित एक ५,१४२ मीटर (१६,८७० फ़ुट) ऊँचा पहाड़ है। यह गंगाबल झील से उभरता हुआ प्रकट होता है और हिन्दुओं द्वारा पवित्र माना जाता है। इसे चढ़ने का सबसे आसान मार्ग बांडीपूर ज़िले के आरीन क्षे...
null
null
null
[CS Wikipedia] Ludvík Lazar Zamenhof Ludvík Lazar Zamenhof (pol. ) (15. prosince 1859 Bělostok – 14. dubna 1917 Varšava) byl oční lékař, filolog a tvůrce esperanta, umělého jazyka určeného pro mezinárodní komunikaci. Dětství a kulturní pozadí Narodil se 15. prosince 1859 v polském městě Bělostoku (tehdy součást Ruskéh...
null
null
null
null
Translate the following pseudocode into Python code.
i = 0 while i < 10 print i i = i + 1
i = 0 while i < 10: print(i) i += 1
null
Refactor the following condition to use the ternary operator instead of an if-else statement.
if (x < 0) { y = -1; } else { y = 1; }
y = x < 0 ? -1 : 1;
null
Optimize the following python code for a more efficient solution.
def to_square(nums): squares = [] for num in nums: squares.append(num * num) return squares
def to_square(nums): squares = [num * num for num in nums] return squares
[CS Wikipedia] Bitva u Tarutina Bitva u Tarutina byla bitvou napoleonských válek. Bitva skončila vítězstvím ruské armády nad francouzskými vojsky. Nástin událostí 24. června 1812 vpadla Napoleonova půlmilionová armáda do Ruska. Ruská armáda nemohla francouzský postup zastavit a musela ustupovat. Po nerozhodné bitvě u ...
null
null
null
null
Write an R statement to calculate the probability of getting a number greater than 5 from a range of 1 to 10.
# Calculate the probability probability = mean(x > 5) print(f"Probability of getting a number greater than 5 from a range of 1 to 10 is {probability}.")
[CS Wikipedia] Klimczok Klimczok dříve také Klimczak (1117 m n. m.) je horský vrchol, který se nachází v jihovýchodní části Pásma Baraniej Góry (Beraní hory) v Slezských Beskydech. Přes vrchol prochází administrativní hranice Bílsko-Bělé a také procházela historická hranice mezi Slezskem a Malopolskem. Vrchol Klimczok...
null
null
null
null
Create a dictionary in Python and store the names of four countries and the cities within them.
# Create a Dictionary dict = { "India" : ["Delhi", "Mumbai", "Chennai"], "USA" : ["New York", "Washington", "Los Angeles"], "Canada" : ["Toronto", "Vancouver", "Ottawa"], "France" : ["Paris", "Marseille", "Lyon"] } # Print the Dictionary print(dict)
null
Formulate a SQL query that fetches the records with the latest date
Table name: my_table Columns: id, date
SELECT * FROM my_table ORDER BY date DESC LIMIT 1;
null
Create a JavaScript function which takes two arguments and returns the larger number.
function findMax(num1, num2) { if (num1 > num2) { return num1; } else { return num2; } }
null
Update the given code to generate the correct output
def func(x, n): s = 0 for i in range (n): s += (x**i) return s Output: The sum of series x^1 + x^2 + x^3 + ... + x^n is
def func(x, n): s = 0 for i in range (n): s += (x**i) return s def generateSumString(x, n): result = "The sum of series " for i in range(1, n+1): result += x + "^" + str(i) if(i != n): result += " + " else: result += " is" return result def main(): x = 4 n = 5 print(generateSumString(x, n), func(x,n)) main()
null
Develop a web scraping Python program to scrape the product details of a sample store.
The website is located at https://example.com
import requests from bs4 import BeautifulSoup # Get the HTML from the webpage page = requests.get('https://example.com') soup = BeautifulSoup(page.text, 'html.parser') # Isolate the product information product_list = soup.find_all('div', class_='product') # Extract the product information products = [] for product ...
null
Create a PHP script to encode a given string in base-64.
<?php // Function to encode a given string in base-64 function encodeBase64($str){ return base64_encode($str); } echo encodeBase64("Hello World!"); ?>
null
Generate a list of combinations of three numbers from a given array in Python.
[1, 2, 3, 4, 5]
combinations = [] for i in range(len(arr)): for j in range(i+1, len(arr)): for k in range(j+1, len(arr)): combinations.append([arr[i], arr[j], arr[k]])
null
Improve the performance of the below algorithm written in Python.
def algorithm(arr): result = [] for i in range(len(arr)): for j in range(i + 1, len(arr)): if arr[i] + arr[j] == 0: result.append((arr[i], arr[j])) return result def optimizedAlgorithm(arr): result = [] seen = set() for num in arr: if -num in seen: ...
[CS Wikipedia] Pala Pala může být: příjmení osob Pala (příjmení) sídla v Estonsku Pala (obec) – samosprávná obec v kraji Jõgevamaa Pala (Pala) – vesnice náležející ke stejnojmenné obci Pala (Kõue) – vesnice náležející k obci Kõue v kraji Harjumaa Pala (Kuusalu) – vesnice náležející k obci Kuusalu v kraji Harjumaa Pala...
null
null
null
null
Think of a situation where you would use recursion.
Recursion can be used when performing a task that can be broken down into smaller, simpler parts. For example, performing a Depth-First Search on a Graph. It can also be used when implementing algorithms to solve complex problems such as finding the largest number in a list or creating a binary search tree.
null
Create a Python script to solve an equations.
2x + 3 = 5
def solve(eq): lhs_x = eq.split("=")[0] rhs = float(eq.split("=")[1]) x = float(lhs_x.split("+")[0].split("x")[0]) constant = float(lhs_x.split("+")[1]) return (rhs - constant) / x if __name__ == "__main__": eq = "2x + 3 = 5" print(solve(eq))
null
Write a Python function that prints the first n even numbers.
def print_even_numbers(n): for i in range(2, n*2, 2): print(i)
[HI Wikipedia] आमिर ख़ान आमिर ख़ान (नस्तालीक़: عامر خان) (जन्म आमिर हुसैन ख़ान ; मार्च 14, 1965) एक भारतीय फ़िल्म अभिनेता, निर्माता, निर्देशक, पटकथा लिखनेवाले, कभी कभी गायक और आमिर ख़ान प्रोडक्सनस के संस्थापक-मालिक है। अपने चाचा नासिर हुसैन की फ़िल्म यादों की बारात (1973) में एक बाल कलाकार की भूमिका में नज़र आए थे और...
null
null
null
null
Modify the above Python Flask application to accept form input and create a new task.
Not applicable
from flask import Flask, request, redirect, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(name) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class Task(db.Model): id = db.Column(db.Integer, primary_key=True) description = db.Column(db.String(120), uniqu...
null
Build a program to remove all duplicate words from a given list of strings
["Python", "Python", "programming", "language", "language"]
def remove_duplicates(lst): new_list = [] for i in lst: if i not in new_list: new_list.append(i) return new_list print(remove_duplicates(["Python", "Python", "programming", "language", "language"]))
[HI Wikipedia] तोडुपुज़ा "तोडुपुज़ा" (थोडुपुझा)( केरल राज्य में इडुक्की जिले में एक नगरपालिका और व्यावसायिक केंद्र है। यह शहर कोच्चि से 62 किलोमीटर पूर्व दक्षिण में बसा हुआ है। पी.जे. जोसेफ तोडुपुज़ा विधानसभा निर्वाचन क्षेत्र से सातवीं बार के लिए निर्वाचित हुए. वह केरल कांग्रेस (एम) पार्टी के अध्यक्ष है। लोकप्रिय फिल्...
null
null
null
null
Write a function in Python that will take two inputs, an array of strings and a letter, and returns the number of elements in the array that contain the given letter.
['cat', 'dog', 'fish','apple'] letter: 'a'
def count_elements_with_letter(arr,letter): count = 0 for a in arr: if letter in a: count += 1 return count count_elements_with_letter(['cat','dog','fish','apple'], 'a') # output: 3
null
Write an algorithm to generate the Fibonacci series up to the nth term
def fibonacci(n): a = 0 b = 1 if n < 0: print("Incorrect input") elif n == 0: return a elif n == 1: return b else: for i in range(2,n): c = a + b a = b b = c return b
null
Design a Python script to check if a given value is an alphabet or not.
""" Design a Python script to check if a given value is an alphabet or not """ # function to check if the given value is an alphabet or not def is_alphabet(value): # check if the value is empty if value == '': return False # check if the given value is an alphabet if value.isalpha(): ...
null
From the input list, create a dictionary containing only key-value pairs for even integers.
[4, 7, 9, 10, 16, 18]
# function to create a dictionary containing only key-value pairs for even integers def even_dict(arr): return {i : i for i in arr if i % 2 == 0}
null
Construct a decision tree classifier from given datasets in Python.
Feature sets in the datasets are ‘Age’, ‘Income’ and ‘Gender’ and labels are ‘Credit’.
from sklearn import tree import pandas as pd # Load the data df = pd.read_csv("data.csv") # Define the features and labels features = ["Age", "Income", "Gender"] labels = ["Credit"] # Create a Decision Tree classifier clf = tree.DecisionTreeClassifier() # Train the model using the training sets clf.fit(df[features]...
null
design a functions which removes the duplicate elements from a list
def remove_duplicates(x): res = [] for i in x: if i not in res: res.append(i) return res
[DE Wikipedia] Olympische Sommerspiele 1920/Schwimmen – 100 m Freistil (Männer) Der Schwimmwettkampf über 100 Meter Freistil der Männer bei den Olympischen Spielen 1920 in Antwerpen wurde vom 22. bis 29. August 1920 ausgetragen. Alle Medaillengewinner kamen aus den Vereinigten Staaten. Rekorde Vor Beginn der Olympisch...
null
null
null
null
Create a function that returns a substring of a given string.
string = 'This is a sample string'
def get_substring(string, start, end): return string[start:end]
null
Design an algorithm in python to solve the Towers of Hanoi puzzle.
Number of discs: 3
def hanoi(discs, start, temp, end): if discs > 0: hanoi(discs - 1, start, end, temp) end.append(start.pop()) hanoi(discs - 1, temp, start, end)
null
Write a HTML code to display a ordered list of five items inside a div with the classname "list".
<div class="list"> <ol> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> </ol> </div>
[EN Wikipedia] Ruakōkoputuna River The Ruakōkoputuna River is a river of the Wairarapa, in the Wellington Region of New Zealand's North Island. It flows northeast from its sources within Haurangi Forest Park to the east of Palliser Bay, reaching the Huangarua River south of Martinborough. The river's upper section flo...
null
null
null
null
What could be a use case of a 'while' loop in Python?
A while loop can be used to iterate over a sequence or perform a computation until a specific condition is met. For example, it can be used to generate a list of prime numbers, where it would check if the current number is a prime number by checking if its divisible by any of the already discovered primes before it.
[EN Wikipedia] 1949–50 Norwegian 1. Divisjon season The 1949–50 Norwegian 1. Divisjon season was the 11th season of ice hockey in Norway. Eight team participated in the league, and Gamlebyen won the championship. Regular season External links Norwegian Ice Hockey Federation Norra Eliteserien (ice hockey) seasons 1949–...
null
null
null
null
Write a Python program to implement Linear Search for an array of numbers
arr = [2, 3, 5, 7, 11] n = 11
def LinearSearch(arr, n): for i in range(len(arr)): if arr[i] == n: return i return -1 index = LinearSearch(arr, n) print(index)
null
Search in the API documentation to find all possible parameters that can be used with the API call.
The API contains the following parameters that can be used with the API call: - search queries - sorting criteria - filters - categories - limit - offset - user information - timestamp
null
Remove the empty tuples in the list.
mylist = [(), (1,), (1, 2), (), (3, 4), (), (5)]
mylist = [(), (1,), (1, 2), (), (3, 4), (), (5)] filtered_list = list(filter(None, mylist)) print(filtered_list)