text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Construct a Python program that takes a string as input and creates a new string with the first character of each word in the given string
"This is a sample string"
def first_letter_string(input_str): output_str = "" for w in input_str.split(): output_str += w[0] return output_str input_str = "This is a sample string" print(first_letter_string(input_str))
[DE Wikipedia] Wilhelm Behringer Wilhelm Behringer ist der Name folgender Personen: * Wilhelm von Behringer (1820–1902), deutscher Richter und Politiker, MdR Wilhelm Behringer (Richter) (1853–1931), deutscher Richter Wilhelm Behringer (Politiker) (1893–1968), deutscher Politiker (FDP), MdL Bayern Wilhelm Heinrich Behr...
null
null
null
null
Find the frequency of a given phrase in the text
text = "This is a phrase that I want to find the frequency of" phrase = "phrase"
def find_frequency(text, phrase): fdist = nltk.FreqDist(text.lower().split()) return fdist[phrase]
null
Given a text string, write a function in Python to identify all the words that have more than 3 characters.
text = "Python is an easy to learn language"
def longer_words(text): words = text.split() longer = [word for word in words if len(word) > 3] return longer
[HI Wikipedia] मुस्तानसिर बार्मा पद्म श्री डॉ॰ मुस्तानसिर बार्मा सांख्यिकीय भौतिकी के क्षेत्र में कार्यरत भारतीय वैज्ञानिक हैं। वो टाटा मूलभूत अनुसंधान संस्थान के पूर्व निदेशक हैं। शोध उनका शोध कार्य मुख्यतः सांख्यिकीय भौतिकी के क्षेत्र में है। पुरस्कार और सम्मान युवा वैज्ञानिक, भारतीय राष्ट्रीय विज्ञान अकादमी (आईएनएस...
null
null
null
null
Write an SQL query to calculate the sum of all prices of items purchased by customers.
SELECT SUM(price) FROM Purchases;
null
What is the sum of all the even numbers in the range 1-100 inclusive?
2550 # The output will be 2550
null
Write a Python program to validate a US phone number.
def is_valid_phone_number(phone): if len(phone) != 12: return False if phone[3] != '-' or phone[7] != '-': return False for i in range(0, 12): if i != 3 and i != 7: if not phone[i].isdecimal(): return False return True result = is_valid_phone_number("123-456-7890") print(resul...
null
Create a program in Python to generate random numbers.
import random def generate_random_numbers(n): numbers = [] for _ in range(n): numbers.append(random.randint(0, 100)) return numbers # Generate 10 random numbers numbers = generate_random_numbers(10) print(numbers)
[EN Wikipedia] Pakiri River The Pakiri River is a river of the Auckland Region of New Zealand's North Island. It flows generally northwest from hills overlooking Leigh, reaching the Pacific Ocean coast west of Wellsford. See also List of rivers of New Zealand References Rivers of the Auckland Region Rivers of New Zeal...
null
null
null
null
Develop a tool to detect plagiarism in python programs.
program1.py def factorial(n): res = 1 for i in range(1, n+1): res = res * i return res program2.py def factorial(n): res = 1 for i in range(1, n+1): res = res * i return res
""" Develop a tool to detect plagiarism in python programs """ import difflib def detect_plagiarism(file1, file2): file1_lines = open(file1).readlines() file2_lines = open(file2).readlines() similarity = difflib.SequenceMatcher(None, file1_lines, file2_lines).ratio() print("Similarity between the two...
null
Create a constructor in JavaScript that will assign a value to an object's properties.
properties: x, y, z
function MyObject(x, y, z) { this.x = x; this.y = y; this.z = z; }
null
Generate a rotating cube in Python using OpenGL.
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * # cube vertices vertices = ( (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1), (1, -1, 1), (1, 1, 1), (-1, -1, 1), (-1, 1, 1) ) # cube edges edges = ( (0,1), (0,3), (0,4), ...
null
Analyze a given text and generate a dictionary of frequency of each word in the text.
text = "This is a sample text to analyze the frequency of the words"
def analyze_text(text): text = text.lower().split() freqDict = {} for word in text: if word in freqDict: freqDict[word] += 1 else: freqDict[word] = 1 return freqDict if __name__ == '__main__': text = "This is a sample text to analyze the frequency of the words" print(analyze_text(text)) Output: {'this': 1, 'is': 1, 'a'...
null
Using the provided text, remove all punctuation and store the resulting output in a new variable.
text = "This is a text string with punctuation!"
import re new_text = re.sub('[^\w\s]','', text)
null
Create a Python program to search for an item in a list and return its index.
[2, 3, 5, 7, 11], target = 5
def linear_search(list, target): for index, item in enumerate(list): if target == item: return index return -1 result = linear_search([2, 3, 5, 7, 11], 5) print(result)
null
Write a C program to find the difference between the maximum and minimum values in an array.
arr = {2, 8, 10, 9}
#include<stdio.h> int diffMaxMin(int arr[], int n) { int max_num = arr[0], min_num = arr[0]; int i; for (i = 0; i < n; i++) { max_num = max_num > arr[i] ? max_num : arr[i]; min_num = min_num < arr[i] ? min_num : arr[i]; } return (max_num - min_num); } int main() { int arr[] = {2, 8, 10, 9}; int n = sizeof(arr) / sizeof...
null
Write a shell script to find all even numbers from 1 to 50.
#!/bin/bash for i in {1..50..2} do echo $i done
null
Find the Big O notation of the following code
def factorial(n): answer = 1 for i in range(1, n+1): answer *= i return answer
The Big O notation of the given code is O(n).
null
Rearrange the given array in an ascending order using selection sort algorithm.
Array: [2, 8, 5, 3, 9]
function SelectionSort(arr) { for (let i = 0; i < arr.length; i++) { let min = i; for (let j = i+1; j < arr.length; j++) { if (arr[j] < arr[min]) min = j; } let temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; } return arr; } SelectionSort([2, 8, 5, 3, 9]); // Output: [2, 3, 5, 8, 9]
[CS Wikipedia] Posuvný pohyb Posuvný pohyb (též postupný pohyb nebo translace) je takový pohyb tuhého tělesa, při kterém všechny body tělesa konají pohyb po stejných, pouze navzájem posunutých, trajektoriích. Rychlosti jednotlivých bodů tělesa jsou při posuvném pohybu stejné, proto lze zkoumání posuvného pohybu převés...
null
null
null
[DE Wikipedia] Isaak Habrecht Isaak Habrecht ist der Name folgender Personen: * Isaak Habrecht (Uhrmacher) (1544–1620), Schweizer Uhrmacher Isaak Habrecht (Mediziner) (1589–1633), Schweizer Mediziner, Astronom und Mathematiker
null
null
null
[DE Wikipedia] Entenfang Ein Entenfang ist eine Anlage zum Fang von Wildenten, siehe Vogelkoje. Entenfang steht auch für verschiedene Orte in Deutschland. in Baden-Württemberg: Entenfang, Platz in Mühlburg (Karlsruhe), Haltestelle der Straßenbahn Karlsruhe Entenfang, Waldfläche im Naturschutzgebiet Hinterwörth-Laast i...
null
null
null
null
Create a function to print out words that include the letter "e" from a given list of strings.
mylist = ["hello", "world", "fire", "feline"]
def print_words_with_e(mylist): for word in mylist: if 'e' in word: print(word) print_words_with_e(mylist) #Output: hello fire feline
[HI Wikipedia] पोर्ट सईद मुहाफ़ज़ाह पोर्ट सईद मुहाफ़ज़ाह (अरबी: , अंग्रेज़ी: Port Said Governorate) मिस्र का एक मुहाफ़ज़ाह (उच्च-स्तरीय प्रशासनिक विभाग) है। यह सुएज़ नहर के उत्तरी द्वार पर भूमध्य सागर पर स्थित एक बंदरगाह है। इन्हें भी देखें मिस्र के मुहाफ़ज़ात‎ सन्दर्भ पोर्ट सईद मुहाफ़ज़ाह मिस्र के मुहाफ़ज़ात मिस्र
null
null
null
null
Compute the absolute difference between two given numbers.
x = 7 y = 4
diff = abs(x - y) print(diff) # output: 3
null
Could you write a program in Python to simulate Conway's Game of Life?
size = 10
# create the grid function def createGrid(length, width): grid = [[0 for x in range(width)] for y in range(length)] return grid # initialise the grid with cells def initGrid(grid): for i in range(len(grid)): for j in range(len(grid[i])): grid[i][j] = int(random.random()+.5) ...
null
Write a shell script to print all the environment variables in use.
# Using Bash: # Print the environment variables for var in $(env); do echo "$var"; done
null
Optimize the following Python code to be as efficient as possible.
def fun(N): result = 0 for i in range(1, N+1): for j in range(1, N+1): result += i + j return result
def fun(N): result = (N*(N+1))/2 result *= (2 * N + 1) result /= 3 return int(result)
[HI Wikipedia] प्रभात खबर प्रभात खबर झारखंड, बिहार और पश्चिम बंगाल में दैनिक रूप से प्रकाशित होने वाला एक हिंदी भाषा का समाचार पत्र है। यह अखबार भारत के कई राज्यों में प्रसारित होता है, जिनमें बिहार, झारखंड, पश्चिम बंगाल और उड़ीसा के कुछ हिस्से शामिल हैं। इसकी स्थापना अगस्त 1984 में झारखंड की राजधानी रांची में हुई थी।...
null
null
null
[CS Wikipedia] Objemový průtok Objemový průtok (objemový tok) je objem kapaliny nebo plynu, který proteče jedním místem (celým průřezem v jednom místě trubice) za jednotku času. Značení Značka: QV Jednotka SI: metr krychlový za sekundu, zkratka m3·s−1 V imperiálních jednotkách se průtok měří v CFS, CFPS (, kubické sto...
null
null
null
null
Create a function to determine if two strings are symmetrical.
def is_symmetrical(str1, str2): for i in range(0, len(str1)): if str1[i] != str2[-i-1]: return False return True
null
Create an API in Python using the Flask framework that can create, read, update, and delete items in a database.
Not applicable
from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/items', methods=['GET', 'POST']) def items(): if request.method == 'GET': # Return all items # ... elif request.method == 'POST': # Create a new item # ... @app.route('/items/<id>', methods=['GET', 'PUT', 'DELETE']) def item(id): if ...
[DE Wikipedia] Fahad al-Mehallel Fahad al-Mehallel (; * 11. November 1970 in Riad) ist ein ehemaliger saudi-arabischer Fußballspieler. Karriere Klub Er begann seiner Karriere in der Saison 1988/89 bei al-Shabab und verbrachte hier auch den Großteil seiner Karriere. Bis zur Saison 1999/2000 gewann er mit seinem Team dr...
null
null
null
null
Explain what a constructor is and how it is used in C++.
A constructor is a special member function of a class which is used to initialize objects of its class type. A constructor has the same name as the class and its purpose is to initialize the members of an object with the given values when an object of that class is declared. In C++, constructors can be either default o...
null
Parse a given JSON string and extract all the values of the key "name".
json_str = '{"name": "Jack", "age": 22, "status": "Active"}'
import json parsed = json.loads(json_str) name_list = [] for key, value in parsed.items(): if key == 'name': name_list.append(value) print(name_list)
[EN Wikipedia] Neidy Romero Neidy Katherine Romero Mendoza (born 14 February 1995) is a Venezuelan footballer who plays as a defender. She has been a member of the Venezuela women's national team. International career Romero represented Venezuela at the 2014 South American U-20 Women's Championship. At senior level, s...
null
null
null
null
Create a MySQL query to find the name of all users in a table named "users".
SELECT name FROM users;
[DE Wikipedia] Palazzo Nuovo Der Palazzo Nuovo (deutsch Neuer Palast) in Rom ist der von der Zugangsrampe zum Kapitolsplatz aus gesehen linke Palast. Hierin befinden sich, wie im gegenüberliegenden Konservatorenpalast, zahlreiche Ausstellungsstücke der Kapitolinischen Museen. Geschichte Die Grundsteinlegung für diesen...
null
null
null
[DE Wikipedia] Riesen-Scheidenstreifling Der Riesen- oder Doppeltbescheidete Scheidenstreifling (Amanita ceciliae) ist ein Ständerpilz aus der Familie der Wulstlingsverwandten (Amanitaceae). Er ist gekennzeichnet durch große Fruchtkörper mit braunem Hut, ringlosem Stiel und grauer Gesamthülle. Die Art gilt als selten ...
null
null
null
null
Create a program to implement a selection sort in Python.
[5, 3, 2, 4, 1]
def selection_sort(arr): n = len(arr) for i in range(n-1): min_index = i for j in range(i+1, n): if arr[min_index] > arr[j]: min_index = j arr[i], arr[min_index] = arr[min_index], arr[i] return arr
[CS Wikipedia] Xylenol Xylenol (též dimethylfenol) je aromatická sloučenina se dvěma methylovými skupinami a hydroxylovou skupinou (patří tedy mezi fenoly). Existuje šest izomerů z nichž nejdůležitější je 2,6-xylenol (2,6-dimethylfenol) s oběma methylovými skupinami v poloze ortho vůči hydroxylové skupině. Název „xyle...
null
null
null
null
Find and replace all occurrences of "cat" with "dog" in the given string.
I have a cat and two cats
I have a dog and two dogs
null
Write a function in JavaScript that takes a given array and prints its elements in reverse order.
[1, 2, 3, 4]
function reverseArray(arr) { let reversedArr = []; let index = arr.length - 1; while (index >= 0) { reversedArr.push(arr[index]); index--; } return reversedArr; }
null
Make changes to the following code to include a 'break' statement.
while True: print("Hello")
while True: print("Hello") if condition is met: break
null
Select all the records in the given table where the ID is greater than 5.
Table ID | Name | Address 1 | John | UK 2 | Jack | US 5 | Mary | UK 11 | Chris | Canada
SELECT * FROM Table WHERE ID > 5;
[CS Wikipedia] De Koel De Koel nebo celým názvem podle sponzora Seacon Stadion – De Koel je fotbalový stadion v nizozemském městě Venlo a je domovem klubu VVV-Venlo. Kapacita je 8 000, z toho je 1 500 míst ke stání. Otevřen byl 19. března 1972 inauguračním zápasem mezi VVV-Venlo a Camburem, který skončil remízou 1:1. ...
null
null
null
[EN Wikipedia] George Vasey (botanist) George Vasey (February 28, 1822 – March 3, 1893) was an English-born American botanist who collected a lot in Illinois before integrating the United States Department of Agriculture (USDA), where he became Chief Botanist and curator of the greatly expanded National Herbarium. Bio...
null
null
null
null
Implement a function in Python that prints the average of the two numbers passed as arguments.
x=15 y=20
def compute_average(x, y): return (x + y) / 2 print(compute_average(x,y))
null
Write a Python program to modify a given list such that each element is equal to the square of the original element minus 2.
sample_list = [3, 5, 7, 9]
modified_list = [7, 15, 23, 31] # Python code sample_list = [3, 5, 7, 9] modified_list = [x**2 - 2 for x in sample_list]
null
Create an SQL query to select all columns from the table "Employees" in a database named "CompanyDB".
SELECT * FROM CompanyDB.Employees;
[EN Wikipedia] 2010 Omiya Ardija season 2010 Omiya Ardija season Competitions J. League 1 Emperor's Cup J. League Cup Player statistics Other pages J. League official site Omiya Ardija Omiya Ardija seasons
null
null
null
null
Create a Python program to generate 10 random numbers between 0 and 10.
import random random_numbers = [] for i in range(10): random_numbers.append(random.randint(0,10)) print(random_numbers)
[DE Wikipedia] Paris–Luxemburg 1969 Paris–Luxemburg 1969 war die 7. Austragung von Paris–Luxemburg, einem mehrtägigen Etappenrennen. Das Rennen wurde von Eddy Merckx vor Felice Gimondi und Roger De Vlaeminck gewonnen. Teilnehmende Mannschaften Etappenübersicht Ergebnisse Gesamtwertung Teamwertung Weblinks Paris–Luxemb...
null
null
null
null
Write a Python script that prints the numbers 1 to 10 and their squares.
Not applicable
def print_squares(): for i in range(1, 11): print(f'{i} : {i*i}') print_squares()
[DE Wikipedia] Viktor-Bubanj-Kaserne Die Kaserne „Viktor Bubanj“ war eine Kaserne der JNA in Sarajevo, die während des Bosnienkriegs offiziell als Militärgefängnis der bosnischen Regierungstruppen diente. Sie war nach dem ehemaligen Generalstabschef der JNA Viktor Bubanj († Oktober 1972) benannt, bekam zu Beginn des K...
null
null
null
null
What are the characteristics of a Function in JavaScript?
A function in JavaScript is a block of code that is delimited by curly brackets and is designed to perform a specific task. It consists of a function declaration, which includes the function name and its parameters, and a function body containing the code that is to be executed when the function is called. The function...
[DE Wikipedia] OpenUI5 OpenUI5 ist ein JavaScript-Framework, entwickelt um betriebssystemunabhängige Geschäftsanwendungen zu erstellen. Es ist ein Open-Source-Projekt und wird von der SAP SE unter der Apache-2.0-Lizenz entwickelt und ist offen für Erweiterungen. Der OpenUI5-Kernel basiert auf JavaScript, jQuery, und L...
null
null
null
null
Create a code in Python to send automated email notifications to customers when their orders have been delivered.
import smtplib def send_notification(email): '''This function will send automated email notifications to customers when their orders have been delivered''' sender = eamil@example.com receiver = email message = f"Your order has been delivered. Thank you for choosing us. " try: smtpObj = smtp...
null
Write a Python program that takes a dataset as input and calculates the sum, mean and median of the data.
DataSet = [1, 5, 8, 9, 12, 17, 20]
s=73 mean=10.428571 median=9 # Program to calculate the sum,mean,median of the data dataset = [1,5,8,9,12,17,20] # calculate the sum s = 0 for items in dataset: s = s + items # calculate mean mean = s/len(dataset) # calculate median dataset_sorted = sorted(dataset) m_m = len(dataset_sorted) if m_m%2 == ...
null
Given a list of strings, write a function which will return only strings which start with an uppercase letter.
String List = ["hello", "World", "foo", "bar"]
def extract_capital_words(string_list): capital_words = [] for word in string_list: if word[0].isupper(): capital_words.append(word) return capital_words
null
Create a function to calculate the Levenshtein distance between two strings
str1 = "geeks", str2 = "geek"
def lev_dist(str1, str2): if len(str1) < len(str2): return lev_dist(str2, str1) if len(str2) == 0: return len(str1) previous_row = range(len(str2) + 1) for i, c1 in enumerate(str1): current_row = [i + 1] for j, c2 in enumerate(str2): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = pr...
null
Create a program in Python that takes a sentence as an input and prints out the sentence in reverse.
Hello world!
def reverse_sentence(sentence): words = sentence.split() newWords = [word[::-1] for word in words] newSentence = " ".join(newWords) return newSentence print(reverse_sentence("Hello world!"))
null
Generate code for an ML model object-tracking system in Python. The system should be able to detect the objects like pedestrian, vehicle, animals and track the movement of the object.
Not applicable
import cv2 import numpy as np # Setup Video Capture cap = cv2.VideoCapture(0) # 0 is the default webcam # Object Classifier object_classifier = cv2.CascadeClassifier('object.xml') # Tracking while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Detect Objects objects = object_cla...
[HI Wikipedia] अरबी भाषा अरबी भाषा सामी भाषा परिवार की एक भाषा है। ये हिन्द यूरोपीय परिवार की भाषाओं से मुख़्तलिफ़ है, यहाँ तक कि फ़ारसी से भी। ये इब्रानी भाषा से सम्बन्धित है। अरबी इस्लाम धर्म की धर्मभाषा है, जिसमें क़ुरान-ए-शरीफ़ लिखी गयी है। देश अरब कई देशों की राजभाषा है, जैसे सउदी अरब, लेबनान, सीरिया, यमन, मिस्र,...
null
null
null
[HI Wikipedia] सिक्लिड सिक्लिड (Cichlid) पर्सिफ़ोर्मेज़ गण के सिक्लिडाए कुल की हड्डीदार मछलियाँ होती हैं। वे लैब्रोइडेइ (Labroidei) नामक उपगण की सदस्य होती हैं जिसमें कुछ अन्य मछली कुल भी शामिल हैं। सिक्लिडों का कुल विस्तृत और विविध है। वर्तमान में इस कुल में १,६५० से अधिक जातियाँ मिल चुकी हैं और हर वर्ष यह गिनती बढ़त...
null
null
null
null
Create a python program to test if a number is even or odd.
def is_even(num): if num%2==0: return True else: return False
null
Design a Python dictionary for storing data about countries and their corresponding capital cities.
countries_cities = { "UK": "London", "France": "Paris", "Spain": "Madrid", "Germany": "Berlin", "Italy": "Rome" }
null
What is the volume of a sphere with radius 7 cm?
The volume of a sphere with radius 7 cm is 1436.755 cm3.
null
Create a JavaScript function that takes a name as a parameter and replaces spaces with '_'
Tom Smith
function replaceSpace(name){ return name.replace(/\s/g,'_'); }
null
Compose a Python function to retrieve all documents from a Firebase Realtime Database collection.
A Firebase project URL and collection name
def get_all_docs(project_url, collection_name): # project_url and collection name # Your Firebase Config firebaseConfig = { "apiKey": "apiKey", "authDomain": "projectId.firebaseapp.com", "databaseURL": project_url, "storageBucket": "<your-storage-bucket>", } # Initializ...
null
Write a function in JavaScript to perform the following operation:
Add two numbers a and b
function sum(a, b) { return a + b; }
null
Write an SQL query to find the oldest user in the users table.
SELECT * FROM users ORDER BY age DESC LIMIT 1;
null
Construct an SQL query to find the number of records where the value in a certain column is greater than a specified value.
SELECT COUNT(*) FROM TABLE_NAME WHERE COLUMN_NAME > VALUE;
null
Design a class in Java for creating a 2D point.
public class Point { double x,y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public double distance(Point other) { return Math.sqrt(Math.pow(x - ot...
[HI Wikipedia] गढ़वा गढ़वा (Garhwa) भारत के झारखण्ड राज्य के गढ़वा ज़िले में स्थित एक शहर है। यह ज़िले का मुख्यालय भी है। राष्ट्रीय राजमार्ग 39 यहाँ से गुज़रता है। विवरण यह गढवा ज़िले का मुख्यालय है। ज़िले का निर्माण पलामू के आठ प्रखंडो को मिलाकर 1 अप्रैल 1991 को किया गया जो पलामू के दक्षिण पश्चिम हिस्से में स्थित थे।...
null
null
null
[EN Wikipedia] Galaxy 4 (disambiguation) Galaxy 4 may refer to: Technology Samsung Galaxy S4, an Android smartphone produced by Samsung Samsung Galaxy Tab S4, an Android tablet produced by Samsung Galaxy IV, a satellite belonging to Intelsat's Galaxy fleet Other uses Galaxy 4, the first serial of the third season in t...
null
null
null
null
Create a Python function which takes a list of positive integers as its argument and returns the sum of the largest and the second largest number in the list.
[123, 534, 745, 321, 876]
def get_sum(nums): assert all(n >= 0 for n in nums), "list items must all be positive!" # return the sum of the two largest numbers max_num = max(nums) nums.remove(max_num) second_max_num = max(nums) return max_num + second_max_num # test my_list = [123, 534, 745, 321, 876] print(get_sum(my_list)) # will print ...
[DE Wikipedia] Champian Fulton Champian Fulton (* 12. September 1985 in Norman, Oklahoma) ist eine US-amerikanische Jazzpianistin und -sängerin. Leben und Wirken Champian Fultons Vater ist der Trompeter und Flügelhornspieler Stephen Fulton, der mit Clark Terry befreundet ist. Bereits in der Highschool arbeitete sie mi...
null
null
null
null
Create a code snippet for making a POST request using Python.
import requests url = 'https://www.example.com' data = {'var1': 'value1', 'var2': 'value2'} response = requests.post(url, data=data)
null
Reverse this sentence: "I can do coding."
"coding do can I"
null
Create a Python program to generate random passwords that contains numbers, alphabets (upper and lower) and special characters
import random # define string of all characters string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+~<>?' # specify length of random password length = 8 # generate random password random_password = "" for i in range(length): random_password = random_password + random.choice(str...
null
Create a function in Python to find all elements of a given list whose sum is equal to a given number.
list = [5, 7, 9, 4] number = 18
def find_elements(list, number): result = [] for i in range(len(list)): for j in range(i + 1, len(list)): if list[i] + list[j] == number: result.append([list[i], list[j]]) return result # Driver code list = [5, 7, 9, 4] n = 18 print(find_elements(list, n))
null
Create a JavaScript function that takes two strings of equal length and returns the positions of the characters which don't match.
"abcdefg", "hijklmn"
function findNonMatchingPos(str1, str2) { let positions = []; if(str1.length != str2.length) { return -1; //handle unequal lengths } for(let i = 0; i < str1.length; i++) { if(str1.charAt(i) !== str2.charAt(i)) { positions.push(i); } } return positions; }
[EN Wikipedia] May-a Maya Cumming (born 2001), known professionally as May-a (stylised in all caps), is an Australian singer-songwriter from Sydney, New South Wales. On 2 February 2022, Cumming was featured on the single "Say Nothing", a collaboration with Australian electronic musician and producer Flume. Early life ...
null
null
null
null
Identify any inefficient coding practices used in the following snippet.
def find_largest(number_list): #Define variable for holding the biggest number largest = 0 for num in number_list: if num > largest: largest = num return largest
The code works, however the variable `largest` is not properly initialized. Instead of setting it to 0, it should be set to the first element in the list - `number_list[0]`. This will improve the efficiency of the code, as it will not have to perform unnecessary comparisons.
null
Suggest an efficient algorithm for sorting the following list.
[7, 1, 4, 8, 9, 2]
def sort(array): length = len(array) for i in range(length): j = i while j > 0 and array[j-1] > array[j]: # Swap elements array[j], array[j-1] = array[j-1], array[j] j -= 1 return array
null
Create a python script to identify if a given string is a valid IPv4 address or not.
String: 192.168.25.688
def is_valid_ipv4(ip): parts = ip.split('.') if len(parts) != 4: return False for part in parts: if not part.isdigit(): return False if int(part) < 0 or int(part) > 255: return False return True print(is_valid_ipv4('192.168.25.688')) Output: False
null
Write a Python code to find the nearest integer to a given number.
def nearest_integer(number): if number - int(number)>= 0.5: return int(number) + 1 else: return int(number)
[CS Wikipedia] Kostel svatého Jana Křtitele (Horní Cerekev) Kostel svatého Jana Křtitele je filiální a hřbitovní kostel v římskokatolické farnosti Horní Cerekev, nachází se na západním okraji města Horní Cerekev uprostřed hřbitova. Kostel je jednolodní barokní stavba s pozdně gotickým jádrem s polygonálním závěrem, př...
null
null
null
[CS Wikipedia] Jan Verner Jan Verner (* 3. března 1951, Mladá Boleslav) je bývalý československý motocyklový závodník, reprezentant v ploché dráze. Jeho bratrem byl plochodrážní závodník Václav Verner a strýcem bývalý plochodrážní závodník Miloslav Verner. Závodní kariéra Ve finále Mistrovství světa jednotlivců na plo...
null
null
null
null
Write a Python code that prints the longest continuous increasing sequence of integers within a given list.
[1, 2, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 9]
def longest_continuous_increasing(arr): """Function to return the length of the longest continuous increasing sequence of integers within a given list Args: arr (list): a list of integers Returns: int: the length of the longest continuous increasing sequence """ n = len(arr) max_len = 0 curr_len = 1 for i in range(1, n...
null
Generate a Python program which reads a string as input and removes all vowels present in the string and print out the revised string.
apple
def removeVowels(string): vowels = ('a', 'e', 'i', 'o', 'u') revised_string = "" for letter in string: if letter.lower() not in vowels: revised_string += letter return revised_string string = "apple" reviseString = removeVowels(string) print("Revised string =", reviseString)
null
Create a function in Python to multiply two matrices.
matrixA = [[1, 2], [3, 4]], matrixB = [[5, 6], [7, 8]]
def multiplyMatrix(A, B): rowsA = len(A) columnsA = len(A[0]) rowsB = len(B) columnsB = len(B[0]) if columnsA != rowsB: print("Cannot multiply") return result = [[0 for row in range(columnsB)] for col in range(rowsA)] # Compute matrix multiplication for i in range(rowsA): for j in range(columnsB): for k in range(column...
null
Write a Python program to generate a list containing all permutations of the characters of a given string.
string = 'ABC'
from itertools import permutations def generate_permutations(string): return list(permutations(string)) string = 'ABC' print(generate_permutations(string)) # Output: [('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
null
Implement a decision tree classifier in Python.
# Importing DecisionTreeClassifier from sklearn library from sklearn.tree import DecisionTreeClassifier # Defining the decision tree classifier # Using "entropy" as criterion to decide the further split clf = DecisionTreeClassifier(criterion="entropy") # Fitting the decision tree classifier on the data clf = clf.fit(...
null
Transform the following code from Python to JavaScript.
for i in range(10): print(i)
for (let i = 0; i < 10; i++) { console.log(i); }
null
Create an Android app to accept user input and calculate the area of a circle.
public class MainActivity extends AppCompatActivity { EditText radiusEditText; TextView outputTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); radiusEditText = findViewById(R.id.radiusEditText); outputTextView = findView...
null
Create a Python program that takes a list of words given by the user and prints out a sentence constructed from these words.
words = ['The', 'quick', 'brown', 'fox']
words = ['The', 'quick', 'brown', 'fox'] sentence = " ".join(words) print(sentence) # Output: The quick brown fox
null
Given a list of tuples, return a new list with the value of each tuple increased by one.
tuples = [(1,2), (2,3), (3,4)]
new_tuples = [] for t in tuples: new_tuples.append((t[0] + 1, t[1] + 1))