text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Design python code to optimize the following function: ⅇ͏^(−𝐱^2)
import math from scipy.optimize import minimize def objective(x): return math.exp(-x**2) x0 = 5 print('Initial objective: ' + str(objective(x0))) solution = minimize(objective, x0) print('Optimized objective: ' + str(objective(solution.x)))
[CS Wikipedia] Widescreen eXtended Graphics Array++ WXGA++, neboli Widescreen eXtended Graphics Array je standard displejů s grafickým rozlišením 1600 × 900 pixelů. Z CRT monitorů tímto rozlišením disponovalo jen několik málo nejdražších profesionální modelů. Nyní je využíván na LCD obrazovkách ve větších noteboocích ...
null
null
null
[DE Wikipedia] Kieferorthopädie Die Kieferorthopädie ist das Teilgebiet der Zahnmedizin, das sich mit der Erkennung und Behandlung von Fehlstellungen der Kiefer und der Zähne (Zahnfehlstellung) befasst. Der Inhalt des Fachbereichs wird besser durch die Bezeichnung Dento-Maxilläre Orthopädie (Kieferregulierung) wiederg...
null
null
null
null
Write a Python program to optimize the given linear objective function using the Simplex algorithm.
import numpy as np from scipy.optimize import minimize def optimize_function(objective): bounds = ((0, None), (0, None), (0, None)) res = minimize(objective, [1,1,1], method="Nelder-Mead", bounds=bounds) return res
null
Create a text-based user interface for a simple game using Python. The game should allow the user to start a game, make moves, and view the game status.
Not applicable
import os import sys class game: def __init__(self): self.board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] self.turn = 'X' self.score = [0, 0] def move(self, x, y): self.board[x][y] = self.turn if self.turn == 'X': self.t...
[DE Wikipedia] Hermann von Sachsenheim (Landhofmeister) Hermann von Sachsenheim (* um 1428/1430; † 15. November 1508) war ein deutscher Politiker aus dem Rittergeschlecht der Sachsenheimer und Sohn des gleichnamigen Minnesängers. Als Landhofmeister und Diplomat stand er im Dienst der württembergischen Herrscher. Die S...
null
null
null
null
Write an HTML page that displays one heading and two paragraphs.
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>Heading</h1> <p>Paragraph 1</p> <p>Paragraph 2</p> </body> </html>
[EN Wikipedia] Çukur Çukur () is a Turkish action, drama and thriller television series Produced by Ay Yapım, directed by Sinan Öztürk and written by Gökhan Horzum and Damla Serim. It premiered on 23 October 2017 and concluded on 7 June 2021 with a total of 131 episodes (four seasons). Plot The Koçovalı family is in c...
null
null
null
null
Generate a Random Forest classifier in Python to categorize emails into two classes - spam and not-spam.
Not applicable
# Random Forest classifier setup from sklearn.ensemble import RandomForestClassifier # Sample data X = [['email_1'], ['email_2'], ...] y = [0, 1, ...] # 0 is not-spam, 1 is spam # Train the model model = RandomForestClassifier(n_estimators=100) model.fit(X, y) # Make predictions predictions = model.predict(X_test)
null
What's the output of this program in Python given the following input?
input_string = "Hello, World!" list_of_chars = list(input_string) for current_char in list_of_chars: print(current_char)
H e l l o , W o r l d !
null
Implement a validator in Python that checks the format of user input for a given field and throws an error if it is not valid.
Not applicable
def validate(data, field, regex): # makes sure data is not empty if not data: raise ValueError('Data is required.') # makes sure data contains field if not field in data: raise ValueError('Field ' + field + ' is required.') # check format of data import re if not re.match(reg...
null
Write an SQL query to count the number of people with a given last name in a table of people.
lastName = 'Smith'
SELECT COUNT(*) FROM people WHERE lastName = 'Smith';
null
Write a Python program that can generate all permutations of a given list.
list_a = [1, 2, 3]
def generate_permutations(list_a): import itertools return list(itertools.permutations(list_a)) generate_permutations(list_a)
[HI Wikipedia] सुदास (ऋग्वेद) सुदास भारत में एक प्राचीन राजा थे जिनका उल्लेख ऋग्वेद में मिलता है। वे दशराज्ञ युद्ध के विजेता थे जिसका वर्णन ऋग्वेद ७:१८, ७:३३ और ७:८३:४-८ में है। उनका जीवनकाल अलग-अलग स्रोतों में १७०० ईसापूर्व से लेकर ११०० ईसापूर्व के बीच के किसी समय में अनुमानित किया जाता है। नामार्थ 'सुदास' के नाम के ...
null
null
null
[HI Wikipedia] शहर शहर बड़ी और स्थायी मानव बस्ती होती है। शहर में आम तौर पर आवास, परिवहन, स्वच्छता, भूमि उपयोग और संचार के लिए निर्मित किया गया एक व्यापक सिस्टम होता हैं। ऐतिहासिक रूप से शहरवासियों का समग्र रूप से मानवता में छोटा सा अनुपात रहा है। लेकिन आज दो शताब्दियों से अभूतपूर्व और तेजी से शहरीकरण के कारण, कहा जात...
null
null
null
null
Produce a chart of linear equations in Python.
Equations: y = 5x + 2 y = -3x + 6
import matplotlib.pyplot as plt x = [i for i in range(-10, 10)] y1 = [5*i + 2 for i in x] y2 = [-3*i + 6 for i in x] plt.plot(x, y1, label='y = 5x + 2') plt.plot(x, y2, label='y = -3x + 6') plt.legend() plt.show()
[HI Wikipedia] ओरेनबूर्ग ओब्लास्त ओरेनबूर्ग, रूस का एक ओब्लास्त (области या प्रांत) है। सोवियत संघ के ज़माने में, १९३८ से १९५७ तक, इसका नाम बदलकर च्कालोव ओब्लास्त रखा गया था। विवरण ओरेनबूर्ग ओब्लास्त की दक्षिणी सीमाएँ काज़ाख़स्तान से लगती हैं। यूराल नदी इस ओब्लास्त की प्रमुख जलधारा है। लोग २०१० की जनगणना के हिसाब से ओ...
null
null
null
null
Write a python program to generate an array filled with the first n prime numbers.
n = 10
# Python3 code to generate an # array containing first n primes import math def generatePrimeArray(n): prime = [True for i in range(n + 1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * 2, n + 1, p): prime[i] = False p += 1 # prime[0]= False # prime[1]= False # Store pr...
null
Generate a Python function that takes two three-dimensional vectors as parameters and computes the magnitude of the cross product.
Not applicable
def cross_product_magnitude(vector_a, vector_b): """ Calculate the magnitude of the cross product of two 3D vectors """ vector_a_x, vector_a_y, vector_a_z = vector_a vector_b_x, vector_b_y, vector_b_z = vector_b # Calculate the cross product cross_x = vector_a_y * vector_b_z - vector_a_z * vector_b_y cross_y = ...
null
You need to write an API request in Python to return JSON data from an API endpoint.
import requests API_ENDPOINT = 'api.example.com/data' response = requests.get(API_ENDPOINT) if response.status_code == 200: data = response.json()
null
Write a regular expression to extract the city names from the following string.
address: #38 number street, new york city, san jose, CA
import re address_string = "#38 number street, new york city, san jose, CA" pattern = r'(?:,|^)([\s\w]*)(?:,|$)' result = re.findall(pattern, address_string) print(result) // ['new york city', 'san jose']
null
Create a class in Python to store employee details like name, age and salary.
class Employee: def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary def get_details(self): print(f"Name: {self.name}") print(f"Age: {self.age}") print(f"Salary: {self.salary}")
null
Create a class called 'Address' with four string fields: address line 1, address line 2, city, and zipCode.
class Address { String addressL1; String addressL2; String city; String zipCode; public Address(String addressL1, String addressL2, String city, String zipCode) { this.addressL1 = addressL1; this.addressL2 = addressL2; this.city = city; this.zipCode = zipCode; } }
null
Design a Python algorithm to merge two sorted lists.
def merge_two_lists(list1, list2): merged_list = [] while list1 and list2: if list1[0] < list2[0]: merged_list.append(list1.pop(0)) else: merged_list.append(list2.pop(0)) merged_list.extend(list1 or list2) return merged_list
null
Write a Python program that predicts the future price of a stock in two weeks.
Current stock prices: IBM $145, AAPL $285, MSFT $181
# Import necessary libraries import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression # Load the data data = [[145, 285, 181], [149, 290, 184], [153, 295, 187]] data = pd.DataFrame(data, columns=['IBM', 'AAPL', 'MSFT']) # Define and fit the linear regression model model = LinearRegress...
null
Write a Python program that takes a URL and checks for broken links.
import requests def check_for_broken_links(url): # Request webpage response = requests.get(url) # Parse webpage for all links links = response.html.find_all('a') # Check response code of each link for link in links: link_url = link['href'] response = requests.get(link_url)...
null
Write a Python 3 script that reads input from stdin line by line and prints the number of occurrences of each word.
The quick brown fox jumps over the lazy dog
import sys dictionary={} for line in sys.stdin: words_in_line = line.split() for word in words_in_line: word=word.lower() if word in dictionary: dictionary[word]+=1 else: dictionary[word]=1 for word in dictionary: print(word +":"+ str(dictionary[word]))
null
Write a procedure in PL/SQL to find the sum of numbers from 1 to 10.
create or replace procedure addNums(sum OUT NUMBER) begin sum := 0; for i in 1 .. 10 loop sum := sum + i; end loop; end addNums;
null
Create a program in Java that finds the maximum element in an array.
public static int getMaxElement(int[] arr) { int max = Integer.MIN_VALUE; for (int el : arr) { if (el > max) max = el; } return max; }
null
Develop a Python program to calculate the mean of a given array.
60, 54, 77, 78, 37, 35
def mean(arr): total = 0 for num in arr: total += num return total/len(arr) arr = [60, 54, 77, 78, 37, 35] print("Mean: ", mean(arr))
null
Create a PHP function to calculate the total amount of tax to be paid given the income and tax rate.
income = 50000, tax rate = 0.2
function calcTax(income, rate) { return income * rate; } var totalTax = calcTax(50000, 0.2); console.log(totalTax); //10000
null
Generate a Python program to construct a hash table that stores strings as keys and integers as values.
def create_hash_table(): hash_table = dict(zip(list_of_strings, list_of_integers)) return hash_table
null
Create a program to create a new string where the first and last occurrence of each character is removed.
'Hello World'
def strip_string(s): new_str = "" counts = {} # Create a dictionary to record the number of occurrences of each character for letter in s: if letter not in counts: counts[letter] = 1 else: counts[letter] += 1 for char in s: if counts[char] > 1: new_str += char counts[char] -= 1 return new_str
null
Transform the given XML data into a Python dictionary.
<root> <person> <name>John</name> <age>27</age> <hobbies> <hobby>Movies</hobby> <hobby>Photography</hobby> </hobbies> </person> </root>
import xml.etree.ElementTree as et root = et.fromstring('<root><person><name>John</name><age>27</age><hobbies><hobby>Movies</hobby><hobby>Photography</hobby></hobbies></person></root>') data_dict = {} for elem in list(root): key = elem.tag data_dict[key] = {} for subelem in list(elem): data_dict[k...
null
Generate a class in Python to represent a Person with the following attributes: name, age, gender.
class Person: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def get_name(self): return self.name def get_age(self): return self.age def get_gender(self): return self.gender
null
Create a Java program to implement the classic Tic Tac Toe game.
import java.util.Scanner; public class TicTacToe { public static char[][] board = new char[3][3]; public static boolean playerX; public static Scanner scan; public static void main(String[] args) { scan = new Scanner(System.in); playerX = true; initializeBoard(); while(true) { printBoard(); nextMove(playerX); if(checkW...
[CS Wikipedia] Kytarový efekt Kytarový efekt je elektronické zařízení, které upravuje signál elektrické kytary vedený do zesilovače. Původní signál má tvar sinusoidy, ovšem kytarové efekty jej různě deformují, slangově „mrší“, proto jsou nazývány „mršítka“ nebo podle tvaru „krabičky“ či „pastičky“. V zahraničí se pro ...
null
null
null
null
Generate a list of 100,000 random numbers from 0 to 1 using NumPy in Python.
Not applicable
import numpy as np random_numbers = np.random.uniform(0, 1, 100000)
[CS Wikipedia] Vasilij Erošenko Vasilij Erošenko (12. ledna 1890 – 23. prosince 1952) byl ruský spisovatel esperanta, nevidomý, přes svoji slepotu procestoval velkou část světa, hlavně Čínu a Japonsko. Psal japonsky a přednášel ruskou literaturu na pekingské univerzitě. Je autorem původních děl: Ĝemo de unu soleca ani...
null
null
null
null
Create a web crawling program using Python
import requests from bs4 import BeautifulSoup # Function to crawl a given website def web_crawl(url): # Get the content from the given URL page = requests.get(url) # Create a bs4 object with the content soup = BeautifulSoup(page.content, 'html.parser') # Find all links on the pag...
null
Create a Python dictionary which contains the student name and their grade for the course.
{ "John": 85, "Alice": 91, "Bob": 74 }
student_grades = { "John": 85, "Alice": 91, "Bob": 74 }
[EN Wikipedia] WEMY WEMY is a Christian radio station broadcasting on 91.5 FM, serving the Green Bay, Wisconsin area. The station's format consists of Christian adult contemporary music with some Christian talk and teaching. WEMY is also heard in the Manitowoc–Two Rivers area through a translator on 95.5. It is part o...
null
null
null
null
Create a HTML page to show a result of the sum of two numbers.
<!DOCTYPE html> <html> <head> <title>Sum of Two Numbers</title> <script> // get numbers from user var a = prompt("Enter the first number"); var b = prompt("Enter the second number"); // calculate the sum var sum = +a + +b; // print the result document.write("Result : " +sum); </script> </head> <body> </body> </html>
[CS Wikipedia] Nobujuki Hijama Nobujuki Hijama (檜山 修之, Hijama Nobujuki, Hiyama Nobuyuki) se narodil 25. srpna, 1967. Nobujuki je populární japonský seijú, který se narodil v Hirošimě. V současnosti je člen Arts Vision. Vybrané role Anime RockMan.EXE (Rei Saiko) (西古 レイ) Bleach (Ikkaku Madarame) Kapitán Cubasa J (Kodžir...
null
null
null
null
Using a for loop, count the number of words in the below string.
string = "This is a test string"
count = 0 for word in string.split(): count += 1 print("Number of words:", count)
null
Generate a python program which prints a formatted list containing the elements from two input lists.
list_1 = [1, 2, 3] list_2 = [4, 5, 6]
def print_list(list_1, list_2): formatted_list = [list_1 + list_2 for i in range(len(list_1))] for x in formatted_list: for y in x: print(y) list_1 = [1, 2, 3] list_2 = [4, 5, 6] print_list(list_1, list_2) # Output: # 1 # 2 # 3 # 4 # 5 # 6
[DE Wikipedia] Wolxheim Wolxheim (elsässisch: Wolixe) ist eine französische Gemeinde mit Einwohnern (Stand ) im Département Bas-Rhin in der Region Grand Est (bis 2015 Elsass). Sie ist Mitglied der Communauté de communes de la Région de Molsheim-Mutzig. Wappen Blasonierung: Eine goldene Wolfsangel auf blauem Grund. Geo...
null
null
null
null
Create an HTML form with one input field which requests the user's name.
<form action="" method="get"> <label for="name">Name:</label> <input type="text" id="name" name="name" required> <input type="submit" value="Submit"> </form>
null
Generate a Python class to compare two strings.
class StrComparer: def __init__(self, str1, str2): self.str1 = str1 self.str2 = str2 def is_same(self): if self.str1 == self.str2: return True else: return False
null
Write a Python program to convert a binary number to decimal.
def bin_to_dec(binary): decimal, i, n = 0, 0, 0 while(binary != 0): dec = binary % 10 decimal = decimal + dec * pow(2, i) binary = binary//10 i += 1 return decimal
null
Develop a python class that checks if a given number is a prime number or not.
class CheckPrime(object): def __init__(self, number): self.number = number def is_prime(self): if self.number < 2: return False for i in range(2, self.number): if self.number % i == 0: return False return True if __name__ == '_...
null
Construct a query to find all movies released since a given year.
year: 2000
SELECT * FROM movies WHERE year > 2000;
null
Write a C# program to remove all adjacent duplicates from a string.
string str = "azxxzy";
string removeAdjacentDuplicates(string str) { int l = str.Length; char[] array = str.ToCharArray(); int index = 0; for (int i = 0; i < l; i++) { if (i == 0 || array[i - 1] != array[i]) array[index++] = array[i]; else while (i + 1 < l && array[i + 1] == array[i]) i++; } return new string(array, 0, index); }
null
Construct a python program that prints a multiplication table given two numbers (x and y).
int x = 5; int y = 10;
int x = 5; int y = 10; for i in range(1, y+1): for j in range(1, x+1): print('{} x {} = {}'.format(i, j, i*j))
null
Build a decison tree in Python to classify emails as spam or not spam.
import pandas as pd from sklearn.tree import DecisionTreeClassifier # Create dataframe df = pd.DataFrame({'content': ['This is a great deal!', 'Buy now!'], 'spam': [0, 1]}) # Create features and labels X = df['content'] y = df['spam'] # Create decision tree dtree_model = DecisionTreeClassifier(max_depth = 2).fit(X...
[HI Wikipedia] आईएफबीडीओ रक्त दाता संगठन अंतर्राष्ट्रीय महासंघ (अंग्रेजी में संक्षिप्त आईएफबीडीओ फ्रेंच और स्पेनिश में फियोडस) एक अंतरराष्ट्रीय संगठन जिसका मुख्य उद्देश्य स्वैच्छिक गैर रक्तदाताओं से रक्त कार्यवाही में सदस्य राज्यों की अच्छी तरह से रक्त दान और निरीक्षण प्रक्रियाओं के लिए सुरक्षा मानकों के रूप में आत्मन...
null
null
null
null
Write a PHP function for calculating the average of an array of numbers.
function calculateAverage($numbers) { $sum = array_sum($numbers); $n = count($numbers); $average = $sum/$n; return $average; }
[DE Wikipedia] Santa Mariana Santa Mariana ist ein brasilianisches Munizip im Norden des Bundesstaats Paraná. Es hatte 2021 geschätzt 11.523 Einwohner, die sich Santa-Marianenser nennen. Seine Fläche beträgt 427 km². Es liegt 462 Meter über dem Meeresspiegel. Etymologie Der Name stellt eine Ehrung von Mariana Junqueir...
null
null
null
null
Convert the following code to Python and make it object-oriented.
function celsius_to_fahrenheit(celsius) { let fahrenheit = (celsius * 9/5) + 32 return fahrenheit }
class TemperatureConverter: def celsius_to_fahrenheit(self, celsius): fahrenheit = (celsius * 9/5) + 32 return fahrenheit
null
Write a Java method to transform a String input into a String array with each element the length of 4.
String input = "HelloWorld";
public static String[] stringToArray(String input) { String[] stringArray = new String[input.length()/4]; int count = 0; for (int i = 0; i < input.length(); i += 4) { stringArray[count] = input.substring(i, i+4); count++; } return stringArray; }
[DE Wikipedia] Thomas Oppermann (Jurist) Thomas Oppermann (* 15. Februar 1931 in Heidelberg; † 26. Januar 2019) war ein deutscher Staatsrechtler. Von 1967 bis 1999 war er ordentlicher Professor für Öffentliches Recht und Auswärtige Politik an der Eberhard Karls Universität Tübingen. Leben und Wirken Thomas Oppermann s...
null
null
null
null
Using Java, create a program to compute the area of a circle given the radius.
""" Using Java, create a program to compute the area of a circle given the radius. """ public class AreaCircle { public static void main(String[] args) { double radius = 7.5; double area; area = Math.PI * Math.pow(radius, 2); System.out.println("Area of the circle is: " + area); } }
null
Create a python script to take in a number as input and output its binary equivalent.
# Input number n = int(input("Enter a number: ")) # Using format() print("The binary equivalent of {} is:".format(n), format(n, 'b'))
[CS Wikipedia] Sven-Ove Svensson Sven-Ove Svensson (1923 – leden 1987) byl švédský fotbalista a později trenér, který hrával na pozici záložníka. V roce 1954 získal ve Švédsku ocenění Guldbollen pro nejlepšího fotbalistu roku. Díky svému jménu měl přezdívku SOS. Klubová kariéra Téměř celou svou kariéru strávil v klubu...
null
null
null
null
Write a Python code snippet for a function to calculate the number of words in a given string.
myString = "The sky is blue"
def countWords (myString): return len(myString.split()) num = countWords(myString) print("Number of words =", num)
null
Implement a quicksort algorithm in Python to sort a list of 6 integers [52,85,23,6,37,77].
[52,85,23,6,37,77]
def quicksort(nums): if len(nums) <= 1: return nums else: pivot = nums[0] less = [i for i in nums[1:] if i <= pivot] greater = [i for i in nums[1:] if i > pivot] return quicksort(less) + [pivot] + quicksort(greater) print(quicksort([52,85,23,6,37,77]))
null
Write a Python function to sort a dictionary (key: value) by its values in descending order.
my_dict = {1: 4, 2: 3, 3: 2, 4: 1}
def desc_sort_dict(my_dict): return {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1], reverse=True)}
null
Write a Python program to generate a random array of integers of length N with values between 1 and M (inclusive).
- N = 10 - M = 100
import random N = 10 M = 100 random_array = [random.randint(1, M) for _ in range(N)] print(random_array) # Output: [3, 82, 83, 32, 45, 44, 6, 67, 25, 29]
[DE Wikipedia] Tadeusz Gede Tadeusz Gede (* 28. Dezember 1911 in Tiflis, Georgien; † 4. März 1982 in Warschau) war ein Politiker der Polnischen Vereinigten Arbeiterpartei PZPR (Polska Zjednoczona Partia Robotnicza) in der Volksrepublik Polen, der unter anderem zwischen 1949 und 1952 Außenhandelsminister sowie von 1952...
null
null
null
[HI Wikipedia] अग्नि-२ अग्नि द्वितीय (अग्नि-२) भारत की मध्यवर्ती दुरी बैलिस्टिक प्रक्षेपास्त्र है। इसे रक्षा अनुसंधान एवं विकास संगठन ने विकसित किया है। यह अत्याधुनिक तकनीक से बनी 21 मीटर लंबी और 1.3 मीटर चौड़ी अग्नि-२ मिसाइल परमाणु हथियारों से लैस होकर 1 टन पेलोड ले जाने में सक्षम है। 3 हजार किलोमीटर तक के दायरे में ...
null
null
null
null
Build a GUI application in Python to take user input and display a message.
import tkinter as tk root = tk.Tk() root.title("GUI Application") tk.Label(root, text="Enter your name:").grid(row=0, column=0, sticky="W") name_entry = tk.Entry(root) name_entry.grid(row=0, column=1) def on_button_click(): name = name_entry.get() tk.Label(root, text="Hello "+name).grid(row=1, column=1) tk....
[DE Wikipedia] Liberalerna Liberalerna (kurz L; deutsch Die Liberalen; bis 2015 Folkpartiet liberalerna, „Volkspartei Die Liberalen“) sind eine im schwedischen Reichstag vertretene Partei. Sie erreichte in der jüngsten Reichstagswahl 2018 5,5 Prozent der Stimmen und 20 von 349 Mandaten. Von 2006 bis 2014 beteiligte si...
null
null
null
null
Generate a python code to sum the elements in the given array.
arr = [1, 2, 3, 4, 5]
def sum_array(arr): total = 0 for num in arr: total += num return total sum_array(arr)
[HI Wikipedia] मानव लिंग का आकार मानव लिंग आकार में, जिसमें लम्बाई और परिधि शामिल हैं, अपनी तनी हुई और नरम अवस्था में विभिन्न माप का हो सकता है। सामान्य रूप से मानव लिंग की प्राकृतिक परिवर्तनशीलता के अलावा, कई ऐसे कारक हैं जो किसी भी पुरुष में मामूली भिन्नता पैदा करते हैं, जैसे कि उत्तेजना का स्तर, दिन का समय, कमरे का...
null
null
null
null
Design a loop in Python to iterate over the elements of a list and print the elements in reverse order.
[10, 15, 20]
my_list = [10, 15, 20] for i in my_list[::-1]: print(i)
[DE Wikipedia] Hölk-Hochhäuser Als Hölk-Hochhäuser werden zwei Hochhäuser an den Straßen Im Hölk und Poggenbreeden in Bad Oldesloe nordöstlich von Hamburg bezeichnet. Die beiden 13-stöckigen Wohntürme wurden 1972/73 durch die Wohnungsbaugenossenschaft Neue Lübecker errichtet, umgeben von Einfamilienhäusern. In ca. 230...
null
null
null
null
Create a function that sorts a list of dictionaries using the values.
animals = [{"name": "Dog", "age": 5}, {"name": "Cat", "age": 3}, {"name": "Fish", "age": 1}, {"name": "Deer", "age": 8}]
def sort_dict_list(animals): sorted_animals = sorted(animals, key=lambda k: k['age']) return sorted_animals result = sort_dict_list(animals) print(result) # Output: [{'name': 'Fish', 'age': 1}, {'name': 'Cat', 'age': 3}, {'name': 'Dog', 'age': 5}, {'name': 'Deer', 'age': 8}]
null
What would you change in the following function to sort a list of numbers in increasing order?
let arr = [ 4, 2, 5, 1, 3 ] function bubbleSort(arr) { for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp } } } }
let arr = [ 4, 2, 5, 1, 3 ] function bubbleSort(arr) { for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr.length - i - 1; j++) { if (arr[j] < arr[j + 1]) { let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp } } } }
[HI Wikipedia] अण्डमान और निकोबार की जनजातियाँ अण्डमान और निकोबार की जनजातियाँ भारत के अण्डमान और निकोबार द्वीपसमूह की जनजातियों को कहते हैं। यहाँ की प्रमुख जनजातियाँ और उनकी संख्या इस प्रकार है: निकोबारी - ३०,००० ओजे - १०० जारवा - २७० महान अण्डमानी - ४५ शेम्पेन - २०० अण्डमान और निकोबार द्वीपसमूह अंदमान निकोबार द्वीप ...
null
null
null
null
Write a code that returns a 2-dimensional array of size n by m containing all 0s
n = 3 and m = 5
def create2DArray(n, m): array = [[0 for x in range(m)] for y in range(n)] return array print(create2DArray(3, 5)) # prints [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
null
Write a SQL query to get the top 5 scores for a given game.
SELECT * FROM Scores ORDER BY score DESC LIMIT 5;
null
Create a Python class to implement a multiplication table
class MultiplicationTable: def __init__(self, limit): self.limit = limit def create_table(self): for i in range(1, self.limit+1): for j in range(1, self.limit+1): print(i*j, sep= '\t', end='') print()
null
Create an array of strings containing the names of the seven days of the week.
let daysOfWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
null
Create a program in JavaScript that takes in a positive integer and returns the sum of its digits.
824
function sumDigits(num) { let str = num.toString(); let result = 0; for (let char of str) { result += Number(char); } return result; }
null
Write code to establish a connection between a Python backend and a MySQL database.
Host = 'localhost' Username = 'root' Password = '123456' Database = 'sample_database'
import mysql.connector #Create MySQL Connection connection = mysql.connector.connect(host = Host, database = Database, user = Username, password = Password) #Check whether connection is established or not if connection.is_connected(): print("Connection established successfully")
null
Create an algorithm in Python to generate random numbers between 1 and 10 without repetition.
Number of random numbers needed is 5
import random def generate_random_numbers(n): result = random.sample(range(1, 11), n) return result random_numbers = generate_random_numbers(5) print(random_numbers) # Example output: [4, 9, 2, 6, 8]
null
Edit the code below so that the condition outcome is true. if 3 > 5: outcome = True
if 5 > 3: outcome = True
[EN Wikipedia] Grounding in communication Grounding in communication is a concept proposed by Herbert H. Clark and Susan E. Brennan. It comprises the collection of "mutual knowledge, mutual beliefs, and mutual assumptions" that is essential for communication between two people. Successful grounding in communication re...
null
null
null
[EN Wikipedia] GuaraníSat-1 GuaraníSat-1 was the first Paraguayan satellite. The nanosatellite's development was part of a collaboration between the Paraguayan Space Agency and the fourth Joint Global Multination Birds Satellite (Birds-4) multi-national project initiated by the Kyushu Institute of Technology of Japan....
null
null
null
null
Create a Python program that takes two lists of integers and prints the common elements between the two lists.
list1 = [2, 4, 6, 8] list2 = [4, 8, 10]
list1 = [2, 4, 6, 8] list2 = [4, 8, 10] common_elements = list(set(list1).intersection(list2)) print(common_elements) # Output: [4, 8]
null
Write a Python program to find the minimum cost of a path from top left cell to bottom right cell of a matrix.
matrix = [[2, 0, 3, 5], [4, 5, 1, 2], [3, 1, 2, 7]]
def min_path_sum(matrix): # initialize the solution matrix res = [[0 for _ in range(len(matrix[0]))] for _ in range(len(matrix))] # copying the first row elements res[0] = matrix[0] # iterate over the remaining rows for i in range(1, len(matrix)): # copy the first element res[i][0] = res[i-1][0] + matrix[i][0] for j in...
[HI Wikipedia] दामेली भाषा दामेली या दामेड़ी (Dameli, ) कुनर (कुनड़) शाखा की एक दार्दी भाषा है जो पाकिस्तान के चित्राल ज़िले की दोमेल वादी में बोली जाती है। इसे लगभग ५,००० लोग मातृभाषा के रूप में बोलते हैं। इनमें से पुरुष अक्सर पश्तो भी बोलना जानते हैं और बहुतों को खोवार और उर्दू भाषाएँ आती हैं। इसके बावजूद यह भाषा जी...
null
null
null
null
Generate a list of output values by multiplying the input values from two array in Python.
[1, 2, 3] and [4, 5, 6]
array1 = [1, 2, 3] array2 = [4, 5, 6] output = [val1 * val2 for val1, val2 in zip(array1, array2)] print(output) # Output [4, 10, 18]
[CS Wikipedia] Armstrong Siddeley Sapphire Armstrong Siddeley Sapphire byl britský proudový motor vyráběný v 50. letech firmou Armstrong Siddeley. Jednalo se o konečný vývoj prací, které začaly na motoru Metrovick F.2 v roce 1940 a vyvinuly se do pokročilého motoru s axiálním kompresorem a prstencovou spalovací komoro...
null
null
null
null
Write a function to retrieve the last element of a given array of strings.
arr = ["word", "sentence", "paragraph"];
def get_last_element(arr): return arr[-1] # Testing arr = ["word", "sentence", "paragraph"] last_element = get_last_element(arr) print("The last element is: ", last_element)
null
Write a class in Python to store the objects of student and their grades.
# Class to store student and grades class StudentGrades: def __init__(self, student_name): self.student_name = student_name self.grades = {} def add_grade(self, course_name, grade): self.grades[course_name] = grade def get_total_grade(self): total_grade = 0 for grade in self.grades.values(): total_grade += grade return...
[DE Wikipedia] Mole-Nationalpark Der Mole-Nationalpark (englisch Mole National Park) ist ein Nationalpark in Ghana, der 1971 als erstes Tierreservat des Landes gegründet wurde. Mit 4840 km² ist er vor dem Digya-Nationalpark der größte Nationalpark Ghanas. Der Mole-Nationalpark liegt im Nordwesten des Landes in der Sav...
null
null
null
null
What is a use case for inheritance in object-oriented programming?
In object-oriented programming, inheritance is used to create and maintain a hierarchical relationship between classes. By inheriting properties and methods from a parent class, a child class can reuse and extend the functionalities of the parent class. This allows developers to write less code and keep their codebase ...
null
Construct a for loop in Python for outputting the numbers in the range of 5-15.
for i in range(5, 16): print (i)
null
You need to design a database for a school where multiple students can have a tutor of a subject. What is the best way to design the database?
The best way to design the database is to create three tables: students, tutors and subjects. The students table would contain columns for each student's name, ID and contact details. The tutors table would contain the tutor's name, ID and contact details. The subjects table would contain the subject name, description ...