text stringlengths 141 2.89k ⌀ | instruction stringlengths 19 1.5k ⌀ | input stringlengths 0 800 ⌀ | output stringlengths 1 2.5k ⌀ |
|---|---|---|---|
null | Parse an XML document using Python. | import xml.etree.ElementTree as ET tree = ET.parse("file.xml") root = tree.getroot() for child in root: print(f"{child.tag}: {child.text}") | |
null | Create a function in Python that takes an integer argument and returns True if the argument is an even number and False if it is an odd number. | def even_odd(n):
if n % 2 == 0:
return True
else:
return False | |
null | Implement a simple machine learning algorithm in R to classify a given dataset. | # Load the libraries library(caret) library(Metrics) # Create the training and testing sets split = createDataPartition(iris$Species, p = 0.75, list = FALSE) train_set = iris[split, ] test_set = iris[-split, ] # Train the model model = train(Species ~ ., data = train_set, method = "rpart") # Make Predictions on the tes... | |
null | Develop an algorithm in Python for sorting the following array in ascending order. | [9, 8, 11, 5] | def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
array = [9, 8, 11, 5]
bubble_sort(array)
print(array) |
null | Create a basic web crawler in Python. The crawler should take a URL as input and return a list of all external links found on the page. | https://canvas.elte.hu/ | import requests
from bs4 import BeautifulSoup
# make an HTTP request to the given URL
r = requests.get(url)
# parse the response
soup = BeautifulSoup(r.content, 'html.parser')
# find all the links on the page
links = soup.find_all('a')
external_links = []
# loop through the links and extract the external ones
for l... |
null | Convert the given Python code to Java. | def search(arr, x):
n = len(arr)
for i in range (0, n):
if (arr[i] == x):
return i;
return -1; | public static int search(int[] arr, int x) {
int n = arr.length;
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
} |
null | Write a function to find the average of given numbers using a list. | nums = [2, 4, 6, 8] | """ Write a function to find the average of given numbers using a list """ def find_average(nums): return sum(nums) / len(nums) if __name__ == '__main__': nums = [2, 4, 6, 8] print(find_average(nums)) |
null | This code attaches hooks to the return statements of functions in a module. To use it, import the immlib library and create an instance of the ReturnBP or ReturnLog class. Then, call the add method on the instance with the name of the hook and the address of the return statement as arguments. Finally, run the program t... | #!/usr/bin/env python
import immlib
from immlib import LogBpHook, BpHook
class ReturnBP(BpHook):
def __init__(self):
BpHook.__init__(self)
def run(self, regs):
imm = immlib.Debugger()
eip = regs["EIP"]
imm.log("bp, EIP is 0x%08X " % eip)
imm.addKnowledge("0x%0... | |
null | Edit this HTML code to add a link element in the head of the page. | <html> <head> <title>Example page</title> </head> <body> </body> </html> | <html> <head> <title>Example page</title> <link href="style.css" rel="stylesheet"> </head> <body> </body> </html> |
[CS Wikipedia] Alexandr Ioan Cuza
Alexandr Jan Cuza (rumunsky: Alexandr Ioan Cuza) (20. březen 1820, Huși, Rumunsko – 15. květen 1873, Heidelberg, Německo) byl v letech 1859–1862 kníže Valašska a Moldávie a zároveň v letech 1859–1866 vládce resp. domnitor Spojených knížectví Valašska a Moldávie (od roku 1862 Spojené k... | null | null | null |
null | Identify which language the following code snippet is written in. | #include<bits/stdc++.h> using namespace std; int main() { cout << "Hello, World"; return 0; } | C++ |
null | Develop a Python module to generate random numbers. | import random
def generate_random_numbers(length, min_value, max_value):
return [random.uniform(min_value, max_value) for _ in range(length)] | |
null | Use CSS to style an HTML paragraph. | <p> This is a sample paragraph. </p> | <p style="font-family: Arial, sans-serif; font-size: 1.2em; color: #1a1a1a; line-height: 1.8em;">This is a sample paragraph.</p> |
null | Edit the code to create a class for a profile. | class Profile { } | class Profile { constructor(name, email, avatar_url) { this.name = name; this.email = email; this.avatar_url = avatar_url; } updateName(name) { // update the profile's name this.name = name; } updateEmail(email) { // update the profile's email address this.email = email; } updateAvatar(url) { // update the profile's av... |
[DE Wikipedia] Erdumlaufbahn
Erdumlaufbahn kann bedeuten Umlaufbahn eines Satelliten um die Erde → Satellitenorbit Umlaufbahn der Erde um die Sonne → Erdbahn Siehe auch: Umlaufbahn | null | null | null |
null | Compare and contrast HTTP and HTTPS. | HTTP (Hypertext Transfer Protocol) and HTTPS (Hypertext Transfer Protocol Secure) are both protocols used to transfer data over the internet. The main difference between them is that HTTPS is a secure connection, using encryption technology to protect and authenticate data exchanged over the connection. HTTP on the oth... | |
[CS Wikipedia] Gossip
Gossip (původně The Gossip) bylo trojčlenné americké indie rock seskupení, založené Beth Dittovou, kytaristou Bracem Painem a hráčkou na bicí Hannah Blilieovou. Kapela pochází ze státu Arkansas a většinou hrála po hudebních klubech. V roce 2016 ohlásila Beth Dittová rozpad skupiny. Obsazení Beth ... | null | null | null |
null | Create a function that checks if a string contains all the vowels. | def check_if_string_contains_all_vowels(string): vowels = ['a', 'e', 'i', 'o', 'u'] str_vowels = [ltr for ltr in string.lower() if ltr in vowels] return len(str_vowels) == len(vowels) | |
null | Create a program to print out all prime numbers below 100. | # Function to print prime numbers def prime_numbers_below_100(): for num in range(2, 100): prime = True for i in range(2, num//2 + 1): if num % i == 0: prime = False break if prime: print(num, end=" ") print("Prime numbers below 100 are:") prime_numbers_below_100() | |
[EN Wikipedia] SSBN Degree College
Sri Sai Baba National Degree College is an autonomous degree college located in Anantapur, Andhra Pradesh, India. It is a Government Aided College also known as Sai Baba College.The College, named after Sri Shiridi Sai Baba, was established in October 1981 under the aegis of the Anan... | null | null | null |
null | Design and write a Python program to search a particular website for links that contain a certain keyword. | Not applicable | from urllib.request import urlopen
from bs4 import BeautifulSoup
# URL to search for (keyword included)
url = 'http://example.com/search?query=keyword'
# Parse HTML and save to BeautifulSoup object
html = urlopen(url)
bs = BeautifulSoup(html.read(), 'html.parser')
# Save all links found in the HTML document
links = ... |
[DE Wikipedia] Vermutung von Feit-Thompson
Die Vermutung von Feit-Thompson ist eine zahlentheoretische Vermutung, die den Beweis des Satzes von Feit-Thompson und damit der Klassifikation der endlichen einfachen Gruppen erheblich vereinfachen würde. Die Vermutung besagt, dass es keine Primzahlen und mit gibt, für die d... | null | null | null |
null | Can you write a code snippet in Python that replaces all occurrences of a specific character in a string? | string = "Hello World"
character = "o" | def replace_all_occurrences(string, character):
return string.replace(character, "") |
null | Create a function to iterate a list of strings and print them. | def iterate_strings(string_list): for string in string_list: print(string) if __name__ == '__main__': string_list = ["apple", "banana", "cherry"] iterate_strings(string_list) | |
null | Create an end-to-end machine learning system in Python by using a deep neural network to solve a multi-class classification problem. | Not applicable | # Importing Libraries
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
# Defining Input and Output
x = np.array([[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]])
y = np.array([[1], [1], [2], [3], [3], [2]])
# Defining and Compiling the Model
model = Sequential()
model.add(Dense(4,... |
[HI Wikipedia] सर्वभारतीय तृणमूल कांग्रेस
तृणमूल कांग्रेस (बंगाली: সর্বভারতীয় তৃণমূল কংগ্রেস) मुख्यतः पश्चिम बंगाल में सक्रिय एक भारतीय राजनैतिक दल है। इस दल का जन्म भारतीय राष्ट्रीय कांग्रेस से विघटन होकर हुआ। इस दल की नेता ममता बनर्जी है। सर्वभारतीय तृणमूल कांग्रेस (संक्षेप में एआईटीसी, टीएमसी या तृणमूल कांग्रेस) प... | null | null | null |
null | Create a CNN classifier in Python using Keras that can classify the MNIST dataset. | Not applicable | import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
# Set image dimensions
img_rows, img_cols = 28, 28
# Load data
(X_train, y_train), (X_test, y_test) = mnis... |
[CS Wikipedia] Mark Woodforde
Mark Woodforde (* 23. září 1965, Adelaide) je bývalý australský profesionální tenista, specializující se na čtyřhru, v níž dosáhl nejlepších výsledků. Tenisová kariéra V mužské čtyřhře získal dvanáct titulů z Grand Slamu a dalších pět ve smíšené čtyřhře. Společně s krajanem Toddem Woodbri... | null | null | null |
null | Create a function in Python to identify consecutive numbers in a given list. | [1, 4, 6, 5, 2, 7, 9] | def consecutive_numbers(lst):
count = 0
for i in range(len(lst)-1):
if lst[i+1] - lst[i] == 1:
count += 1
else:
count = 0
return count
# Test Code
lst = [1, 4, 6, 5, 2, 7, 9]
result = consecutive_numbers(lst)
print(result)
# Output --> 2 |
[DE Wikipedia] Live at the Berlin Philharmonic 1977
Live at the Berlin Philharmonic 1977 ist ein Jazzalbum von Hal Galper. Die am 4. November 1977 auf den Berliner Jazztagen in der Berliner Philharmonie entstandenen Aufnahmen erschienen am 15. Januar 2021 auf Origin Records. Hintergrund Der Pianist Hal Galper hatte – ... | null | null | null |
null | Create a Python script that generates a list of the prime numbers between two given numbers. The script should use the Sieve of Eratosthenes algorithm to generate the prime numbers | Start=1, End=20 | def sieve_of_eratosthenes(start, end):
prime = [True] * (end + 1)
p = 2
while p * p <= end:
if prime[p]:
for i in range(p * p, end + 1, p):
prime[i] = False
p += 1
prime_numbers = []
for p in range (start, end):
if prime[p]:
prime_numb... |
null | Train a logistic regression model using Scikit-Learn. | import numpy as np from sklearn.linear_model import LogisticRegression X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) Y = np.array([0, 0, 1, 1]) | model = LogisticRegression(solver='lbfgs') model.fit(X, Y) |
null | Write a function in C that returns the maximum element in an integer array. | int findMaximum(int arr[], int size) { int max = arr[0]; for (int i=1; i<size; i++) if (arr[i] > max) max = arr[i]; return max; } | |
[EN Wikipedia] Pavelló de la Vall d'Hebron
The Pavelló de la Vall d'Hebron () is an indoor venue located in Barcelona, Spain. The building was completed in 1991 for the Games. For the 1992 Summer Olympics, it hosted the basque pelota demonstration and the volleyball preliminaries. For the 1992 Summer Paralympics, it h... | null | null | null |
null | Construct a list in Python that contains the names of the months in order, starting with January. | months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] | |
null | Generate a class in python to represent a student with properties described below:
- name: a string
- age: an integer
- marks: an array of integers | student1 {
name: "John",
age: 18,
marks: [80,90,85]
} | class Student:
def __init__(self, name, age, marks):
self.name = name
self.age = age
self.marks = marks
def get_name(self):
return self.name
def get_age(self):
return self.age
def get_marks(self):
return self.marks |
null | Use the given code to optimize the dimensions of a beam. Import the necessary libraries and define the parameters P and E. Define the objective function to calculate the volume of the beam. Define the constraints for the optimization problem. Use the fmin_cobyla function to find the optimal dimensions of the beam. Prin... | from scipy.optimize import fmin_cobyla
import sys, os, subprocess, numpy
P, E = 1000.0, 69e9 # N, Pa, m, m
fileName = 'optimizeTest.txt'
resultName = '../TestsResults/opt.txt'
def objective(x):
height = x[0]
width = x[1]
length = x[2]
volume = length * width * height
return volume
def g0(x):
... | |
null | Create a Python program to scrape data from a website. The program should accept the website's URL as input. | https://example.com | import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Scrape data from the website
# ...
# ... |
null | How to create a basic HTML page in JavaScript? | We can create a basic HTML page using the document.write() method. The syntax to create an HTML page using document.write() is as follows: document.write("<html>"); document.write("<head>"); document.write("<title>My Page</title>"); document.write("</head>"); document.write("<body>"); document.write("My first web page ... | |
null | Convert this Python function to JavaScript. | def string_to_num_list(string):
numbers = []
for letter in string:
numbers.append(ord(letter))
return numbers | function stringToNumList(string) {
let numbers = [];
for (let letter of string) {
numbers.push(letter.charCodeAt(0));
}
return numbers;
} |
null | Write a Bash script for creating a directory in the current working directory. | #!/bin/bash # Create a directory mkdir myDir | |
[EN Wikipedia] Albedo
Albedo (; ) is the fraction of sunlight that is diffusely reflected by a body. It is measured on a scale from 0 (corresponding to a black body that absorbs all incident radiation) to 1 (corresponding to a body that reflects all incident radiation). Surface albedo is defined as the ratio of radios... | null | null | null |
[CS Wikipedia] Recep Tayyip Erdoğan
Recep Tayyip Erdoğan (tureckou výslovností ; * 26. února 1954 Istanbul) je prezident Turecké republiky, bývalý starosta Istanbulu a v letech 2003 až 2014 turecký premiér. Život Erdoğan se narodil na předměstí Istanbulu ve čtvrti Kasımpaşa, v rodině, která se sem přestěhovala z provi... | null | null | null |
null | Name the components of a typical machine learning pipeline. | A typical machine learning pipeline consists of data pre-processing, model training, model evaluation and model deployment. Data pre-processing involves cleaning, formatting, and transforming the data, while model training involves selecting an appropriate model and using it to learn from the data. Model evaluation eva... | |
null | Create a HTML page with a form that takes in two numbers as input and adds them together when the form is submitted. | <!DOCTYPE html> <html> <head> <title>Adding Form</title> </head> <body> <form action="" method="post"> <input type="number" name="a"> <input type="number" name="b"> <input type="submit" value="Submit" /> </form> <script> document.querySelector('form').onsubmit = function(event) { event.preventDefault(); const a = Numbe... | |
[DE Wikipedia] Weißschwanz-Antilopenziesel
Der Weißschwanz-Antilopenziesel (Ammospermophilus leucurus) gehören zur Gattung der Antilopenziesel. Er kommt in Teilen der westlichen Vereinigten Staaten sowie in Mexiko (Baja California) vor. Merkmale Weißschwanz-Antilopenziesel haben eine Länge von 18 bis 23 cm und ein Gew... | null | null | null |
null | Build a mathematical model in Python to calculate the probability of heads on a coin toss. | def probability_of_heads(n):
total_outcomes = 2**n
heads_outcomes = total_outcomes/2
probability_of_heads = heads_outcomes / total_outcomes
return probability_of_heads | |
[HI Wikipedia] अकबर
जलाल उद्दीन मोहम्मद अकबर () (15 अक्तूबर, 1542 ,७ अक्तूबर, १६०५) तैमूरी वंशावली के मुगल वंश का तीसरा शासक थे। अकबर को अकबर-ऐ-आज़म (अर्थात अकबर महान), शहंशाह अकबर, महाबली शहंशाह के नाम से भी जाने जाते हैं। सम्राट अकबर मुगल साम्राज्य के संस्थापक जहीरुद्दीन मुहम्मद बाबर का पौत्र और नासिरुद्दीन हुमायूं ... | null | null | null |
null | Write a Python algorithm to compute the number of islands. An island is a group of connected 1s in an array where all four adjacent lands have value 0. | def count_islands(grid):
if not grid:
return 0
row = len(grid)
col = len(grid[0])
num_islands = 0
for i in range(row):
for j in range(col):
if grid[i][j] == 1:
num_islands += dfs(grid, i, j, row, col)
return num_islands
def ... | |
null | Create a Python function that takes two lists, compare them, and return True if both lists are identical and False if they differ. | list1 = [1, 2, 3]
list2 = [1, 2, 3] | def compare_lists(list1, list2):
if len(list1) != len(list2):
return False
for i in range(len(list1)):
if list1[i] != list2[i]:
return False
return True |
null | What is the Big-O notation of a given algorithm | Big-O notation is a method of expressing the time complexity of an algorithm. It quotes the upper bound of an algorithm’s running time in terms of a function of the size of the input data. This is useful for determining the efficacy of an algorithm as different inputs of different sizes require different run times from... | |
[DE Wikipedia] Living Targets
Living Targets ist das dritte Studioalbum der Beatsteaks. Geschichte Es ist das erste Album der Beatsteaks mit Torsten Scholz am Bass. Das Album sollte ursprünglich The Ordinary Me heißen, weswegen das erste Lied auch mit den Worten „My name is Tom and I am funky“ beginnt. Jedoch wurde di... | null | null | null |
null | Generate a random number between 1 and 10 using Python. | import random
# Generate a random number between 1 and 10
random_number = random.randint(1, 10)
print(random_number) | |
[DE Wikipedia] Castello di Rende
Das Castello di Rende (auch Castello Normanno genannt) ist eine Burg aus dem 11. Jahrhundert im historischen Zentrum von Rende in der italienischen Region Kalabrien. Dort ist heute ein Museum für zeitgenössische Kunst untergebracht, das nach Roberto Bilotti Ruggi d’Aragón benannt ist. ... | null | null | null |
null | Write a Python code to search for an input keyword in the given string and replace it with another keyword. | str = "Hello, world"
search_substring = "world"
replace_substring = "Earth" | str = "Hello, world"
search_substring = "world"
replace_substring = "Earth"
def replace_substring(str, search_substring, replace_substring):
if search_substring in str:
str = str.replace(search_substring, replace_substring)
return str
print(replace_substring(str, search_substring, replace_substring)... |
[CS Wikipedia] Cordulia
Cordulia je rod vážek z čeledi lesklicovitých. Česky je rod pojmenovaný lesklice, stejně jako rody Antipodochlora, Epitheca, Oxygastra a Somatochlora . Na celém světě existují 3 druhy tohoto rodu. V Česku se vyskytuje jen jeden druh, lesklice měděná. Seznam druhů Seznam podle Cordulia aenea (Li... | null | null | null |
null | Create a function that takes an array as a parameter and continuously adds each item to the total sum. | arr = [6, 4, 3, 10] | def addItems(arr): total = 0 for number in arr: total = total + number return total |
null | Create a function in Python that takes as input a list of strings and returns a dictionary of all the unique words and their frequency | The list of strings is ["hello", "world", "hello", "goodbye"] | def get_freq_dict(strings):
words = set()
freq_dict = {}
for string in strings:
words.update(string.split(' '))
for word in words:
freq_dict[word] = strings.count(word)
return freq_dict
strings = ["hello", "world", "hello", "goodbye"]
freq_dict = get_freq_dict(strings)
print(freq_dict) # prints {... |
null | Create a function that takes three parameters and adds them together. | No input. | def my_func(a, b, c): return a + b + c |
null | Implement a program in Python to find the average of an array of length n. | Input: [2, 4, 6, 8, 10] | def findAverage(arr):
# Initialize sum
sum = 0
# Iterate over the array to calculate sum
for n in arr:
sum += n
# Calculate the average and return
return sum/len(arr)
# Driver code
arr = [2, 4, 6, 8, 10]
print(findAverage(arr)) |
[DE Wikipedia] Grafschaft Beaumont-le-Roger
Die Grafschaft Beaumont-le-Roger heißt eigentlich Grafschaft Beaumont; der Zusatz ist lediglich eine Erweiterung des Namens des Hauptortes Beaumont-le-Roger nach Roger de Beaumont, dem ersten Herren von Beaumont, dient aber auch dazu, die Grafschaft Beaumont-le-Roger von and... | null | null | null |
[DE Wikipedia] Miyako-Sprache
Die Miyako-Sprache (Eigenbezeichnung: //, Myāku-futsu; jap. Miyako-hōgen „Miyako-Dialekt“) gehört zu den Ryūkyū-Sprachen und wird auf den Miyako-Inseln in der japanischen Präfektur Okinawa gesprochen. Unterschieden wird die Miyako-Sprache noch in den Miyako-Dialekt auf Miyako-jima, den Ir... | null | null | null |
null | Create a Python program to classify a text document into one of five categories (news, sports, health, politics, and entertainment). | Document text | import nltk
import string
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
# Data for model training
categories = ["news", "sports", "health", "politics", "entertainment"]
data = {
"news": [["This is a news article."], ["An event occurred in the news today."]],
"sports": [["A huge basketball... |
[HI Wikipedia] रक्सौल
रक्सौल (Raxaul) भारत के बिहार राज्य के पूर्वी चम्पारण ज़िले में स्थित एक शहर है। नेपाल सीमा रक्सौल भारत-नेपाल सीमा पर स्थित है और अपने चीनी उद्योग के कारण जाना जाता है। इसके पास ही नेपाल का बीरगंज स्थित है। बीरगंज रेलवे स्टेशन नेपाल सरकार रेलवे (NGR) से भारत की सीमा के पार बिहार के रक्सौल स्टेशन ... | null | null | null |
null | Create a Python program to build a dictionary of each unique word in the text and the number of times it appears. | text = "In computing, a hash table (hash map) is a data structure which implements an associative array abstract data type, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found." | words = text.split(' ')
words_dict = {}
for word in words:
if word not in words_dict:
words_dict[word] = 1
else:
words_dict[word] += 1
print(words_dict) |
null | Create a text classification model using Scikit-learn to classify a message with either "positive" or "negative" sentiment. | from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import LogisticRegression # Vectorize the message into a format that the model can accept vect = CountVectorizer().fit(X_train) X_train_vectorized = vect.transform(X_train) # Train a Logistic Regression model model = LogisticRegressio... | |
null | Design a CSS style to make an element a circle and have a red border | #circle { width: 50px; height: 50px; border-radius: 50%; border: 1px solid red; } | |
null | Create a Python program to compare two given strings and returns the number of mismatched letters. | string1 = "abcdefg"
string2 = "accfghe" | def compare_strings(string1, string2):
mismatched = 0
for i in range(min(len(string1), len(string2))):
if string1[i] != string2[i]:
mismatched += 1
return mismatched
string1 = "abcdefg"
string2 = "accfghe"
compared = compare_strings(string1, string2)
print("Number of mismatched letters... |
null | Generate a regular expression to match a valid email address. | /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/ | |
null | Rewrite the following if-statement into a switch statement. | if (grade == "A") { gradeValue = 4.0; } else if (grade == "B") { gradeValue = 3.0; } else if (grade == "C") { gradeValue = 2.0; } else if (grade == "D") { gradeValue = 1.0; } | switch(grade) { case 'A': gradeValue = 4.0; break; case 'B': gradeValue = 3.0; break; case 'C': gradeValue = 2.0; break; case 'D': gradeValue = 1.0; break; default: gradeValue = 0; break; } |
null | Design an algorithm in Python which will traverse a linked list and select all elements that are greater than 10. | # Linked List Node
class Node:
# Constructor to initialise the node object
def __init__(self, data):
self.data = data
self.next = None
# Linked List class contains a Node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Traverses linked list and ... | |
null | Write a function in Python to convert a dictionary into a list and then sort the list alphabetically. | Example Dictionary: {'a':1, 'b':2, 'c':3} | def dict_to_sorted_list(d):
# Convert Dictionary to List
lst = list(d.items())
# Sort List Alphabetically
lst.sort(key=lambda x: x[0])
return lst
example_dict = {'a':1, 'b':2, 'c':3}
sorted_list = dict_to_sorted_list(example_dict)
print(sorted_list)
# Output:
# [('a', 1), ('b', 2), ('c', 3)] |
null | Create a script in Python that checks a provided URL for a specific keyword within its content and outputs either a pass or fail result. | URL: http://www.example.com
Keyword: success | import requests
url = 'http://www.example.com'
keyword = 'success'
r = requests.get(url)
if keyword in r.text:
print('Pass')
else:
print('Fail') |
null | Write a script in Python for printing the given second level sub-dictionary. | data = {'first': {'A': 1, 'B': 2}, 'second': {'C': 3, 'D': 4}} | second_dict = data.get('second') for key, value in second_dict.items(): print(key, value) |
[CS Wikipedia] Pneumatické zařízení
Pneumatické zařízení je mechanický stroj, který využívá tlaku plynu k přenesení nebo zvětšení síly. Pneumatická zařízení využívají často i rozdílu mezi atmosférickým tlakem a tlakem plynu (přetlak nebo podtlak), příp. proudění plynu. Princip pneumatických zařízení spočívá v tom, že ... | null | null | null |
null | Create a python generator that prints fibonacci numbers from n to 2*n-1. | n = 10 | def fibonacci_generator(n): a, b = 0, 1 while a < 2 * n - 1: yield a a, b = b, a + b |
[EN Wikipedia] Girls Do Not Joke
Girls Do Not Joke (Italian: Ragazze non scherzate) is a 1929 Italian silent comedy film directed by Alfred Lind and starring Leda Gloria, Maurizio D'Ancora and Giuseppe Pierozzi. Cast Isa Bluette Maurizio D'Ancora Leda Gloria Piero Pastore Giuseppe Pierozzi References Bibliography Ricc... | null | null | null |
[CS Wikipedia] Evropa
Evropa je území vnímané buďto jako jeden ze šesti světadílů v jejich tradičních pojetích, nebo jako západní část Eurasie. Ze severu jej ohraničuje Severní ledový oceán, ze západu Atlantský oceán, z jihu Středozemní a Černé moře spolu s vodními cestami, které je spojují, a z východu Asie (o přesné... | null | null | null |
[DE Wikipedia] Barcode (Band)
Barcode war eine dänische Hardcore-Band aus Aarhus. Sie war die Band von Gitarrist Jacob Bredahl, der von 1997 bis 2007 auch der Sänger von Hatesphere war. Geschichte Die Band wurde 1995 in Dänemark gegründet und veröffentlichte ein Jahr später ihr erstes Demo. Das Debütalbum Hard Jet Sup... | null | null | null |
null | Read a code and identify the data type of the variables a and b | a = 8 b = "Hello" | A is an integer and B is a string. |
null | Create a function which takes in an array and returns a list of all the elements which appear only once in the array. | def find_unique_elements(arr): unique_elements = [] for elem in arr: if arr.count(elem) == 1: unique_elements.append(elem) return unique_elements | |
null | Create a Python 3 function that takes a list of integers as an input and output the maximum sum of an increasing subsequence of the list. | [10, 12, 4, 6, 5, 3] | def max_inc_subseq_sum(arr):
n = len(arr)
max_sum = [0]*n
for i in range(n):
max_sum[i] = arr[i]
for i in range(1, n):
for j in range(i):
if arr[i] > arr[j] and max_sum[i] < max_sum[j] + arr[i]:
max_sum[i] = max_sum[j] + arr[i]
return max(max_sum)
print(max_inc_subseq_sum([10, 1... |
null | Create an HTML form containing four text inputs: Name, Email, Phone Number and Address. | <form> <label>Name: <input type="text" name="name"> </label> <label>Email: <input type="text" name="email"> </label> <label>Phone Number: <input type="text" name="phone"> </label> <label>Address: <input type="text" name="address"> </label> </form> | |
null | Convert the following JSON string to a valid Python dictionary. | '{"name": "John", "age": 32, "city": "New York"}' | data = json.loads('{"name": "John", "age": 32, "city": "New York"}') |
[CS Wikipedia] Oldřich Kníchal
Oldřich Kníchal (9. ledna 1939 Humenné – 21. března 2021) byl novinář, spisovatel a překladatel, píšící česky, slovensky a esperantsky, překládal z maďarštiny. Život V Praze vystudoval historii a filologii, pracoval jako redaktor ČTK, přispíval do různých deníků, redigoval časopisy v esp... | null | null | null |
null | In Python, create an algorithm for efficiently sorting a list of numbers in ascending order. | [4,7,2,1,11,0,29] | def sort_list(numbers):
for i in range(len(numbers)-1):
for j in range(i+1, len(numbers)):
if numbers[i] > numbers[j]:
numbers[i], numbers[j] = numbers[j], numbers[i]
return numbers |
null | Develop a Python program that finds the maximum value in a given array. | [1, 2, 7, 4, 5] | def findMax(arr):
max = arr[0]
for i in range(1, len(arr)):
if max < arr[i]:
max = arr[i]
return max
max_num = findMax([1,2,7,4,5])
print(max_num) |
[CS Wikipedia] Margaret Beachamová
Margaret Beachamová (* 28. září 1946) je bývalá britská atletka, běžkyně, která se věnovala středním tratím. Sportovní kariéra Na přelomu 60. a 70. let 20. století patřila k evropské mílařské špičce. Jejím největším úspěchem je titul halové mistryně Evropy v běhu na 1500 metrů z roku... | null | null | null |
null | Build a Python program to print out the 3 largest odd numbers in a given list. | [4, 7, -1, 2, 8, 5] | list_of_nums = [4, 7, -1, 2, 8, 5]
largest_odd_numbers = []
for num in list_of_nums:
if num % 2 != 0 and len(largest_odd_numbers) < 3:
largest_odd_numbers.append(num)
largest_odd_numbers.sort()
print (largest_odd_numbers) |
null | Given a list of strings, write a Python program to calculate the maximum length of a string. | list_of_strings = ["dog", "cat", "elephant", "bird"] | max_length = 0
for string in list_of_strings:
max_length = max(max_length, len(string))
print(max_length) |
[CS Wikipedia] Martin Horváth
Martin Horváth (27. prosince 1982 – 21. dubna 2016 Tomice II) byl český fotbalový záložník. Jeho bratrem je zpěvák Vlastimil Horváth. Fotbalová kariéra V české lize hrál za FC Marila Příbram. Nastoupil ve 3 ligových utkáních. Ligová bilance Literatura Radovan Jelínek, Miloslav Jenšík a ko... | null | null | null |
null | Create a python program to assess whether or not a movie genre is representing violent behavior, given a review of the movie. | Review: The movie is full of thrilling action scenes and lots of violence. | """
Create a program to assess whether or not a movie genre is representing violent behaviour
"""
import nltk
from nltk.tokenize import word_tokenize
def classify_movie(review):
# Tokenize review
tokens = word_tokenize(review)
# Check for violent words in the review
violent_words = ['violence', 'viol... |
null | Design a sorting algorithm in Python that is capable of sorting very large lists. | [25, 6, 7, 3, 12, 89, 74, 55] | def sort(array):
for i in range(len(array)):
low = i
for j in range(i+1, len(array)):
if array[low] > array[j]:
low = j
array[i], array[low] = array[low], array[i]
return array
example = [25, 6, 7, 3, 12, 89, 74, 55]
sorted_array = sort(example)
print(sorted... |
null | Create a function to add two integers x and y. | def add_two_integers(x, y): return x + y | |
null | Write a function that returns the day of the week given a date. | date = '2020-12-30' | date = '2020-12-30' import datetime def getDayofWeek(date): # Convert the string to datetime d = datetime.datetime.strptime(date, "%Y-%m-%d") # Return the day of the week return d.strftime("%A") print(f"The day of the week for {date} is {getDayofWeek(date)}.") |
null | Create a SQL query that returns the maximum and minimum order amounts from the database. | SELECT MAX(order_amount) AS max_order, MIN(order_amount) AS min_order FROM orders; | |
null | Create a class named “Vehicle” that has 3 instance variables. | class Vehicle: def __init__(self, name, color, max_speed): self.name = name self.color = color self.max_speed = max_speed | |
null | Use the OpenGL API to create a vertex buffer object (VBO). | GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); | |
null | Add a try-except clause to the given code to catch IndexError exceptions. | list1 = [1, 2, 3] print(list1[5]) | try: list1 = [1, 2, 3] print(list1[5]) except IndexError: print("IndexError occurred.") |
null | Find the index of the letter 'a' in the string 'abcde'. | string = "abcde" | Index of 'a' in the given string is 0. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.