text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Imagine you have an array with the following elements: [3, 7, 2, 8, 1, 4]. Sort the array so that the elements are in ascending order.
[1, 2, 3, 4, 7, 8]
null
Create a Python program that compares two given lists to check if they have any common element.
list1 = [1,2,3] list2 = [4,5,6]
def compare_lists(list1, list2): '''This function checks if two lists have any common element''' found_common = False for x in list1: if x in list2: found_common = True break return found_common
null
Create a python program that categorizes a given list of numbers into odd and even numbers.
list N = [1, 2, 3, 4, 5, 6]
even = [] odd = [] for num in N: if num % 2 == 0: even.append(num) else: odd.append(num)
null
Describe the result of running this code.
obj = { 'a': 1, 'b': 2, 'c': 3 } for key in obj.keys(): print(key + ': ' + obj[key])
The result of running this code is that it prints each key-value pair in the object with key and value separated by a colon and a space, e.g, 'a: 1', 'b: 2', 'c: 3'.
null
Write a line of JavaScript code to create a variable `x` and assign the number `7` to it.
let x = 7;
null
Update the code to add a class attribute "var" with the value "value".
class MyClass(): def __init__(self): pass
class MyClass(): var = "value" def __init__(self): pass
[CS Wikipedia] Marty Balin Marty Balin, rodným jménem Martyn Jerel Buchwald, (30. ledna 1942 Cincinnati, Ohio, USA – 27. září 2018) byl americký zpěvák a kytarista. V roce 1965 založil skupinu Jefferson Airplane, kde byl jedním z jejích hlavních zpěváků až do roku 1971. Mezitím, v letech 1969–1970 působil ještě ve sku...
null
null
null
null
Reverse the words of the sentence "The quick brown fox jumps over the lazy dog".
dog lazy the over jumps fox brown quick The
null
Write a method in Python to calculate the sum of two numbers without using any built-in functions.
3, 5
def sum_two_numbers(a, b): result = 0 for i in range(b): result += a return result a = 3 b = 5 print(sum_two_numbers(a, b))
null
Create a function to calculate the total cost after N discounts.
discounts = [10, 15, 20]
def calculate_total(discounts): total = 0 for discount in discounts: total -= total * (discount / 100) return total
null
Generate a piece of code for raising an exception in Python.
raise Exception("This is an exception")
null
Programmatically generate a random password of length 8 that contains at least one lowercase letter, one uppercase letter, one number, and one special character.
import string import random def generate_password(): letters = string.ascii_letters numbers = string.digits symbols = string.punctuation chars = letters + numbers + symbols length = 8 password = "".join(random.sample(chars, length)) if any(char.islower() for char in password) \ and any(char.isupper() for char in passwo...
null
Create a new list where the elements are the square of the elements in the given list.
list = [1, 2, 3, 4]
new_list = [x**2 for x in list]
[HI Wikipedia] प्रक्षेप्य एक प्रक्षेप्य वह वस्तु कहलाती है जिसे दिक् (खाली अथवा नहीं) में किसी बल के अधीन प्रक्षेपित किया जाता है। यद्यपि समष्टि (दिक्) में किसी भी वस्तु की गति (उदाहरण के लिए क्रिकेट के खेल में क्षेत्ररक्षक द्वारा गेंद को फैंकना) को प्रक्षेप्य कहा जा सकता है, यह शब्द सामान्यतः कम मारक क्षमता वाली वस्त...
null
null
null
[EN Wikipedia] Üçkardeş, Ergani Üçkardeş is a neighbourhood in the municipality and district of Ergani, Diyarbakır Province in Turkey. Its population is 180 (2022). References Neighbourhoods in Ergani District
null
null
null
null
Create a for-loop in Python for printing all numbers from 1 to 9 (inclusive).
for x in range(1, 10): print(x)
null
Create a Python function that takes in a list and prints a dictionary with the elements and the product of each element.
list = [7, 8, 5]
def product_of_list(list): output = {} for element in list: output[element] = element * element return output print(product_of_list([7, 8, 5]))
null
Generate a random string of length 10 using the string library of Python.
import random import string def randomString(): letters = string.ascii_lowercase length = 10 return ''.join(random.choice(letters) for i in range(length))
null
Design an algorithm in Python to perform binary search.
def binary_search(arr, target): start = 0 end = len(arr) - 1 while start <= end: mid = (start + end) // 2 if arr[mid] == target: return mid elif arr[mid] > target: end = mid - 1 else: start = mid + 1 return -1
[DE Wikipedia] SegWit Segregated Witness, auch kurz SegWit, ist der Name für einen implementierten Soft Fork Change im Transaktionsformat der Kryptowährung Bitcoin. Der formale Titel „Segregated Witness (Consensus layer)“ hatte die Bitcoin Improvement Proposal Nummer BIP141. Ziel war es, die Transaktions-Verformbarkei...
null
null
null
null
Create a class 'Stack' that has a method 'max_stack' that returns the maximum element in the stack.
class Stack(): def __init__(self): self.stack = [] # Inserts an element in the stack def push(self, item): self.stack.append(item) # Return the maximum element in a stack def max_stack(self): max_elem = self.stack[0] for i in range(1,len(self.stack)): if self.stack[i]>max_elem: max_elem = self.stack[i] return max_elem
[CS Wikipedia] Pension pro svobodné pány Pension pro svobodné pány je český film natočený režisérem Jiřím Krejčíkem v roce 1967 podle divadelní hry Seána O'Caseyho. Situační komedie se odehrává v pensionu, do něhož si svobodný mládenec (Josef Abrhám) tajně přivede svou milenku (Iva Janžurová) a snaží se jí skrýt jedna...
null
null
null
null
Write a JavaScript function to find all words in a string.
This is a string
function findWords(str) { let words = []; let start = 0; for (let i = 0; i < str.length; i++) { if (str[i] == ' ') { let word = str.substring(start, i); if (word != '') words.push(word); start = i + 1; } } let lastWord = str.substring(start, str.length); if (lastWord != '') words.push(lastWord); return words; }
null
Using the given array, write a Javascript program to sort the elements in descending order.
let numbers = [2, 10, 5, 4, 3];
let numbers = [2, 10, 5, 4, 3]; numbers.sort((a,b) => b - a); console.log(numbers); //output: [10, 5, 4, 3, 2]
null
Write a custom python sorting algorithm.
List of numbers: [3, 2, 1, 4]
def custom_sort(list_a): # Creating a list to store the sorted elements sorted_list = [] while list_a: # Find the smallest number from the list min_item = min(list_a) # Append the smallest number to the sorted list sorted_list.append(min_item) # Rem...
[HI Wikipedia] ऋषिकेश हृषीकेश (तद्भव: ऋषिकेश) भारतीय राज्य उत्तरखण्ड के देह्रदून ज़िले में देह्रदून के निकट एक नगर है। यह गंगा नदी के दाहिने किनारे पर स्थित है और हिन्दुओं हेतु एक तीर्थस्थल है, जहाँ प्राचीन सन्त उच्च ज्ञानान्वेषण में यहाँ ध्यान करते थे। नदी के किनारे कई मन्दिर और आश्रम बने हुए हैं। इसे "गढ़वाल हिमालय ...
null
null
null
null
Write a Python program to divide two numbers and return the quotient and remainder of the division.
x = 10 y = 3
x = 10 y = 3 quotient = int(x / y) remainder = x % y print("Quotient:", quotient) print("Remainder:", remainder) # Output: Quotient: 3, Remainder: 1
null
Develop an efficient Python program to find the longest common sub-sequence from two given strings.
String1 = "ACDFSCD" String2 = "ACBCD"
def LongestCommonSubsequence(X, Y, m, n): if m == 0 or n == 0: return 0; elif X[m-1] == Y[n-1]: return 1 + LongestCommonSubsequence(X, Y, m-1, n-1); else: return max(LongestCommonSubsequence(X, Y, m, n-1), LongestCommonSubsequence(X, Y, m-1, n)); # Driver Code X = "ACDFSCD" Y = "ACBCD" m = len(X) n = len(...
null
Create a Python script to generate random numbers with using a certain range.
Minimum = 5, Maximum = 15
import random min_n = 5 max_n = 15 def random_number_generator(min_n, max_n): return random.randint(min_n, max_n) for num in range(0, 10): print (random_number_generator(min_n, max_n))
[CS Wikipedia] Zemské volby v Čechách 1889 Zemské volby v Čechách 1889 byly volby konané v Českém království 2. a 5. července 1889, kterými byli zvoleni poslanci Českého zemského sněmu coby zákonodárného sboru zemské samosprávy v rámci rakousko-uherského, respektive předlitavského ústavního systému. Probíhaly podle ku...
null
null
null
null
Write a regular expression to match a word, which has at least five letters and that only consists of lowercase alphabets.
[a-z]{5,}
null
Generate HTML table with a given list of dictionaries.
[{'name': 'John', 'age': 20}, {'name': 'Alice', 'age': 22}]
<table> <tr> <th>Name</th> <th>Age</th> </tr> <tr> <td>John</td> <td>20</td> </tr> <tr> <td>Alice</td> <td>22</td> </tr> </table>
null
Write a Python program to take two numbers as input and find the greatest common divisor.
36 and 18
def gcd(a, b): if a == 0: return b while b != 0: if a > b: a = a - b else: b = b - a return a # Test print(gcd(36, 18)) # Output: 18
null
Create a Python program to find the most common element in a list.
[3, 5, 3, 3, 3, 4, 5]
def most_common_element(list_of_numbers): # Initialize the dictionary and count the number of each element in the list frequency_dict = {} for element in list_of_numbers: if element not in frequency_dict: frequency_dict[element] = 1 else: frequency_dict[element] += 1 ...
[CS Wikipedia] Enigma (rozcestník) Enigma (ze starořeckého αἴνιγμα – hádanka) má více významů: Enigma – německý šifrovací stroj z druhé světové války Enigma (hudební skupina) – německý studiový projekt, částečně zaměřený na taneční diskotéky Enigma Records – americké hudební vydavatelství alternativní hudby osmdesátýc...
null
null
null
null
Write a Python script to find all the numbers which are divisible by 7, but are not multiples of 5; between 2000 and 3200 (both included).
res = [] for i in range(2000, 3200): if (i%7 == 0) and (i%5 != 0): res.append(str(i)) print(','.join(res))
null
Create a MySQL query to get the names of all users who are over 18.
SELECT name FROM users WHERE age > 18;
[CS Wikipedia] Coriolisova síla Coriolisova síla je setrvačná síla působící na tělesa, která se pohybují v rotující neinerciální vztažné soustavě tak, že se mění jejich vzdálenost od osy otáčení. Coriolisova síla má směr kolmý ke spojnici těleso – osa otáčení a způsobuje stáčení trajektorie tělesa proti směru otáčení ...
null
null
null
null
Update a MySQL table to increase the salary of all employees by 10%.
Employess table contains the following columns: - id: Integer - name: Text - salary: Number
UPDATE Employees SET salary = salary * 1.1;
null
Create a program to find the smallest number in a given list using a for loop in Python.
Example list: [12, 4, 16, 15]
def find_smallest_number(lst): smallest = lst[0] for number in lst: if number < smallest: smallest = number return smallest print(find_smallest_number([12, 4, 16, 15])) # Output: 4
[DE Wikipedia] Bogdan Andrejewitsch Reichmen Bogdan Andrejewitsch Reichmen (; * 26. Mai 2002 in Jewpatorija, Ukraine) ist ein russischer Fußballspieler. Karriere Reichmen begann seine Karriere beim FK Krasnodar. Im August 2018 spielte er erstmals für die dritte Mannschaft Krasnodars in der Perwenstwo PFL. In der Saiso...
null
null
null
null
Create a list of students which contains a nested list of the student’s name and age.
students = ["Sam", 19], ["Alice", 20], ["Linda", 21]
student_list = [[student[0], student[1]] for student in students]
null
Construct an algorithm in Python to find the top three numbers in a list.
[10, 8, 3, 11, 7, 14, 13]
def top_three(lst): sorted_lst = sorted(lst, reverse=True) return sorted_lst[:3] print(top_three([10, 8, 3, 11, 7, 14, 13]))
[EN Wikipedia] Academia for Equality Academia for Equality (A4E; ) is a members' organization working to promote democratization, equality and access to higher education for all communities living in Israel. The organization numbers more than 600 Israeli members, from universities and colleges both in Israel and abroa...
null
null
null
[HI Wikipedia] महाराष्ट्र महाराष्ट्र भारत का एक राज्य है जो भारत के पश्चिमी प्रायद्वीपीय क्षेत्र में स्थित है। इसकी गिनती भारत के सबसे धनी एवं समृद्ध राज्यों में की जाती है। महाराष्ट्र शब्द संस्कृत का है जो दो शब्दों द्वारा मिलकर बना है महा तथा राष्ट्र इसका अर्थ होता है महान देश। यह नाम यहाँ के संतों की देन है। इसकी र...
null
null
null
null
Create a TicTacToe game in Python.
class TicTacToe: def __init__(self): self.board = [['_' for _ in range(3)] for _ in range(3)] self.turn = 'x' def display(self): for row in self.board: print(' '.join(row)) def check_win(self): board = self.board # check if the player with the current turn has a r...
[DE Wikipedia] Anand Anand steht für: Anand (Film), Hindi-Film von Hrishikesh Mukherjee (1971) anderer Name für die keltische Gottheit Anu (Göttin) Orte: Anand (Gujarat), Stadt in Indien Anand (Distrikt), Distrikt in Gujarat, Indien Personen: Anita Anand (* 1967), kanadische Anwältin und Politikerin (Liberale Partei),...
null
null
null
[DE Wikipedia] Touros Touros, amtlich , ist eine Gemeinde in Rio Grande do Norte in der Nordostregion Brasiliens. Der Ort ist auch als „Esquina Brasiliera“ (Brasilianische Ecke) bekannt, da er sich an der nordöstlichsten Ecke des Landes befindet und die nächstgelegene südamerikanische Stadt zu Afrika ist (2841 km von ...
null
null
null
null
Design a program in Python to generate a random password.
import random, string def genRandomPassword(): length = 8 random_password= ''.join([random.choice(string.ascii_letters + string.digits + string.punctuation) for n in range(length)]) return random_password password = genRandomPassword() print(password)
null
Write a Django code to print the name of all the users in the database.
from django.contrib.auth.models import User users = User.objects.all() for user in users: print(user.username)
null
Use expand tabs to replace all the tabs in the following text with four spaces.
text = '\thello \tworld \t'
import re text = '\thello \tworld \t' text = re.sub('\t', ' ', text) print(text)
null
Write a Python program to create a symmetric matrix (with the same elements along the diagonal axis) from a given list of integers.
[1,2,3]
input_list = [1,2,3] num_elements = len(input_list) def create_symmetric_matrix(input_list): matrix = [[0 for x in range(num_elements)] for y in range(num_elements)] for i in range(num_elements): for j in range(num_elements): if i == j: matrix[i][j] = input_list[i] ...
null
Write an HTML page to display three columns with headings ‘Name’, ‘Age’ and ‘Occupation’ in a table layout.
<!DOCTYPE html> <html> <head> <title>Simple Table Layout</title> </head> <body> <h1>Table with Three Columns</h1> <table> <tr> <th>Name</th> <th>Age</th> <th>Occupation</th> </tr> </table> </body> </html>
null
Write a Python program to solve the quicksort algorithm.
Array = [10, 7, 8, 9, 1, 5]
def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right)
null
Create a test harness in C++ to verify the correctness of the following function
// A function to calculate the nth Fibonacci number // Input: nth Fibonacci number // Output: nth Fibonacci number int calcFib(int n) { if (n<=1) return n; return calcFib(n-1) + calcFib(n-2); }
#include <iostream> // Function to calculate the // nth Fibonacci number int calcFib(int n) { if (n <= 1) return n; return calcFib(n - 1) + calcFib(n - 2); } // Test Harness to verify the correctness // of the calcFib implementation int main() { // Input value to calculate const int n = 10; // Expected Output value con...
[DE Wikipedia] Kathedrale St. Jakobus (Görlitz) Die Kathedrale St. Jakobus in Görlitz ist die Bischofskirche des römisch-katholischen Bistums Görlitz. Geschichte Die heutige Kathedrale wurde in den Jahren 1898 bis 1900 nach Plänen des Architekten Joseph Ebers errichtet und am 6. Oktober 1900 geweiht. Ursprünglich war ...
null
null
null
null
Create a Python loop that will iterate through the following list and will print each item's value multiplied with 5.
numbers = [5, 10, 15, 20, 25]
for number in numbers: print(number*5)
null
Given an array containing words and a string, find the shortest word in the array that is a substring of the string
words = ["apple", "banana", "cat", "dog"], string = "aquickbrownfoxjumpsoverthelazydog"
""" Given an array containing words and a string, find the shortest word in the array that is a substring of the string. """ def find_shortest_substring(words, string): min_length = float("inf") min_word = None for word in words: j = string.find(word) if j>-1 and len(word)<min_length: min_length = len(word) min_word = ...
[EN Wikipedia] Transit River The Transit River is a river in New Zealand, flowing into Milford Sound. See also List of rivers of New Zealand References Rivers of Fiordland
null
null
null
null
Create an HTML page with two <div> elements
<html> <body> <div> Content </div> <div> Content </div> </body> </html>
null
Develop an algorithm to remove the duplicate words in a given string.
"I love coding love coding Python"
def remove_duplicates(string): words = string.split(" ") res = [] for word in words: if word not in res: res.append(word) return (" ".join(res)) string = "I love coding love coding Python" res = remove_duplicates(string) print("String after removing duplicates:") print(res)
null
Develop a python class to model a book with attributes title and authors.
class Book: def __init__(self, title, authors): self.title = title self.authors = authors myBook = Book('The Great Gatsby', 'F. Scott Fitzgerald') print(myBook.title, myBook.authors)
[CS Wikipedia] Jaguár americký Jaguár americký (Panthera onca) je kočkovitá šelma patřící do rodu Panthera. Je jediným zástupcem tohoto rodu v Americe. Po tygrovi (P. tigris) a lvu (P. leo) je největší kočkovitou šelmou a na západní polokouli úplně největší. Vyskytuje se od Mexika přes velkou část Střední Ameriky jižn...
null
null
null
null
You are given a string. Count the total number of lowercase letters in the string.
def count_lowercase(string): count = 0 for char in string: if char.islower(): count += 1 return count
null
Edit the given Python program so that it prints the current date, in the format YYYY-mm-dd.
print("Hello!")
from datetime import date print("Hello!") current_date = date.today().strftime("%Y-%m-%d") print("Today's date is", current_date)
null
Write an SQL query to select the data of all the employees who joined in the last 5 years and earn more than $100,000.
SELECT * FROM employees WHERE start_date > DATE_SUB(NOW(), INTERVAL 5 YEAR) AND salary > 100000;
[DE Wikipedia] Departamento Formosa Das Departamento Formosa liegt im Südosten der Provinz Formosa im Norden Argentiniens und ist eine von neun Verwaltungseinheiten der Provinz. Es grenzt im Norden an das Departamento Pilcomayo, im Osten an Paraguay, im Süden an das Departamento Laishí und im Westen an das Departament...
null
null
null
null
Find a way to calculate the power of a number without using * or **
base = 3 exponent = 4
def power(base, exponent): result = 1 for _ in range(exponent): result *= base return result
null
Identify the best algorithm to find the maximum sum of a subarray in a given array and write a Python code snippet accordingly.
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
def maxSubarraySum(arr): max_so_far = 0 max_ending_here = 0 for i in range(0, len(arr)): max_ending_here += arr[i] if max_ending_here < 0: max_ending_here = 0 if (max_so_far < max_ending_here): max_so_far = max_ending_here return max_so_far
null
Using Java, create a class that implements sorting of an array of integers.
public class Sorting { public void sort(int[] array) { for (int i = 0; i < array.length - 1; i++) { int index = i; for (int j = i + 1; j < array.length; j++) { if (array[j] < array[index]) { index = j; // index of lower number } } int smallerNumber = array[index]; array[index] = array[i]; array[i] = smallerNumber; } } ...
null
Write a dictionary comprehension to mapp the following list
[('a',0),('b',1),('c',2)]
{key: value for (key,value) in [('a',0),('b',1),('c',2)]}
null
Create a class called RelatedManagerListSerializerField that inherits from ListSerializerField. The class should have an __init__ method that takes in a serializer, sort_by, and use_prefetch as arguments. The class should also have a pre_value method that takes in fields and exclude as arguments, and a set_value method...
# -*- coding: utf-8 -*- from collections import Iterable try: from django.db.models.query import QuerySet from django.db.models import Manager except ImportError: QuerySet = None Manager = None from aserializer.fields import ListSerializerField from aserializer.django.utils import get_local_fields, get...
null
Create an MySQL query that finds customers whose age is between 18 and 25
SELECT * FROM customers WHERE age BETWEEN 18 AND 25;
[DE Wikipedia] Scott Harrington Scott Harrington ist der Name folgender Personen: * Scott Harrington (Rennfahrer) (* 1963), US-amerikanischer Automobilrennfahrer Scott Harrington (Eishockeyspieler) (* 1993), kanadischer Eishockeyspieler
null
null
null
null
Write a function that takes two arguments, an array arr and a value x, and returns the number of times x appears in the array arr.
arr = [1, 2, 3, 4, 5, 6, 7, 8, 5] x = 5
def count_val(arr, x): count = 0 for i in arr: if i == x: count += 1 return count count_val(arr, x)
[HI Wikipedia] मूर्वा मूर्वा (वानस्पतिक नाम : Clematis Gouriana) या 'मरोड़फली' नाम की लता हिमालय के उत्तराखण्ड को छोड़ भारतवर्ष में और सब जगह होती है। इसमें सात-आठ डंठल निकलकर इधर उधर लता की तरह फैलते हैं। फूल छोटे छोटे, हरापन लिए सफेद रंग के होते हैं। इसके रंशे बहुत मजबूत होते हैं जिससे प्राचीन काल में उन्हें वटकर धन...
null
null
null
null
Write a C program to calculate the order of a particular number in ascending order.
input_number = 4
int input_number = 4; int order = 0; for(int i=0; i < input_number; i++){ order++; } printf("The order of the number %d in ascending order is %d.", input_number, order);
null
Design a Node.js program to send a push notification to users when the deadline of a task is reached.
const { Notifications } = require('node-notifier'); function sendPushNotification() { const message = "This is a reminder that your deadline is approaching"; const notification = new Notifications({message}) notification.send(); }; // Function to monitor the deadline function deadlineMonitor() { setInterval(function(){...
null
Write a SQL statement that updates the value of attribute 'salary' to 80000 where the attribute 'deptname' is equal to 'sales'.
UPDATE employees SET salary = 80000 WHERE deptname = 'sales';
null
Derive the formula for calculating the circumference of a circle.
The formula for calculating the circumference of a circle is C = 2*π*r, where r is the radius of the circle.
null
Create a function to check if two strings are an anagram of one another using Python.
str1 = 'cat' str2 = 'tac'
def anagram_checker(str1, str2): if (len(str1)==len(str2)): if ("".join(sorted(str1.lower())) == "".join(sorted(str2.lower()))): return True else: return False
null
Generate a Python program that takes in two dates and prints the gap between them in number of days.
from datetime import datetime def days_gap(date1, date2): d1 = datetime.strptime(date1,"%m/%d/%Y") d2 = datetime.strptime(date2,"%m/%d/%Y") day_gap = abs((d2 - d1).days) return day_gap
null
Create a python function that can receive a list of integers and return a list of tuples with consecutive numbers.
[1, 2, 3, 7, 8, 9, 10]
def get_consecutive(arr): result = [] i = 0 while i < len(arr): s = i while (i + 1 < len(arr)) and (arr[i + 1] == arr[i] + 1): i += 1 result.append((arr[s], arr[i])) i += 1 return result # Test arr = [1, 2, 3, 7, 8, 9, 10] print(get_consecutive(arr)) # Outpu...
null
Develop a function to find all elements in a given array which appear more than once.
nums = [4, 3, 6, 7, 3, 8, 4, 9]
def find_duplicates(nums): duplicates = [] for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] == nums[j]: duplicates.append(nums[i]) return duplicates
null
Write a SQL query to select everyone from the table named 'users' with the first name equal to 'John'.
SELECT * FROM users WHERE firstname = 'John';
null
Create a data visualization of the following data set with the target variable as red and the predictor variables as blue.
data = [[1, 2, 1, 0], [2, 4, 0, 1], [2, 3, 0, 1], [3, 6, 1, 0]]
import matplotlib.pyplot as plt x_1 = [1, 2, 2, 3] x_2 = [2, 4, 3, 6] target = [1, 0, 1, 0] for i in range(len(x_1)): c = 'r' if target[i] == 1 else 'b' plt.scatter(x_1[i], x_2[i], marker='o', c=c) plt.title("Data Visualization") plt.xlabel("x_1") plt.ylabel("x_2") plt.show()
null
Modify this string in such a way that it should start with "Hello " and must end with " World".
str = "World, say hello"
str = "Hello World"
[EN Wikipedia] William G. Saywell link title William George Gabriel Saywell (born 1936) is a Canadian historian. He is the former president and Vice-Chancellor of Simon Fraser University Early life and education Saywell was born in 1936 in Regina, Saskatchewan to parents John Ferdinand Tupper Saywell and Vera Margueri...
null
null
null
null
Create a function in PHP to check a given string for palindromes.
<?php function checkPalindrome($str) { // Reverse the given string $revstr = strrev($str); // Checking if the string is equal to its reverse if ($str == $revstr) return true; else return false; } ?>
null
Explain what a while loop is.
A while loop is a control flow statement that repeats a set of instructions while a certain condition is true. It consists of a loop condition and a set of instructions that are to be executed as long as the condition remains true. The loop condition is evaluated first, and if it returns true then the instruction set i...
null
Generate a python program to extract all the words from a given string and store them in a list.
def extract_words_from_string(s): return s.split(' ')
null
Create a recursive function with python as the language to find the sum of all elements in a list.
def sumOfList(list): if len(list) == 1: return list[0] else: return list[0] + sumOfList(list[1:])
null
Create a program to apply upper case to a given string.
String = "welcome to The world Of gEEks"
def upperCaseString(str): res = "" for i in range(len(str)): if i==0 or (str[i-1]==' '): res = res + str[i].upper() else: res = res + str[i] return res str = "welcome to The world Of gEEks" print(upperCaseString(str))
null
Create a CSS script that centers the login form on the webpage.
.login-form { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
null
Build a state machine in Python to process incoming keyboard events
# Define a StateMachine class class StateMachine: def __init__(self): self.handlers = {} self.startState = None self.endStates = [] def add_state(self, state): self.handlers[state.name] = state def set_start(self, name): self.startState = name def set_end(self, name): self.endStates.append(name) def run(self): try: han...
null
Create a function to generate a random password of length n
import random def generate_password(n): """ Create a function to generate a random password of length n :param n: the length of the password :return: a random password of length n """ # create a character list of symbols, alphabets, and numbers characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789...
[HI Wikipedia] पेत्रोज़ावोद्स्क पेत्रोज़ावोद्स्क (रूसी: Петрозаводск, अंग्रेज़ी: Petrozavodsk) रूस के सुदूर पश्चिमोत्तर में स्थित एक शहर है जो उस देश के कारेलिया गणतंत्र नामक संघीय खंड की राजधानी भी है। यह ओनेगा झील के पश्चिमी छोर पर बसा हुआ है और उसके तट पर २७ किमी तक विस्तृत है। पेत्रोज़ावोद्स्क घटना २० सितम्बर १९७७...
null
null
null
null
Using an array, create a web page that prints out all of the array elements.
arr = [1, 2, 3, 4, 5]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Array values</title> </head> <body> <ul> <% for (let i = 0; i < arr.length; i++) { %> <li><%= arr[i] %></li> <% } %> </ul> </body> </html>
null
Update the given function to return a list of tuples where each tuple contains the name and age of each person.
def get_person_info(name, age): """Returns a tuple containing name and age.""" return "Person " + name + " is " + age + " years old."
def get_person_info(name, age): """Returns a list of tuples containing name and age.""" return [(name, int(age))]
null
Create a SQL query to find the employees with the highest salary in each job role.
SELECT a.job_role, a.emp_name, a.salary FROM employees a INNER JOIN ( SELECT job_role, MAX(salary) car_max FROM employees GROUP BY job_role ) b ON a.job_role=b.job_role AND a.salary=b.car_max;