text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Design a class in C# to store employee details.
public class Employee { public string Name; public int Age; public string Department; public int Salary; public Employee(string name, int age, string department, int salary) { Name = name; Age = age; Department = department; Salary = salary; } }
null
Write a SQL query to fetch the name of employees and the sum of their salaries from the database.
SELECT name, SUM(salary) FROM employees GROUP BY name;
null
Explain the concept of parameter estimation in machine learning.
Parameter estimation is the process of determining the optimal values for the parameters of a machine learning algorithm. The values that produce the best performance on the training data are typically used as the parameters for the model. By optimizing the parameters, the model can fit the data more accurately and lea...
[EN Wikipedia] Aleksandr Gvardis Aleksandr Petrovich Gvardis (; born March 2, 1965) is a retired Russian football referee. He became a FIFA international referee in 2003, and his last known activity as a referee was in 2010. He lives in Kaliningrad and is a businessman. He has refereed games in the qualification round...
null
null
null
[CS Wikipedia] Padesát odstínů (filmová série) Filmová trilogie Padesát odstínů je zpracováním stejnojmenné knižní předlohy americké autorky E. L. James. Tři filmy (Padesát odstínů šedi, 2015; Padesát odstínů temnoty, 2017 a Padesát odstínů svobody, 2018) byly natočeny ve spolupráci s autorkou i jejím manželem, který ...
null
null
null
null
Convert the following pseudocode into a JavaScript program.
Input: A, B Output: maximum of A and B
function max(A, B) { if (A > B) { return A; } else { return B; } };
null
You need to write a Python code to revert a given list back to its original form.
my_list = [3, 2, 1, 4]
my_list = my_list[::-1]
null
Write a Python program to check if a string contains any special characters.
CS 1501
def has_special_characters(s): special_characters = '!@#$%^&*()_+-=[]{};:,.<>/?' for char in special_characters: if char in s: return True return False
[CS Wikipedia] Výkon Výkon je skalární fyzikální veličina, která vyjadřuje množství práce vykonané za jednotku času. Rozlišuje se průměrný výkon, který se vztahuje k určitému časovému intervalu, a okamžitý výkon, který se vztahuje k určitému časovému okamžiku. Množství energie spotřebované za jednotku času se označuje...
null
null
null
[DE Wikipedia] Vincent-Froideville Vincent-Froideville ist eine französische Gemeinde mit Einwohnern (Stand ) im Département Jura in der Region Bourgogne-Franche-Comté. Sie gehört zum Kanton Bletterans im Arrondissement Lons-le-Saunier. Sie entstand als Commune nouvelle am 1. April 2016 aus den bisherigen Gemeinden Vi...
null
null
null
null
Create a class in Python to convert raw text into a structured format.
class TextParser: """A class in Python to convert raw text into a structured format""" def __init__(self, text): self.text = text def parse(self): """This method will parse the given text and return it in a structured format""" # initialize an empty output array output...
null
Generate a list of odd numbers from 80 to 100.
[81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
null
Edit this HTML structure to add a footer at the bottom.
<html> <head> <title>My Website</title> </head> <body> </body> </html>
<html> <head> <title>My Website</title> </head> <body> <footer> <p>Copyright © 20
[CS Wikipedia] Prima Krimi Prima Krimi je kanál FTV Prima, který byl spuštěn 2. dubna 2018, na Velikonoční pondělí. Je zaměřený na nejrůznější zahraniční seriály a filmy, jako například Vraždy v Midsomeru, Sběratelé kostí, Castle na zabití, Námořní vyšetřovací služba L. A. nebo American Crime Story. Generální ředitel ...
null
null
null
null
Create a Python script to read CSV data and store the data in a Pandas DataFrame.
import pandas as pd # Read CSV data data = pd.read_csv("data.csv") # Store data to DataFrame df = pd.DataFrame(data)
null
Sort the given list of employee names alphabetically (A-Z).
employee_names = ['John', 'Lisa', 'Emily', 'Mia']
employee_names = ['John', 'Lisa', 'Emily', 'Mia'] sorted_employees = sorted(employee_names) print(sorted_employees)
null
Create a python function to count the number of unique elements from a given list.
arr = [1, 4, 2, 1, 5, 4, 3]
def count_unique_elements(arr): unique_elements = set(arr) return len(unique_elements) if __name__ == '__main__': arr = [1, 4, 2, 1, 5, 4, 3] print(count_unique_elements(arr))
null
Create a random forest model using Python to predict the type of wine from given data.
import pandas as pd from sklearn.ensemble import RandomForestClassifier # create data wine_data = pd.read_csv('wine.csv') # set features features = ['alcohol', 'type', 'sulphates', 'pH', 'quality'] x_train = wine_data[features] y_train = wine_data['type'] # create model model = RandomForestClassifier(n_estimators=100...
null
Implement a method in JavaScript to concatenate two strings together.
function concatenate(string1, string2) { return string1 + string2; }
[HI Wikipedia] महाभारत महाभारत भारत का एक प्रमुख काव्य ग्रंथ है, जो स्मृति के इतिहास वर्ग में आता है। इसे भारत भी कहा जाता है। यह काव्यग्रंथ भारत का अनुपम धार्मिक, पौराणिक, ऐतिहासिक और दार्शनिक ग्रंथ हैं। विश्व का सबसे लंबा यह साहित्यिक ग्रंथ और महाकाव्य, हिन्दू धर्म के मुख्यतम ग्रंथों में से एक है। इस ग्रन्थ को हिन्द...
null
null
null
null
Write a Python script that receives a string from the command line and prints out the string in reverse order.
"This is my string."
import sys input_string = sys.argv[1] print(input_string[::-1])
[EN Wikipedia] Miss Marple Miss Jane Marple is a fictional character in Agatha Christie's crime novels and short stories. Miss Marple lives in the village of St. Mary Mead and acts as an amateur consulting detective. Often characterized as an elderly spinster, she is one of Christie's best-known characters and has bee...
null
null
null
null
Parse the following JSON objects, convert all the values to strings and create a dictionary named "parsed_data".
{ "name": "John Doe", "age": 33, "locations": ["NYC", "LA"] }
import json parsed_data = {} data = { "name": "John Doe", "age": 33, "locations": ["NYC", "LA"] } for key, val in data.items(): parsed_data[key] = str(val)
[HI Wikipedia] केन्द्र-शासित प्रदेश केन्द्र शासित प्रदेश या संघ-राज्यक्षेत्र या संघक्षेत्र भारत के संघीय प्रशासनिक ढाँचे की एक उप-राष्ट्रीय प्रशासनिक इकाई है। भारत के राज्यों की अपनी चुनी हुई सरकारें होती हैं, लेकिन केन्द्र शासित प्रदेशों में सीधे-सीधे भारत सरकार का शासन होता है। भारत का राष्ट्रपति हर केन्द्र शासित प्...
null
null
null
null
Generate a simple Flask route to handle a GET request.
from flask import Flask app = Flask(__name__) @app.route("/myroute", methods=["GET"]) def myfunc(): # write code here if __name__ == '__main__': app.run()
[DE Wikipedia] Otto Schultz (Medailleur) Otto Schultz (* 16. Januar 1848; † 13. August 1911) war ein deutscher Medailleur und Münzeisenschneider. Leben Schultz’ Vater war Lokomotivführer. Otto Schultz lernte bei der Albert Wolff und Julius Moser. Er studierte drei Jahre an der Königlichen Akademie in Berlin und war da...
null
null
null
[CS Wikipedia] Marisa Mell Marisa Mell, vlastním jménem Marlies Theres Moitzi (24. února 1939 Štýrský Hradec – 16. května 1992 Vídeň) byla rakouská herečka. Absolvovala vídeňský Max Reinhardt Seminar, v roce 1954 debutovala ve filmu Das Licht der Liebe. Hrála ve zfilmování Švejka, které natočil v roce 1960 západoněmec...
null
null
null
[DE Wikipedia] Arto Bryggare Arto Kalervo Bryggare (* 26. Mai 1958 in Kouvola) ist ein ehemaliger finnischer Leichtathlet und Olympiateilnehmer. Allgemeines Arto Bryggare gehörte ein Jahrzehnt lang zu den besten 110-Meter-Hürdenläufern Europas. Er war finnischer Meister auf seiner Spezialstrecke von 1977 bis 1987 und ...
null
null
null
null
Describe how language models can be used in natural language processing.
Language models are used in natural language processing to enable machines to understand and generate natural language. Language models assign a probability to a sequence of natural language words to improve the accuracy of predictions in language processing tasks. They are used for automatic speech recognition, machin...
null
Generate a correct JavaScript program to convert a string into an array
s = "hello world";
//function to split a string into an array function stringToArray(s) { return s.split(' '); } //create a string s = "hello world"; //convert string to array array = stringToArray(s); //print the array console.log(array);
[CS Wikipedia] Autorské právo Autorské právo (anglicky ) je odvětví práva, které se zabývá právními vztahy uživatelů a tvůrců tzv. „autorských děl“ k příslušným dílům. Tvůrci mohou být například spisovatelé, hudebníci, filmaři, architekti, urbanisté a programátoři apod. Prostřednictvím autorského práva stát poskytuje ...
null
null
null
null
Generate a logistic regression classifier in Python that classifies data into two classes (0 or 1).
X: An array containing 8 feature values (floats). [1.0472, 2.1930, 1.6025, 0.8886, 2.5850, 1.4692, 1.2548, 0.8496] Y: An array containing labels for the data points (1 or 0). [0, 0, 1, 0, 0, 0, 0, 1]
# Import the necessary libraries import numpy as np from sklearn.linear_model import LogisticRegression # Load in the feature values and labels X = np.array([1.0472, 2.1930, 1.6025, 0.8886, 2.5850, 1.4692, 1.2548, 0.8496]).reshape(-1, 1) y = np.array([0, 0, 1, 0, 0, 0, 0, 1]) # Create the logistic regression model mo...
null
Using Python, create a function to convert HTML to plain text.
Input HTML: ``` <p>Hello world!</p> <div> <p>This is a test.</p> </div> ```
import lxml.html as lh def html_to_text(html): tree = lh.fromstring(html) return tree.text_content() html = "<p>Hello world!</p><div><p>This is a test.</p></div>" print(html_to_text(html))
null
Given a list of numbers, sort them in increasing order.
nums = [2, 3, 1, 4, 5]
def sort_numbers(nums): return sorted(nums)
[DE Wikipedia] Gemma Chan Gemma Chan (* 29. November 1982 in London) ist eine britische Schauspielerin und ein Model. Sie war in Jack Ryan: Shadow Recruit zu sehen, spielte eine Hauptrolle in der Serie Humans und eine Nebenrolle in Phantastische Tierwesen und wo sie zu finden sind aus dem Jahr 2016 sowie die Anführeri...
null
null
null
null
Create an HTML page that has an input field and a button. When the button is clicked, the text from the input field should be printed to the console.
<html> <head> </head> <body> <input type="text" id="myInput"> <button onclick="printInput()">Print Input</button> <script> function printInput(){ const inputVal = document.getElementById("myInput").value; console.log(inputVal); } </script> </body> </html>
[EN Wikipedia] Troyte River The Troyte River is a river of the West Coast region of New Zealand's South Island. It rises in the Hooker Range, 15 kilometres west of Aoraki / Mount Cook, flowing west then north to reach the Karangarua River. See also List of rivers of New Zealand References Rivers of the West Coast, New...
null
null
null
null
Generate a Python program to convert a given binary string to its equivalent decimal value.
1110
def binary_to_decimal(n): num = n dec_value = 0 base = 1 temp = num while temp > 0: last_digit = temp % 10 temp = temp // 10 dec_value += last_digit * base base = base * 2 return dec_value
[CS Wikipedia] 24. prosinec 24. prosinec je 358. den roku podle gregoriánského kalendáře (359. v přestupném roce). Do konce roku zbývá 7 dní. V tento den je Štědrý den. Události Česko 1796 – Ve starorožmitálském chrámu Povýšení svatého Kříže se konala premiéra Rybovy České mše vánoční 1926 – Zaveden simultánní rozhlas...
null
null
null
null
You are given a string and asked to find the frequency of each character in the string
str = "GPT Model"
from collections import Counter def char_frequency(str): return Counter(str) str = "GPT Model" print (char_frequency(str)) # Output: {'G': 1, 'P': 1, 'T': 1, ' ': 1, 'M': 1, 'o': 2, 'd': 1, 'e': 1, 'l': 1}
[EN Wikipedia] Rhabdochaeta spinosa Rhabdochaeta spinosa is a species of tephritid or fruit flies in the genus Rhabdochaeta of the family Tephritidae. Distribution Seychelles. References Tephritinae Insects described in 1914 Diptera of Asia
null
null
null
null
Modify the following code to convert it from JavaScript to Java.
function getAverage(a, b) { return (a + b) / 2; }
public float getAverage(float a, float b) { return (a + b) / 2; }
null
Modify the following python code to print the count of values greater than 5.
data = [1,2,3,4,5,6,7,8,9]
data = [1,2,3,4,5,6,7,8,9] count = 0 for value in data: if value > 5: count += 1 print(count)
null
From the given list, create a dictionary where keys will be the elements and the values will be their corresponding indices.
elements = ["one", "two", "three", "four"]
def list_to_dict(elements): return {el: i for i, el in enumerate(elements)}
null
Create a variable in Python to store the length of a list.
example_list = [1, 2, 3, 4]
list_length = len(example_list)
null
Create a python script to find the palindromic sub-string with the longest length from a given string.
Example String: "forgeeksskeegfor"
def longestPalSubstr(string): maxLength = 1 start = 0 length = len(string) low = 0 high = 0 for i in range(1, length): low = i - 1 high = i while low >= 0 and high < length and string[low] == string[high]: if high - low + 1 > maxLength: ...
null
Using Python, find the number of unique characters in the string "hello world".
len(set("hello world")) # 10 unique characters
null
Create a dictionary comprehension for the given data.
{"A":1, "B":2, "C":3, "D":4}
Dict = {key: value for key, value in {"A":1, "B":2, "C":3, "D":4}.items()}
null
Correct the syntax errors in this piece of Python code.
def greet(name): print("Hello "name)
def greet(name): print("Hello", name)
null
Design a Python script for encrypting text using AES encryption.
Example text: "hello world"
import base64 from Crypto.Cipher import AES def encrypt(key, text): cipher = AES.new(key, AES.MODE_EAX) nonce = cipher.nonce ciphertext, tag = cipher.encrypt_and_digest(text.encode('utf-8')) return (nonce, tag, ciphertext) key = b'Sixteen byte key' text = "hello world" nonce, tag, ciphertext = encrypt(key, text)...
null
Generate a PHP program to accept a string as an input and convert it to uppercase.
<?php $str = 'Hello World!'; echo strtoupper($str); // Output: HELLO WORLD! ?>
null
Given two unsorted lists, create a Python program to identify the common elements between them.
list1 = [5, 3, 2, 6, 8, 9] list2 = [4, 2, 1, 6, 7]
def common_elements(list1, list2): return [element for element in list1 if element in list2] common_elements(list1, list2) # Output: [2, 6]
[EN Wikipedia] SS Milwaukee Nine steamships have been named SS Milwaukee (or derivation). SS Milwaukee (1852), U.S. package freighter. SS Milwaukee (1868), U.S. steam barge. SS Milwaukee (1879), also known as Yonkers, U.S. package freighter. SS Milwaukee (1889), U.S. tugboat. SS Milwaukee (1902), U.S. package freighte...
null
null
null
[HI Wikipedia] भारत में संगीत-शिक्षण १८ वीं शताब्दी में घराने एक प्रकार से औपचारिक संगीत-शिक्षा के केन्द्र थे परन्तु ब्रिटिश शासनकाल का आविर्भाव होने पर घरानों की रूपरेखा कुछ शिथिल होने लगी क्योंकि पाश्चात्य संस्कृति के व्यवस्थापक कला की अपेक्षा वैज्ञानिक प्रगति को अधिक मान्यता देते थे और आध्यात्म की अपेक्षा इस संस्कृ...
null
null
null
null
Create a class named "Car" with attributes like "model" and "speed".
class Car { constructor(model, speed) { this.model = model; this.speed = speed; } getModel() { return this.model; } getSpeed() { return this.speed; } }
[EN Wikipedia] Gmina Grójec Gmina Grójec is an urban-rural gmina (administrative district) in Grójec County, Masovian Voivodeship, in east-central Poland. Its seat is the town of Grójec, which lies approximately south of Warsaw. The gmina covers an area of , and as of 2006 its total population is 23,140 (out of which ...
null
null
null
null
Create a regular expression to check if a given string contains any the letter 'X'.
RegExp("X", "i")
null
You have a list of temperature values. Write a python program to find the day which has the highest temperature.
[58, 59, 61, 63, 66, 68, 71, 72, 75]
def highest_temp(temp_list): highest_temp_day = 0 highest_temp_val = temp_list[0] for i in range(1, len(temp_list)): if temp_list[i] > highest_temp_val: highest_temp_day = i highest_temp_val = temp_list[i] return highest_temp_day
[CS Wikipedia] Ota VIII. z Wittelsbachu Ota VIII. z Wittelsbachu (1180 – 5. března 1209, Oberndorf) byl bavorský falckrabě a vrah římského krále Filipa Švábského. Život Ota byl jediným synem Oty III. Wittelsbašského a poprvé je doložen roku 1193. Byl straníkem Filipa Švábského a ten jej okolo roku 1203 zasnoubil se sv...
null
null
null
null
What is the advantage of using dictionary comprehension in Python?
The main advantage of using dictionary comprehension in Python is that it offers an efficient and concise way to create dictionaries. It can be used to create dictionaries from existing sequences or iterables, or to create new dictionaries from scratch. It also eliminates the need for writing multiple lines of code to ...
null
Generate a machine learning algorithm in Python for recognizing hand-written digits from the MNIST dataset.
Not applicable
import numpy as np from keras.models import Sequential from keras.layers import Dense, Conv2D, Flatten # Create a Sequential model model = Sequential() # Add Conv2D and Dense layers model.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(28,28,1))) model.add(Conv2D(32, kernel_size=3, activation='relu')) m...
null
Create a Python script to perform the following transformation on a given string?
"HELLO WORLD"
inp_str = "HELLO WORLD" result_str = '' for c in inp_str: if c.isupper(): result_str += c.lower() else: result_str += c.upper() print(result_str)
null
Identify the ‘time complexity’ of an algorithm written in Java that calculates average of all elements in a list.
The time complexity of the algorithm is O(n) since it needs to loop through all the elements in the list in order to calculate the average.
null
Given a list of integers, calculate the sum of only the first 3 numbers.
List: [1,4,5,7,2]
list = [1,4,5,7,2] sum = list[0] + list[1] + list[2] #Result: 10
[EN Wikipedia] The Temptation of Saint Anthony (Savoldo) The Temptation of Saint Anthony or The Torment of Saint Anthony is an oil-on-panel painting executed c. 1521–1525 by the Italian Renaissance artist Giovanni Girolamo Savoldo. It is now in the Timken Museum of Art in San Diego. It may relate to the same artist's ...
null
null
null
null
Write a script in python that outputs all even numbers between 0 and 10.
for number in range(0,11): if (number % 2 == 0): print(number)
null
Implement an algorithm to split a string of numbers (integers or floats) in to two parts with an even sum
inputString: '1,2,3,4,5,6'
public int[] splitEvenSum(string inputString) { List<int> nums = new List<int>(); // Split inputString at , and add elements to the list foreach (var num in inputString.Split(',')) { nums.Add(int.Parse(num)); } // Initialize variables int targetSum = 0; int sum1 = 0; int sum2 = 0; List<int> list1 = new List<int>(); Lis...
null
Find the angle between two given vectors
The angle between two vectors can be found using the following formula: theta = arccos(v1.v2 / (||v1||*||v2||)), where v1 and v2 represent the two given vectors and ||v1|| and ||v2|| are the magnitudes of the vectors.
null
Suggest a way to the generate a random number between 0 and 1 in JavaScript.
function getRandom() { return Math.random(); }
null
Generate a correct python script to identify the output of a given expression.
expression: (4 + 2) * 3
a = (4 + 2) * 3 print(a)
[HI Wikipedia] नाशिक नासिक (Nasik) या नाशिक (Nashik) भारत के महाराष्ट्र राज्य के नाशिक ज़िले में स्थित एक नगर है। यह ज़िले का मुख्यालय और महाराष्ट्र का चौथा सबसे बड़ा नगर है। नाशिक गोदावरी नदी के किनारे बसा हुआ है। यह महाराष्ट्र के उत्तर पश्चिम में, मुम्बई से १५० किमी और पुणे से २०५ किमी की दुरी में स्थित है। यह शहर प...
null
null
null
[EN Wikipedia] Larentiini Larentiini is a tribe of geometer moths under subfamily Larentiinae. The tribe was first described by Philogène Auguste Joseph Duponchel in 1845. Recognized genera Anticlea Stephens, 1831 Antilurga Herbulot, 1951 Earophila Gumppenberg, 1887 Ennada Blanchard, 1852 Entephria Hübner, 1825 Herbul...
null
null
null
[HI Wikipedia] वैशाली वैशाली बिहार प्रान्त के वैशाली जिला में स्थित एक गाँव है। ऐतिहासिक स्थल के रूप में प्रसिद्ध यह गाँव मुजफ्फरपुर से अलग होकर १२ अक्टुबर १९७२ को वैशाली के जिला बनने पर इसका मुख्यालय हाजीपुर बनाया गया। मगही,वज्जिका यहाँ की मुख्य भाषा है। ऐतिहासिक प्रमाणों के अनुसार वैशाली में ही विश्व का सबसे पहला गण...
null
null
null
null
Write a Python program to print the elements of a list from the last to the first.
_list = [1,2,3,4,5]
_list = [1,2,3,4,5] # Iterate through the list in reverse order for i in range(len(_list) - 1, -1, -1): print(_list[i]) # Output: # 5 # 4 # 3 # 2 # 1
null
Create a script to multiply each element in a list by 10.
input_list = [1,2,3,4]
def multiply_by_10(input_list): new_list = [] for i in input_list: new_list.append(i*10) return new_list
null
Edit the existing code to focus the cursor in the input field.
<html> <body> <input type="text" id="myInput" /> <script type="text/javascript"> document.getElementById('myInput').focus(); </script> </body> </html>
<html> <body> <input type="text" id="myInput" autofocus /> <script type="text/javascript"> document.getElementById('myInput').focus(); </script> </body> </html>
[EN Wikipedia] 1964–65 Norwegian 1. Divisjon season The 1964–65 Norwegian 1. Divisjon season was the 26th season of ice hockey in Norway. Six teams participated in the league, and Valerenga Ishockey won the championship. Regular season External links Norwegian Ice Hockey Federation Nor Eliteserien (ice hockey) seasons...
null
null
null
null
Optimize an existing Python function to reverse a string. This function should take a string as input and return the reversed string.
'Hello World!'
def reverse_string(input): return input[::-1]
null
Implement a function in Python that takes an array of strings and returns a list of all strings that have length greater than 6
["testing", "this","array"]
def getStringsWithLength(array): output = [] for x in array: if len(x) > 6: output.append(x) return output print(getStringsWithLength(["testing", "this","array"]))
null
Create an HTML page to display a table of students
Data of students: First name, LastName and Age
<html> <head> <title>My Student Table </title> </head> <body> <table> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> </thead> <tbody> {% for firstName, lastName, age in studentsList %} <tr> <td>{{ firstName }}</td> <td>{{ lastName }}</td> <td>{{ age }}</td> </tr> {% endfor %} </tbody> </table> <...
null
Generate a random password of length 8 using Python.
import random def generate_password(length): chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" password = "" for i in range(length): index = random.randint(0, len(chars)-1) password += chars[index] return password length = 8 password = generate_password(length) print("Here's your random password:...
null
Complete the following code to shuffle an array of elements.
#Declaring an array arr = [1, 2, 3, 4, 5] # Your code def shuffle(arr):
#Declaring an array arr = [1, 2, 3, 4, 5] # Your code def shuffle(arr): for i in range(len(arr)-1, 0, -1): j = random.randint(0, i+1) arr[i], arr[j] = arr[j], arr[i] return arr
null
Implement a bubble sort on the given array of integers.
[4, 8, 1, 3, 9]
def bubble_sort(arr): for _ in range(len(arr) -1): for i in range(len(arr)-1): if arr[i] > arr[i+1]: arr[i], arr[i+1] = arr[i+1], arr[i] return arr print(bubble_sort([4, 8, 1, 3, 9])) # [1, 3, 4, 8, 9]
null
Write a Python program to find the maximum and minimum of three numbers.
def findMinMax(num1, num2, num3): if num1 >= num2 and num1 >= num3: maximum = num1 minimum = num3 if num3 <= num2 else num2 elif num2 >= num1 and num2 >= num3: maximum = num2 minimum = num1 if num1 <= num3 else num3 else: maximum = num3 minimum = num1 if num1 ...
[CS Wikipedia] Rada Evropy Rada Evropy (RE) (anglicky Council of Europe, CoE, francouzsky Conseil de l'Europe) je mezinárodní organizace spojující 46 zemí Evropy. Tato instituce dále zahrnuje šest pozorovatelských zemí: Vatikán, Kanadu, USA, Mexiko, Japonsko a Izrael. Rada Evropy je nezávislá na Evropské unii a funguj...
null
null
null
[HI Wikipedia] मैदानी हॉकी मैदानी हॉकी अथवा फ़ील्ड हॉकी (Field hockey) अथावा सामान्यतः हॉकी, हॉकी परिवार का टीम का खेल है। खेल का उद्भव मध्यकाल में स्कॉटलैण्ड, नीदरलैण्ड और इंग्लैण्ड में माना जाता है। यह खेल घास के मैदान अथवा कृत्रिम घास के मैदान पर खेला जा सकता है। प्रत्येक टीम में गोलकीपर सहित ग्याहरह खिलाड़ी होते ह...
null
null
null
null
Write a function which takes in a list containing integers, strings and floats and returns the sum of all numbers in the list.
list = [2, 'John', 8.2, 3.4, 11]
def sum_numbers(lst): sum = 0 for item in lst: if type(item) == int or type(item) == float: sum += item return sum
[CS Wikipedia] Emil Šulc Emil Šulc (1. května 1891 – 3. ledna 1957, Praha, Československo) byl český architekt, jehož návrhy se realizovaly především v Praze. Dle jeho plánů se roku 1921 na domě na pražském Vyšehradě (Vratislavova 28/VI) upravily fasády v přízemí. O tři roky později realizoval zastřešení části dvora a...
null
null
null
null
Use Python and SQL to create a basic database for a fictional company. The company has a list of products, employees, and customers. The database should include models and relations for these three.
Not applicable
from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Product(Base): __tablename__ = 'product' id = Column(Integer, primary_key=True) name = Column(String) class Employee(Base): __tablename__ = 'employee' id = Column(In...
null
What is the Big O time complexity of selection sort?
Selection sort has a time complexity of O(N2) in the worst case.
null
Generate code to construct a deck of cards with Python.
Not applicable
class Card(): # suits is a set of all possible suits suits = {"spades", "hearts", "diamonds", "clubs"} # ranks is a set of all possible ranks ranks = {"Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"} # Create a new card def __init__(self, suit, rank): # Check if the suit is ...
null
Create a SQL table which has 3 columns id, name and price.
CREATE TABLE products ( id INTEGER AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, price DECIMAL(10,2) NOT NULL );
[CS Wikipedia] Polární soustava souřadnic Polární soustava souřadnic je taková soustava souřadnic v rovině, u které jedna souřadnice (označovaná ) udává vzdálenost bodu od počátku souřadnic, druhá souřadnice (označovaná ) udává úhel spojnice tohoto bodu a počátku od zvolené osy ležící v rovině (nejčastěji jí odpovídá ...
null
null
null
null
Update the below Python code to the dynamic programming approach, for finding a maximum subarray of elements, given in an array.
arr- [2, 3, -6, 5, -1,1]
def max_subarray(arr): n = len(arr) max_sum_so_far = arr[0] ending_here_max_sum = arr[0] for i in range(1, n): current_max_sum_with_last_element_i = max(arr[i], ending_here_max_sum + arr[i]) max_sum_so_far = max(max_sum_so_far, current_max_sum_with_last_element_i) ending_here_max_sum = current_max_sum_with_last_...
null
How do you calculate the sum of a list of numbers in Python?
The sum of a list of numbers in Python can be calculated using the built-in sum() function. This function takes an iterable object (such as a list or tuple) containing numbers as its argument and returns the sum of all the elements in the object. For example, sum([1,2,3]) will return 6.
null
Generate a class in Python for representing customers in a banking application. It should include attributes for customer name, account number, and account balance.
Not applicable
class Customer: def __init__(self, name, account_number, balance): self.name = name self.account_number = account_number self.balance = balance def get_balance(self): return self.balance def deposit(self, amount): self.balance += amount def withdraw...
null
Generate a classification model to classify spam messages using logistic regression in python.
""" Generate a classification model to classify spam messages using logistic regression in python """ # Import libraries import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression # Read the dataset dataset = pd.read_csv('spam.csv') # Split the data...
null
Construct an MySQL query to select records from a table named 'employees' where salary is between 50000 and 100000.
SELECT * FROM employees WHERE salary BETWEEN 50000 AND 100000;
null
Write a Python function to find the maximum from 3 numbers.
10, 7, 4
def find_max(a, b, c): max = a if b > max: max = b if c > max: max = c return max max_number = find_max(10, 7, 4) print('Maximum number is', max_number)
null
Write a query to count the number of movies released in 2020 from the database.
SELECT COUNT(*) AS total_movies FROM movies WHERE year = 2020;