text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
How can you generate a random number between 1 to 10 using Python?
import random random.seed() print(random.randint(1, 10))
null
Create a basic REST API endpoint with Python's Flask-Restful library that returns the sum of two numbers when the endpoint is visited.
Not applicable
from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class Sum(Resource): def get(self, a, b): return {'sum': a + b} api.add_resource(Sum, '/sum/<int:a>/<int:b>') if __name__ == '__main__': app.run()
null
What data structure do you choose to represent a sparse matrix in programming?
A sparse matrix can be represented using a hashmap (dictionary) data structure. The hashmap will contain the non-zero elements of the matrix, where each entry will include the row index, column index and the value at that location. This helps in storing and retrieving massive amounts of data in an efficient manner.
null
This code creates archives compatible with ESP32-S* ROM DFU implementation. To use it, run the script with the "write" command and provide the following arguments: - "-o/--output-file": the filename for storing the output DFU image (required) - "--pid": the hexadecimal product identifier (required) - "--json": an optio...
#!/usr/bin/env python # # Copyright 2020-2021 Espressif Systems (Shanghai) CO LTD # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
null
Write a function in Python that takes a set of numbers and prints the sum, mean and standard deviation of the numbers.
[1, 2, 3, 4, 5]
def print_stats(numbers): sum = 0 for i in numbers: sum = sum + i mean = sum / len(numbers) ssd = 0 for i in numbers: ssd = ssd + (i-mean)**2 ssd = ssd / len(numbers) standard_dev = sqrt(ssd) print("Sum = ", sum) print("Mean = ", mean) print("Standard Devia...
null
Create a Python program to build a language model. The model should take a sequence of words as input and predict the next word in the sequence.
Not applicable
import numpy as np from keras.preprocessing.text import Tokenizer from keras.layers import Embedding, LSTM from keras.models import Sequential # tokenizing the text tokenizer = Tokenizer() tokenizer.fit_on_texts(<some text>) sequences = tokenizer.texts_to_sequences(<some text>) vocab_size = len(tokenizer.word_index) ...
null
Use Python to solve the following equation: y = x^2 - x + 1
def solve_equation(x): return x**2 - x + 1
null
Create a basic search engine in Python using a TF-IDF algorithm. The search engine should take a query and a set of documents as input and return the document most relevant to the query.
Query: "running shoes" Documents: Document 1: "New running shoes perfect for running" Document 2: "The best fitting shoes for running" Document 3: "Running is a great way to exercise"
from sklearn.feature_extraction.text import TfidfVectorizer # documents to be indexed documents = ['New running shoes perfect for running', 'The best fitting shoes for running', 'Running is a great way to exercise'] # query query = 'running shoes' # vectorizer object vectorizer = TfidfVectorizer() # transform doc...
[CS Wikipedia] Kamila Chudziková Kamila Chudziková (* 12. září 1986, Kielce) je polská atletka, která se věnuje halovému pětiboji a sedmiboji na dráze. Na berlínském mistrovství světa 2009 získala bronzovou medaili, ke které ji pomohly i dva nové osobní rekordy, v běhu na 200 metrů a kouli. Jejím osobním rekordem v se...
null
null
null
null
Create an HTML form to allow the user to register an account with an email address and a password.
<form action="/register" method="POST"> <label for="email">Email:</label> <input type="email" name="email" required> <br><br> <label for="password">Password:</label> <input type="password" name="password" required> <br><br> <input type="submit" value="Create an Account" name="register"> </form>
[DE Wikipedia] Going Upriver Going Upriver: The Long War of John Kerry ist eine Dokumentation des US-amerikanischen Regisseurs George Butler über den Militärdienst des US-Präsidentschaftskandidaten John Kerry in Vietnam und seine anschließende Beteiligung in der Friedensbewegung und dem Protest gegen den Vietnamkrieg....
null
null
null
null
Given a Python script,rewrite it in Java.
def add(x, y): z = x + y return z
public int add(int x, int y) { int z = x + y; return z; }
null
Create a function that takes two numbers and returns their greatest common divisor in Python.
""" Create a function that takes two numbers and returns their greatest common divisor in Python. """ def greatest_common_divisor(a, b): if a == 0: return b if b == 0: return a if a == b: return a if a > b: return greatest_common_divisor(a - b, b) return greatest_common_divisor(a, b - a) if __name__ == '__main__': prin...
[CS Wikipedia] Vnitřní energie Vnitřní energie (též termodynamická energie) tělesa (termodynamického systému) je extenzivní veličina představující v makroskopickém popisu souhrn energií všech částic, z nichž se těleso skládá. Jde především o jejich kinetickou a potenciální energii, ale může jít také o elektrickou či c...
null
null
null
null
Write a Python program to print the number of prime numbers that exist within a given range.
def primeCounet(start, end): count = 0 for num in range(start, end + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: count = count + 1 return count if __name__ == "__main__": start = 10 ...
[HI Wikipedia] फ्लिपकार्ट फ्लिपकार्ट भारत में स्थित एक ई-कॉमर्स कम्पनी है, जिसका मुख्यालय बंगलौर में स्थित है। इसकी शुरुआत 2007 में सचिन बंसल और बिनी बंसल ने एक ऑनलाइन स्टोर के रूप में की थी, जिसमें मूल रूप से पुस्तकें बेची जाती थी। बाद में इसमें अन्य कई तरह के वस्तुओं को बेचा जाने लगा। 2018 में अमेरीकी कंपनी वॉलमार्ट...
null
null
null
null
Write a JavaScript code snippet to toggle a div's visibility.
const toggleDiv = () => { const div = document.querySelector('.div'); if (div.style.display === 'none') { div.style.display = 'block'; } else { div.style.display = 'none'; } }
[DE Wikipedia] Lisboa-Insel Die Lisboa-Insel () ist eine Insel im Wilhelm-Archipel vor der Graham-Küste des Grahamlands im Norden der Antarktischen Halbinsel. Sie ist die südlichste der kleinen Inseln vor dem südlichen Ende der Petermann-Insel. Teilnehmer der Fünften Französischen Antarktisexpedition (1908–1910) karti...
null
null
null
[CS Wikipedia] Třetí vláda Viliama Širokého Třetí vláda Viliama Širokého existovala v období 11. července 1960 – 20. září 1963. Seznam členů vlády Předseda vlády: Viliam Široký od 21. 3. 1953 Místopředseda vlády: Jaromír Dolanský Václav Kopecký, do 5. 8. 1961 (zemřel) Otakar Šimůnek Rudolf Barák, do 9. 2. 1962 Rudolf ...
null
null
null
null
Create an HTML table that contains 10 rows and 3 columns.
<table> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <t...
null
Write a Python program to find the most popular item purchased by customers.
Table = customers | customer_id | month | city | item | amount | |-------------|-------|-------|---------|--------| | 1 | 1 | LA | pen | 500 | | 2 | 2 | NY | pencil | 600 | | 3 | 3 | LA | pen | 700 | | 4 | 4 | SF | eraser | 800 ...
from collections import Counter customers = [ {'customer_id': 1, 'month': 1, 'city': 'LA', 'item': 'pen', 'amount': 500}, {'customer_id': 2, 'month': 2, 'city': 'NY', 'item': 'pencil', 'amount': 600}, {'customer_id': 3, 'month': 3, 'city': 'LA', 'item': 'pen', 'amount': 700}, {'customer_id': 4, 'month': 4, 'city':...
null
Generate the MD5 hash of the given string.
Hello World
a7ad492532f2f806e140722d00453901
null
Generate a valid SQL query to get the total number of people in each job type
SELECT job_type, COUNT(*) FROM table_name GROUP BY job_type;
null
Given an array of integers, write an algorithm to find the maximum difference between any two elements in the array.
nums = [3, 2, 7, 1, 4]
def find_max_difference(nums): # Initialize a max difference max_diff = float('-inf') # Iterate through the array for i in range(1, len(nums)): diff = nums[i] - nums[i-1] if diff > max_diff: max_diff = diff return max_diff # Call the function find_max_difference([3, 2, 7, 1, 4]) # returns 6
[CS Wikipedia] Seznam esperantských organizací Mimo velkých vyjmenovaných svazů, existuje řada mezinárodních esperantských svazů, jako je mj. automobilový, nevidomých esperantistů, filatelistů, filologie, matematiků, hudebníků, ornitologů, radioamatérů, skautů, šachistů, turistů, vegetariánů, poštovních a telegrafních...
null
null
null
null
Construct a python program to capture a user’s input and print the input back out to the console.
# Accepting user input name = input("Please enter your name: ") # Printing out the user input print("Hello, ", name, "!")
[DE Wikipedia] Stefan Bogoridi Stefan Bogoridi (, gr. Στέφανος Βογορίδης/Stefanos Vogoridis, türk. Stefanaki Bey, rum. Ştefan Vogoride), geboren als Stojko Zonkow Stojkow (bulg. ; * 1775 in Kotel, Osmanisches Reich; † 1. August 1859 in Istanbul/Zarigrad) war ein bulgarisch-osmanischer Beamter, außenpolitischer Berater...
null
null
null
null
Create a SQL query that returns the average number of orders per month for customers in California.
SELECT AVG(NumOrders) FROM (SELECT COUNT(OrderId) AS NumOrders FROM Orders WHERE State = 'CA' GROUP BY MONTH(OrderDate)) AS TotalOrders;
null
Create a python script that takes three required parameters 'x', 'y' and 'z' and prints the result of x * y * z
x=4 y=3 z=2
def multiply(x, y, z): return x * y * z print(multiply(4, 3, 2)) //output 24
[EN Wikipedia] Jawahar Navodaya Vidyalaya Medak Jawahar Navodaya Vidyalaya Medak ( Telugu: జవహర్ నవోదయ విద్యాలయము, వర్గల్ ) (Hindi: जवाहर नवोदया विद्यलया ) known as JNV Wargal or JNV Medak is a central government co-education school located in Wargal, Medak. The School is an autonomous body under the Ministry of Educa...
null
null
null
null
Generate a program in Python to classify a series of numbers into even or odd.
[4, 7, 9, 11, 12]
def classify_numbers(nums): for num in nums: if (num % 2) == 0: print(str(num) + " is even") else: print(str(num) + " is odd") nums = [4, 7, 9, 11, 12] classify_numbers(nums) # Output: # 4 is even # 7 is odd # 9 is odd # 11 is odd # 12 is even
null
How would you modify the following code to print the square of each number in the given list?
nums = [1, 2, 3, 4]
nums = [1, 2, 3, 4] for i in range(len(nums)): nums[i] = nums[i] * nums[i] print(nums) # [1, 4, 9, 16]
null
Make a class called 'Car' that stores information about a car and contains a function called 'start' which when called, prints out "Car has started".
class Car: def __init__(self): self.model = "" self.year = 0 def start(self): print("Car has started")
[HI Wikipedia] संजय गांधी थर्मल पावर स्टेशन संजय गांधी थर्मल पावर प्लांट दक्षिण पूर्व रेलवे (एसईआर) के बिलासपुर - कटनी अनुभाग के बिरसिंहपुर रेलवे स्टेशन पर स्थित है। जो मध्य प्रदेश, भारत के उमरिया जिले का हिस्सा है। बिजली घर संजय गांधी थर्मल पावर प्लांट की 1,340.00 मेगावाट की स्थापित क्षमता है। इस बिजली घर की पहली इका...
null
null
null
null
Extract all the words that begin with 's' from the given list.
list_of_strings = ['stack', 'super', 'stone', 'sit']
list_of_strings = ['stack', 'super', 'stone', 'sit'] words_start_s = [word for word in list_of_strings if word.startswith('s')] print(words_start_s)
[CS Wikipedia] Archeologické muzeum (Košice) Archeologické muzeum v Košicích je muzeum košického městského opevnění, konkrétně jeho Dolní brány. Areál byl odkryt během rekonstrukce Hlavní ulice (1995–1996) za primátora Rudolfa Schustera. Archeologický průzkum vedli košičtí památkáři Marcela Ďurišová a Jozef Duchoň. Pr...
null
null
null
null
Create a Regex pattern to validate mobile phone numbers.
^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$
null
Write a pseudocode to compare two strings and determine which is longer.
Function CompareStrings(str1, str2) if Length(str1) > Length(str2) return str1 else return str2 End Function
[DE Wikipedia] Rheinisches Braunkohlerevier Das Rheinische Braunkohlerevier, oft auch kurz Rheinisches Revier genannt, ist ein Bergbaurevier in der Kölner Bucht, am Nordwestrand des Rheinischen Schiefergebirges. Der Abbau der Braunkohle im Tagebauverfahren wirkte hier maßgeblich landschaftsverändernd und führte zur Au...
null
null
null
null
Write a Python program to convert a given string to one of its equivalent shell script command
string = "copy file1.txt file2.txt"
def string_to_shell_command(string): split_string = string.split() command_name = split_string[0] input_args = split_string[1:] command_args = '' for arg in input_args: command_args += f'"{arg}"' + ' ' return f'{command_name} {command_args}'
null
Critique the given code for best coding practices.
def calculate_total_sum(list_num): total_sum = 0 for num in list_num: total_sum += num return total_sum
The code could improve by using the built-in sum() from the Python library. Also, you should use a more meaningful variable name instead of list_num to better explain the intent of the code. Lastly, you could use type hinting to specify the type of variables passed into the function.
[EN Wikipedia] Eduardo Amorim (politician) Eduardo Amorim (born March 17, 1963) is a Brazilian politician. He has represented Sergipe in the Federal Senate since 2011. Previously he was a deputy from Sergipe from 2007 to 2011 and secretary of state of Sergipe from 2003 to 2004. He is a member of the Brazilian Social D...
null
null
null
null
Create a Python program that calculates the total cost of an online purchase.
ProductName: Powerbank, Quantity: 3, PriceEach: $15
def calculate_total_cost(product_name, quantity, price): return quantity * price total_cost = calculate_total_cost("Powerbank", 3, 15) print("Total cost of the purchase is $" + str(total_cost))
null
Create a web application usingPython and Flask that displays a simple "Hello World" page.
Not applicable
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == '__main__': app.run()
null
Create a code snippet in Python that calculates the sum of the digits of a number.
123
def sum_of_digits(number): sum_digits = 0 while number > 0: sum_digits += (number % 10) number //= 10 return sum_digits print(sum_of_digits(123))
null
Construct a for loop to access each element of the given array.
[1, 2, 3, 4]
arr = [1, 2, 3, 4] for i in range(len(arr)): print(arr[i])
null
Combine the two objects with the same property value.
obj1 = { "name": "John", "age": 22 } obj2 = { "name": "John", "location": "New York" }
obj3 = { "name": "John", "age": 22, "location": "New York" }
null
Modify the following Python code to handle errors.
def read_data_from_json(filename): with open(filename, 'r') as f: data = json.load(f) return data
def read_data_from_json(filename): try: with open(filename, 'r') as f: data = json.load(f) return data except FileNotFoundError: print("The file specified does not exist.") except json.decoder.JSONDecodeError: print("The file specified is not in a valid JSON forma...
null
Correct the error in the given SQL query.
SELECT * FROM Student st INNERJOIN School sc ON st.schoolID = sc.student
SELECT * FROM Student st INNER JOIN School sc ON st.schoolID = sc.schoolID
null
Suggest a code segment to generate a random integer in the range of 0 to 100 using Python.
import random random_int = random.randint(0, 100)
null
Edit a given Python program to optimize the time complexity.
def get_maximum_item(arr): maximum_number = float('-infinity') for item in arr: if item > maximum_number: maximum_number = item return maximum_number
def get_maximum_item(arr): if len(arr) == 0: return float('-infinity') maximum_number = arr[0] for item in arr[1:]: if item > maximum_number: maximum_number = item return maximum_number
null
Write an SQL query to retrieve all rows in a table that match a certain criteria.
Table: Users name | age ------|------ John | 20 Pete | 22 Alex | 18
SELECT * FROM Users WHERE age > 20;
[CS Wikipedia] Gravitační potenciální energie Gravitační potenciální energie je jeden z druhů mechanické energie, kterou má těleso v gravitačním poli. Jedná se o druh potenciální energie. Značení Značka: Ep Jednotka SI: joule, značka: J Další jednotky: viz Energie Výpočet Homogenní gravitační pole V homogenním gravita...
null
null
null
[DE Wikipedia] Der Sechs-Millionen-Dollar-Mann Der Sechs-Millionen-Dollar-Mann (Originaltitel: The Six Million Dollar Man) ist eine US-amerikanische Fernsehserie. Zwischen 1973 und 1978 wurden 106 Episoden in 5 Staffeln für den US-Sender ABC produziert. Im deutschsprachigen Fernsehen war sie erstmals beim Privatsender...
null
null
null
null
In Python, write a function that takes two integers a, b and returns a*b.
def multiply(a, b): return a * b
null
How to generate all permutations of a given list of items?
def permutation(lst): if len(lst) == 0: return [] if len(lst) == 1: return [lst] l = [] for i in range(len(lst)): m = lst[i] remLst = lst[:i] + lst[i+1:] for p in permutation(remLst): l.append([m] + p) return l
[CS Wikipedia] Square Jules-Ferry Square Jules-Ferry je square v Paříži v 11. obvodu. Historie Square bylo založeno v roce 1924 na ploše 5830 m2 uprostřed Boulevardu Jules-Ferry. Náměstí bylo pojmenováno po pařížském starostovi Julesovi Ferrym. V roce 1909 zde byla instalována kamenná socha, kterou vytvořil sochař Jea...
null
null
null
[DE Wikipedia] Liste der Wappen im Kreis Segeberg Diese Liste zeigt die Wappen des Kreises Kreises Segeberg (Schleswig-Holstein) mit seinen Städten, Gemeinden und Ämtern. Kreiswappen Amtsfreie Städte und Gemeinden Ämter Amt Auenland Südholstein Amt Bad Bramstedt-Land Amt Boostedt-Rickling Amt Bornhöved Amt Itzstedt Si...
null
null
null
null
Design an algorithm in Python to estimate future house prices.
import pandas as pd from sklearn.linear_model import LinearRegression # Read the data data = pd.read_csv('housing.csv') # Split into X and y X = data.drop('price', axis=1) y = data['price'] # Initialize the model model = LinearRegression() # Fit the model to the training data model.fit(X, y) # Estimate future prices u...
null
Generate a python program to simulate a simple dice game between two players.
Player-1: Alice Player-2: Bob
import random # initialise the scores Alice_score = 0 Bob_score = 0 while (Alice_score < 10 and Bob_score < 10): # generate dice numbers for both players Alice_val = random.randint(1,6) Bob_val = random.randint(1,6) # check if Alice wins if Alice_val > Bob_val: Alice_score += 1 # check if Bob wins if Bob_va...
null
Identify the purpose of the given lines of code.
# Create a boolean variable is_valid = True
The given code creates a boolean variable called is_valid and assigns it the value of True.
null
Write a function to determine if a given number is prime and returns true or false.
def is_prime(num): if num <= 1: return False for i in range(2, num): if num % i == 0: return False return True
[CS Wikipedia] Erzberg Erzberg je hora ve Štýrsku v Rakousku. Jedná se o významné naleziště železné rudy. Současná výška hory je 1 466 metrů nad mořem, před začátkem těžby to bylo 1 532 metrů nad mořem. Každoročně se v činném povrchovém dole a jeho blízkém okolí pořádá Erzbergrodeo – závod na terénních motocyklech v d...
null
null
null
null
Write a python program to automatically extract the following grade scores from the given text.
Text: “Johnny got 85 in Maths and 63 in English”
maths_score = 85 english_score = 63
null
Write a Python program to optimize a given mathematical expression.
x - 5 + (y * (1 + (z / 2)))
def optimize_expression(expr): expr_tree = ast.parse(expr, mode='eval') # transform expression expr_tree = ast.fix_missing_locations(ast.optimize_expression(expr_tree)) ast.increment_lineno(expr_tree, 1) # compile ast to python code compiled_expr = compile(expr_tree, '', 'eval') r...
[HI Wikipedia] डाइप्रोटोडान्शिया डाइप्रोटोडान्शिया या द्वि-आदिदन्ती (Diprotodontia) धानीप्राणी (मारसूपियल​) जानवरों का एक बड़ा जीवविज्ञानिक गण है जिसमें लगभग १२० जातियाँ आती हैं। इनमें कंगारू, वॉलाबी, कोआला, पॉस्सम और वोम्बैट शामिल हैं। कुछ विलुप्त जातियाँ भी इसमें आती हैं, जैसे कि गेंडे के आकार वाला डाएप्रोटोडोन और '...
null
null
null
null
Convert the following if-else block of code into a ternary expression.
if (condition){ do_something(); } else { do_something_else(); }
condition ? do_something() : do_something_else();
[EN Wikipedia] Pararrhaptica sublichenoides Pararrhaptica sublichenoides is a moth of the family Tortricidae. It was first described by Otto Swezey in 1913. It is endemic to the island of Hawaii. External links Archipini Endemic moths of Hawaii
null
null
null
null
Write a Python program to automatically format and validate user input.
Not applicable
import re def validate_input(input): # validate pattern: pattern = r"^[a-zA-Z]*$" # compile regex regex = re.compile(pattern) # check if input matches pattern if(regex.match(input)): # format the input input = input.lower().capitalize() # return formatted input return input else: # return error retur...
null
Write a Python function that accepts a list and returns the sum of the numbers present in the list.
list = [1, 2, 3, 4, 5]
def list_sum(lst): result = 0 for num in lst: result += num return result
null
Generate a set of Python classes for a game application. The classes should include a main Character class with fields for name, health, and inventory, and a Monster class with fields for name, health, and type (e.g. dragon, ogre, goblin).
Not applicable
class Character: def __init__(self, name, health=100): self.name = name self.health = health self.inventory = [] def add_item(self, item): self.inventory.append(item) def remove_item(self, item): self.inventory.remove(item) class Monster: def __init__(self, name, health=100, type="Monster"): self.name = na...
[DE Wikipedia] Schwedenkiste Die sogenannte Schwedenkiste ist ein zwanzig Foliobände umfassender Dokumentenbestand, in dem die Papiere von Ernst II. von Sachsen-Gotha-Altenburg, Johann Joachim Christoph Bode und anderen bedeutenden Freimaurern und Illuminaten überliefert sind. Der Name leitet sich von dem Umstand ab, ...
null
null
null
null
Can you develop a Python class to calculate the cross entropy loss between two probability distributions?
import numpy as np class CrossEntropy: def __init__(self): pass def loss(self, p, q): return - np.sum(p * np.log(q))
null
Given the HTML structure below, add a red background to the <h1> tag.
<h1>This is a heading</h1>
<h1 style="background-color: red;">This is a heading</h1>
null
Create a Python program that takes a sentence as input and returns a dictionary of the words and their frequencies
This is a sample sentence.
def word_frequency(sentence): words = sentence.split() freq = {word: words.count(word) for word in words} return freq sentence = 'This is a sample sentence.' result = word_frequency(sentence) print(result)
null
Calculate the average of the given two integers.
Integer 1: 2 Integer 2: 5
The average of 2 and 5 is 3.5.
[DE Wikipedia] Liste der Kurzgeschichten von Roald Dahl Die Liste der Kurzgeschichten von Roald Dahl führt in der chronologischen Reihenfolge der Erstveröffentlichungen alle bekannten Kurzgeschichten von Roald Dahl auf. Enthalten sind auch diejenigen Kurzgeschichten, die aus unterschiedlichen Gründen unveröffentlicht ...
null
null
null
null
The given code provides a set of functions and classes for testing in Python. To use this code, you can import the necessary functions and classes into your Python script. To run tests, you can create instances of the TestSuiteResult class and add instances of the TestModuleResult, TestClassResult, and TestResult class...
""" Copyright (c) 2012-2013, Austin Noto-Moniz (metalnut4@netscape.net) Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND...
[HI Wikipedia] कार्बन मोनोक्साइड कार्बन मोनोक्साइड (CO) (अंग्रेजी:Carbon monoxide) एक रंगहीन गैस है। यह गैस हवा से थोड़ी हल्की होती है। ऊँची सांद्रता में यह मनुष्यों और जानवरों के लिए विषाक्त होती है, हालाँकि कम मात्रा में यह कुछ सामान्य जैविक कार्यों के लिए उपयोगी साबित होती है। ढांचा कार्बन मोनोऑक्साइड एक कार्बन परम...
null
null
null
null
Train a machine learning model in Python to predict the COVID-19 fatalities in a given region.
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression # Load data data = pd.read_csv('data.csv') # Split data into features and targets X = data.drop(['Fatalities'], axis=1).values y = data['Fatalitie...
null
Create a Python script to extract the temperature from a JSON object.
{ "location": "Berlin", "weather": { "temperature": 17.6 } }
import json json_string = ''' { "location": "Berlin", "weather": { "temperature": 17.6 } } ''' data = json.loads(json_string) temperature = data["weather"]["temperature"] print(temperature) => 17.6
null
Can you build an algorithm in Python to sort an array with the Bubble Sort technique?
[2, 7, 4, 1, 5, 3]
def bubble_sort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # th...
null
Explain what overfitting is, in the context of machine learning.
Overfitting is a phenomenon in which a machine learning model performs better on training data than on new data. This occurs when a model is excessively complex and able to learn the underlying noise of the training data. As a result, the model doesn’t generalize well on previously unseen data and does not perform as e...
null
Develop a Python program that takes a list of numbers as an input and outputs the numbers in the list sorted in ascending order.
[5, 3, 7, 2, 4, 9, 1]
def sortAscending(list): list.sort() return list # Driver Code list = [5, 3, 7, 2, 4, 9, 1] print(sortAscending(list)) # Output: [1, 2, 3, 4, 5, 7, 9]
null
Develop a machine learning algorithm in Python that can classify an email as either spam or ham.
from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics import accuracy_score # Load the data X_train = [...] y_train = [...] X_test = [...] y_test = [...] # Create the count vectorizer vectorizer = CountVectorizer() X_train_vectors = vectorizer.f...
null
Write a python program to create a histogram of the given list elements
list: [1, 2, 4, 5, 6, 3, 2]
def create_histogram(list): hist = dict() for i in list: if i not in hist: hist[i] = 1 else: hist[i] += 1 return hist
[CS Wikipedia] French Open 2013 – čtyřhra juniorek Obhájcem titulu ve čtyřhře juniorek na pařížském French Open 2013 byl ruský pár Darja Gavrilovová a Irina Chromačovová, který se čtyřhry nezúčastnil. Gavrilovová již nemohla startovat pro věkové omezení a Chromačovová nastoupila do kvalifikace ženské dvouhry, kde byla...
null
null
null
null
Implement a solution for an online reservation system in Python. The system should allow for users to register and make reservations for products.
Sample product list: [ { id: 1, name: 'Sofa', price: 499.99 }, { id: 2, name: 'Table', price: 149.99 }, { id: 3, name: 'Chair', price: 79.99 } ]
import sqlite3 conn = sqlite3.connect('reservation_system.db') conn.execute(''' CREATE TABLE IF NOT EXISTS products ( product_id INTEGER PRIMARY KEY, product_name VARCHAR(20) NOT NULL, price DECIMAL NOT NULL )''') conn.execute("INSERT INTO products VALUES(1, 'Sofa', 499.99)") conn.execute("INSERT INTO products VALUE...
null
Create an API endpoint in Python with Flask that requires authentication.
users = {"John": "123456", "Jenny": "456789"}
from flask import Flask, request app = Flask(__name__) users = {"John": "123456", "Jenny": "456789"} @app.route('/', methods=['GET']) def root(): if request.authorization and request.authorization.username in users \ and request.authorization.password == users[request.authorization.username]: return 'Authentication suc...
null
Create an API in Python using Flask that takes an input string and returns a list of synonyms and antonyms for the input string.
Not applicable
from flask import Flask from flask_restful import Resource, Api from nltk.corpus import wordnet app = Flask(__name__) api = Api(app) class SynAntonyms(Resource): def get(self, word): syns = wordnet.synsets(word) synonyms = [] antonyms = [] for s in syns: for l in s.lemmas(): synonyms.append(l.name()) if l.ant...
null
Write a Java function to find out if a string contains any vowels.
public static boolean containsVowels(String input) { for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { return true; } } return false; }
null
Write a Python script to train a sentiment classifier on a given dataset.
Dataset containing sentences and labels, where each label represents the sentiment of the associated sentence.
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression df = pd.read_csv('dataset.csv') X_train, X_test, y_train, y_test = train_test_split(df['text'], df['label'], random_state=0) vectori...
null
Design a Python program to read numbers from a given array and determine if all numbers are divisible by 5.
array = [10, 15, 20, 25, 30]
def checkDivisible(array): for num in array: if num % 5 != 0: return False return True array = [10, 15, 20, 25, 30] if checkDivisible(array): print('All numbers are divisible by 5') else: print('Not all numbers are divisible by 5')
null
Write a Python program to generate a 3x4 matrix containing random numbers.
import random def generate_random_matrix(): matrix = [[random.randint(1, 10) for col in range(4)] for row in range(3)] return matrix
null
Create a JavaScript class that allows the user to choose the size, position and color of a textbox.
class Textbox { constructor(size, position, color) { this.size = size; this.position = position; this.color = color; } showTextbox() { const textbox = document.createElement("div"); textbox.style.width = this.size + "px"; textbox.style.position = this.position; textbox.style.background = this.color; document.body.appen...
null
Develop a class in Python to optimize the existing code.
def display_message(message): print(message) display_message('Hello World!')
class Display(): def __init__(self, message): self.message = message def display_message(self): print(self.message) message = input('Enter a message: ') display_obj = Display(message) display_obj.display_message()
null
Generate a Python function to generate prime numbers in a given range of numbers.
def generate_primes(start, end): # A list to store prime numbers primes = [] # Iterate from start to end and # check if number is prime or not for num in range(start, end + 1): isPrime = True for i in range(2, num): if (num % i == 0): isPrime = False ...
null
Create a Python class to represent a bank account.
class BankAccount: def __init__(self, owner, balance): self.owner = owner self.balance = balance def deposit (self, amount): self.balance += amount return self.balance def withdraw (self, amount): self.balance -= amount return self.balance
null
Write a script in python to print the first 10 Fibonacci numbers.
# Initialise the first two numbers of the sequence prev, nxt = 0, 1 # Iteratively compute and print out the Fibonacci numbers for i in range(10): #Print the current number in the sequence print(prev) #Compute the next number in the sequence prev, nxt = nxt, prev + nxt
[CS Wikipedia] Sipleův ostrov Sipleův ostrov (Siple Island) je ostrov u pobřeží Antarktidy. Nachází se ve Wrigleyho zálivu u pobřeží Země Marie Byrdové a je obklopen Getzovým ledovým šelfem. Je dlouhý 110 km a má rozlohu 6390 km². Ostrov je pokrytý sněhem a ledem, nejvyšším vrcholem je neaktivní štítová sopka Mount Si...
null
null
null