text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Create a Python web scraper for extracting data from TripAdvisor. The scraper should scrape reviews and ratings for all restaurants and hotels within 5 miles of a given geolocation.
Location coordinates - (43.626074, -79.491644)
import requests from bs4 import BeautifulSoup coords = (43.626074, -79.491644) url = 'https://www.tripadvisor.com/Search?geo={},{}&q=restaurants+and+hotels&distance=5mi'.format(*coords) response = requests.get(url).text soup = BeautifulSoup(response, 'html.parser') rating_nodes = soup.find_all('span', class_='ui_bubb...
null
Trace the recursive Fibonacci algorithm in Python and test its execution time for different values of n.
num = 10
import time def fib(n): if n<0: print("Incorrect input") elif n==1: return 0 elif n==2: return 1 else: return fib(n-1)+fib(n-2) start = time.time() num = 10 print(fib(num)) print("Time taken:", time.time()-start)
[EN Wikipedia] Cinema of South Sudan Cinema is a newly developing industry in South Sudan. History The history of cinema in what is now South Sudan started during the Anglo-Egyptian colonial period in Sudan. In Juba, as in other parts of the country, mobile cinema shows were announced by loudspeakers on the roof of a ...
null
null
null
null
Generate a Python program to print the most popular item in a list.
A list of integers [1, 5, 9, 1, 4, 5, 9]
from collections import Counter def most_popular(arr): cnt = Counter() for number in arr: cnt[number] += 1 return cnt.most_common(1)[0][0] result = most_popular([1, 5, 9, 1, 4, 5, 9]) print(result)
null
Find an example of a sorting algorithm in Python.
Example of a sorting algorithm in Python: def selection_sort(arr): for i in range(len(arr)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i + 1, len(arr)): if arr[min_idx] > arr[j]: min_idx = j # Swap the found minimum element with # the first element arr[i], arr[min_idx] = arr[mi...
null
Construct an IF-ELSE statement that test for a given condition and prints result based on that.
to_test = 5
if to_test < 10: print("Less than 10") else: print("Greater than 10")
null
This code is a Python module for a Rapidgator.net hoster plugin. To use it, import the necessary modules and classes, and then create an instance of the `RapidgatorNet` class. The class has methods for handling premium and free downloads, as well as handling captchas. The `getInfo` function is used to create an instanc...
# -*- coding: utf-8 -*- import pycurl import re from module.common.json_layer import json_loads from module.network.HTTPRequest import BadHeader from module.plugins.internal.AdsCaptcha import AdsCaptcha from module.plugins.internal.ReCaptcha import ReCaptcha from module.plugins.internal.SolveMedia import SolveMedia f...
[HI Wikipedia] वीर विक्रम गुरुङ वीर विक्रम गुरुङ का जन्म 27 अगस्त 1927 को दार्जिलिंग में हुआ। कहानियों में 'बुद्ध भरिया', 'टाइफाइड', 'ठेठ नेपाली कथा', आदि चर्चित। समाज के विभिन्न पक्षों को लेकर कहानी लिखने के लिए ये विख्यात हैं। 'अमर क्षण' कहानी संग्रह प्रकाशित। सन्दर्भ नेपाली साहित्यकार 1927 में जन्मे लोग जीवित लोग
null
null
null
null
Develop a Python program for solving a quadratic equation.
Not applicable
import cmath def quadratic_equation(a, b, c): # calculate the discriminant d = (b**2) - (4*a*c) # find two solutions sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) return sol1, sol2 if __name__ == "__main__": a = 1 b = 5 c = 6 solutions = quadratic_equation(a, b, c) print('The sol...
null
Write a SQL query to summarize the sales of each product.
Table: Sales Columns: product, quantity
SELECT product, SUM(quantity) AS total_sales FROM Sales GROUP BY product;
[CS Wikipedia] Urmi Urmi () je řeka v Chabarovském kraji v Rusku. Je dlouhá 458 km. Plocha povodí měří 15 000 km². Průběh toku Pramení na jižním svahu Badžalského hřbetu a teče podél Burejinského hřbetu. Na dolním toku protéká Dolnoamurskou nížinou. Je pravou zdrojnicí řeky Tungusky v povodí Amuru. Vodní režim Zdrojem...
null
null
null
null
Write a Python program to convert ratings in a list of strings to a float.
['4.5', '3.0', '2.5', '4.0']
def str_to_float(ratings): return [float(x) for x in ratings]
null
Write an SQL query to count the number of books of each genre.
Table Name: books Attributes: id, title, author, genre
SELECT genre, COUNT(*) AS "Number Of Books" FROM books GROUP BY genre;
null
Write a code that takes a number and prints it out in words.
25
def number_to_word(n): tens_words = { 0: '', 2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety', } ones_words = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', } tens = n // 10 ones = n % 10 return tens_words[tens] + ...
null
Write an algorithm in Python to find the average value in an array of integers.
[4, 10, 6, 8]
def avg(arr): # calculating length of array n = len(arr) total_sum = 0 for i in range(0, n): total_sum += arr[i] return total_sum / n # Driver code arr = [4, 10, 6, 8] assert avg(arr) == 7.0
null
Develop a jQuery program to toggle the visibility of a div.
$(document).ready(function () { $("#toggleBtn").click(function () { $("#toggleDiv").toggle(); }); });
null
Optimize a function in Python.
def sum_of_list(lst): sum = 0 for n in lst: sum += n return sum
def sum_of_list(lst): return sum(lst)
null
Develop a regex pattern to match email addresses.
^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$
[DE Wikipedia] Hans Schmitt Hans Schmitt ist der Name folgender Personen: * Hans Schmitt (Pianist, 1835) (1835–1907), österreichischer Musikpädagoge, Pianist und Komponist Hans Schmitt (Bildhauer) (1912–1996), deutscher Bildhauer Hans Schmitt (1924–1995), deutscher Pianist und Hochschullehrer, siehe Hans und Kurt Schm...
null
null
null
null
Parse a given XML element.
<root><book>Python for Dummies</book></root>
def parse_xml(element): root = element.find('root') book = root.find('book').text return book
null
Write a Python script to remove all repeated characters from a string.
string = "aaabbccddeeff"
def removeRepeatedChars(str): result = "" for c in str: if c not in result: result += c return result print(removeRepeatedChars("aaabbccddeeff"))
null
Design a MongoDB collection Schema for stores' inventory records.
db.inventoryRecords.insert({ storeName: String, itemName: String, quantity: Number, unitPrice: Number })
null
Format the following HTML tags correctly.
<html><head> <title>hello world</title></head></html>
<html> <head> <title>Hello World</title> </head> </html>
null
Print the sum of the first ten natural numbers.
def sum_of_first_ten(): """Print the sum of the first ten natural numbers.""" total = 0 for i in range(1, 11): total += i return total if __name__ == '__main__': print(sum_of_first_ten())
null
Generate a random list of 20 unique numbers from 0 to 30.
[3, 5, 12, 11, 14, 0, 22, 19, 10, 6, 1, 25, 18, 27, 24, 16, 17, 21, 20, 15]
null
Given a linked list, write a python program to reverse the linked list.
# A Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # A function to reverse the linked list ...
null
Use Python to build a random number generator in the range [0, 10).
import random x = random.randint(0, 9) print(x)
[EN Wikipedia] 1939–40 Norwegian Ice Hockey Championship season The 1939–40 Norwegian Ice Hockey Championship season was the sixth season of ice hockey in Norway. 14 teams participated in the league, and Grane won the championship. Results First round Grane Stabekk - Forward 3:1 Bygdø - Ready 2:6 B14 - Frisk 1:2 Frogn...
null
null
null
[EN Wikipedia] 1860 in Denmark Events from the year 1860 in Denmark. Incumbents Monarch – Frederick VII Prime minister – Carl Edvard Rotwitt (until 8 February), Carl Christian Hall (from 24 February) Events 8–14 July – The 8th Scandinavian Scientist Conference is held in Copenhagen. 20 November – The frigate Jylland i...
null
null
null
null
Write a script to iterate over all elements in a list, and sum up all integers greater than 5.
var myList = [3, 7, 5, 6, 1]
function sumOfInt(arr) { var sum = 0; for (var i = 0; i < arr.length; i++) { if (arr[i] > 5) { sum += arr[i]; } } return sum; } sumOfInt(myList); // Returns 13
null
Generate a simple python function to concatenate two lists.
def concatenate_lists(list1, list2): return list1 + list2
null
Compare two lists to find missing numbers.
list1 = [1, 2, 3, 4, 5] list2 = [2, 3, 4]
# Create a new set to store the missing numbers missing_numbers = set(list1).difference(set(list2)) # Print the missing numbers print("Missing numbers:", *missing_numbers)
null
Generate a Python script to calculate the total cost of items in a grocery list.
list = {"banana": 2.5, "apple": 3.7, "orange": 4.2, "tomato": 1.2}
# Calculating the total cost of items in a grocery list list_cost = 0 list_items = {"banana": 2.5, "apple": 3.7, "orange": 4.2, "tomato": 1.2} for item, price in list_items.items(): list_cost += price print('The total cost of the items in the list is {}'.format(list_cost)
null
Create a class with two methods, one to return the name and the other to return the age.
class Person: def __init__(self, name, age): self.name = name self.age = age def get_name(self): return self.name def get_age(self): return self.age
[HI Wikipedia] आरगाउ कैन्टन आरगाउ कैन्टन (जर्मन व अंग्रेज़ी: Aargau) स्विट्ज़रलैंड के उत्तर में स्थित एक् कैन्टन (प्रान्त से मिलता-जुलता प्रशासनिक विभाग) है। इस कैन्टन को सन् १८०३ में नेपोलियन बोनापार्ट ने स्विट्ज़रलैंड में हस्तक्षेप करते हुए अपने 'मध्यस्थता विधेयक' (Act of Mediation) के तहत स्विस परिसंघ का हिस्सा बना...
null
null
null
[CS Wikipedia] Vladimír Váňa Vladimír Váňa (15. února 1932 – 25. března 2000) byl český esperantista. Dílo Vynikající je jeho překlad J. Otčenáška: Romeo, Julia Kaj Tenebro (Romeo, Julie a tma) Jaroslav Hašek – Povídky, Osudy dobrého vojáka Švejka Jiří Haussmann – Danoj en Praha''' (Dánové v Praze) Karel Poláček – Joa...
null
null
null
null
Generate a Python code to find the power of a number.
base = 2 exponent = 4
# Calculate power of a number def power(base, exponent): # Initialize result result = 1 # Multiply result with base # until exponent becomes 0 while exponent != 0: result *= base exponent -= 1 # Return result return result # Print the power print(power(base, exponent))
[HI Wikipedia] मोज़ाम्बीक मोज़ाम्बीक (अंग्रेजी: Mozambique, पुर्तगाली: Moçambique) दक्षिणपूर्वी अफ़्रीका में स्थित एक देश है जो पूर्व में हिन्द महासागर से, उत्तर में तंज़ानिया से, पश्चिमोत्तर में मालावी और ज़ाम्बिया से. पश्चिम में ज़िम्बाब्वे से और दक्षिण में स्वाज़ीलैंड और दक्षिण अफ़्रीका से बंधा हुआ है। पहली से पांच...
null
null
null
null
Construct a query in SQL to select users from the "Users" table aged between 30 and 40.
// Table Name Users
SELECT * FROM Users WHERE age BETWEEN 30 AND 40;
[HI Wikipedia] ऋषभदेव तहसील ऋषभदेव राजस्थान, भारत में उदयपुर जिले की एक तहसील है। तहसील में 125 राजस्व गांव और एक शहर शामिल है। तहसील मुख्यालय ऋषभदेव में स्थित है। सन्दर्भ राजस्थान की तहसीलें उदयपुर जिले की तहसीलें
null
null
null
null
Create a set of classes in Python to represent a school database.
class Student: def __init__(self, name, grade): self.name = name self.grade = grade class Course: def __init__(self, name, teachers): self.name = name self.teachers = teachers class School: def __init__(self, name): self.name = name self.studen...
null
Design an algorithm in Python to detect duplicate elements in an array.
[1, 2, 3, 4, 2]
def find_duplicates(lst): seen = set() duplicates = [] for item in lst: if item in seen: duplicates.append(item) else: seen.add(item) return duplicates
null
Output a list of all even numbers between two given positive integers m and n.
m=2, n=10
def evenNumbers(m,n): evenNum=[] for i in range(m,n+1): if i%2 == 0: evenNum.append(i) return evenNum
null
Explain how to use Binary Search in Python?
Binary search is an efficient search algorithm for sorted arrays. In Python, the bisect module can be used for binary search. The bisect.bisect() function finds the position of the number in the list or a place for the number if it is not present. The bisect.bisect_left() function does the same, but carefully chooses i...
[EN Wikipedia] 1937–38 Hovedserien season The 1937–38 Hovedserien season was the fourth season of ice hockey in Norway. Eight teams participated in the league, and Ski- og Fotballklubben Trygg won the championship. First round Group A Group B Final Ski- og Fotballklubben Trygg - Grane 2:0 Relegation First round Sports...
null
null
null
[EN Wikipedia] Southampton, Nova Scotia Southampton is a community in the Canadian province of Nova Scotia, located in Cumberland County . It has two roads leading up to it, Route 2 and Route 302. In Southampton, Nova Scotia there is the Elizabeth House General Store, which opened in 1923. References Southampton on De...
null
null
null
null
Create a Python script that takes a string of comma-separated temperatures and returns a minimum, maximum, and median value.
Input String: 82.0, 84.3, 69.6, 78.2
input_string = '82.0, 84.3, 69.6, 78.2' temperatures = [float(temp) for temp in input_string.split(',')] min_temp = min(temperatures) max_temp = max(temperatures) median_temp = statistics.median(temperatures) print(f'Minimum temperature: {min_temp}, Maximum temperature: {max_temp}, Median temperature: {median_temp}'...
null
What is the syntax to print out the following string?
string = "Hello World!"
print(string)
null
Create a JSON object to represent an address.
{ "houseNumber": "20", "streetName": "Main Street", "city": "Anytown", "state": "AL", "zip": "12345" }
null
Construct a Python function to redesign a given list to meet a given sorting criteria.
my_list = [31, 5, 42, 69, 20]
def sort_list(my_list): return sorted(my_list)
null
Design a program to find the nth Fibonacci number.
n: 10
def nth_fibonacci(n): if n == 0 or n == 1: return 1 else: n1, n2 = 1, 1 for i in range(2, n): n1, n2 = n2, n1 + n2 return n2
null
Create a Python-Flask application for managing a library book catalog. The application should have routes for listing books, adding new books, and deleting books.
Not applicable
# Import Flask and other necessary libraries from flask import Flask, render_template, request, jsonify # Create a Flask app app = Flask(__name__) # Create a books list in memory books = [ { 'name': 'Python Crash Course', 'author': 'Eric Matthes', 'read': False }, { 'name': 'Fluent Python', 'author': 'Luciano R...
[DE Wikipedia] US Marosticense Die Unione Sportiva Marosticense ist ein italienischer Fußballverein aus der Kleinstadt Marostica. Die erste Mannschaft spielt aktuell in der 6. Liga Italiens, der Campionato di Eccellenza. Geschichte Die Gründung von U.S. Marosticense erfolgte 1900 von Mitarbeitern eines Unternehmens in...
null
null
null
[HI Wikipedia] वोपदेव वोपदेव विद्वान्, कवि, वैद्य और वैयाकरण ग्रंथाकार थे। इनके द्वारा रचित व्याकरण का प्रसिद्ध ग्रंथ 'मुग्धबोध' है। इनका लिखा कविकल्पद्रुम तथा अन्य अनेक ग्रंथ प्रसिद्घ हैं। ये 'हेमाद्रि' के समकालीन थे और देवगिरि के यादव राजा के दरबार के मान्य विद्वान् रहे। इनका समय तेरहवीं शती का पूर्वार्ध मान्य है। य...
null
null
null
null
Create a basic game in Python using Pygame.
Not applicable
import pygame import time # defines the size of the window WINDOW_SIZE = (400, 400) # initializes pygame pygame.init() screen = pygame.display.set_mode(WINDOW_SIZE) # game parameters done = False clock = pygame.time.Clock() # game loop while not done: # gets all events for event in pygame.event.get(): if eve...
[CS Wikipedia] Stříbrná (rozcestník) Pojem Stříbrná má více významů: stříbrná - barva název sídla Stříbrná - obec v okrese Sokolov Stříbrná Skalice - obec v okrese Praha-Východ název ulice Stříbrná (Praha) - ulice v Praze 1-Starém Městě jiné Stříbrná Huť - přírodní památka v okrese Tábor Stříbrná studánka (Křemešník) ...
null
null
null
null
Generate an array of the first 10 Fibonacci numbers using any programming language.
let fib = [0, 1]; while (fib.length < 10) { fib.push(fib[fib.length - 1] + fib[fib.length - 2]); } console.log(fib); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
null
Write a Python program to implement a decision tree classifier to classify iris flowers into three categories (setosa, versicolor and virginica).
The iris dataset consists of 50 samples from each of three species of Iris (Iris setosa, Iris virginica and Iris versicolor). Four features were measured from each sample: the length and the width of the sepals and petals, in centimeters.
import numpy as np from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import load_iris # load data iris = load_iris() X = iris.data y = iris.target # split data into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, te...
[CS Wikipedia] Zizinho Zizinho, původním jménem Thomaz Soares da Silva (14. října 1921 – 8. února 2002) byl brazilský fotbalista. Hrával na pozici útočníka. S brazilskou reprezentací získal stříbrnou medaili na mistrovství světa roku 1950, kde se rovněž dostal do all-stars týmu a poté co FIFA začala roku 1950 vyhlašov...
null
null
null
null
Using the .sort() method, sort an array in ascending order.
[5, 3, 9, 1]
arr.sort()
null
Create a C program to print the numbers from 1 to 100, except for any number divisible by 3.
#include <stdio.h> int main() { for (int i = 1; i <= 100; i++) { if (i % 3 != 0) printf("%d\n", i); } return 0; }
null
Create a Python program that takes in text input from the user and searches a given list of strings to find any matches.
strings = ["First","Second","Third"]
import re # input string strings = ["First","Second","Third"] # Get the string inp_str = input("Please enter your string :") # Initialize the flag found = False # Search the string for i in strings: if re.search(i, inp_str): found = True # Print result if found == True: print("String m...
null
Describe the Pandas feature "DataFrame"
Pandas DataFrame is a two-dimensional data structure, i.e. data is aligned in a tabular fashion in rows and columns. It is a widely used tool for data manipulation and analysis in Python. It offers a variety of features such as filtering, sorting, adding/removing columns, updating the data, indexing, and many others.
[HI Wikipedia] दस सर्वकालीन सर्वश्रेष्ठ चलचित्र दस सर्वकालीन सर्वश्रेष्ठ हिंदी चलचित्र कुछ लोग इन्हें मानते हैं : मदर इन्डिया दो बीघा ज़मीन मुगल-ए-आज़म आवारा गाइड प्यासा शोले जाने भी दो यारों बन्दिनी जागते रहो हिन्दी सिनेमा
null
null
null
null
Create a processing sketch that can randomly generate 500 circles.
// Setup a canvas of 500x500 void setup() { size(500, 500); } // Randomly draw 500 circles in the canvas void draw() { for (int i=0; i<500; i++) { float x = random(0, 500); float y = random(0,500); float rand = random(0, 100); fill(rand, rand, rand); ellipse(x, y, 20, 20); } }
null
Write C++ code to find the maximum subarray sum
int maxSubarraySum(int arr[], int n) { int max_so_far = 0, max_ending_here = 0; for (int i = 0; i < n; i++) { max_ending_here = max_ending_here + arr[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; }
[EN Wikipedia] Stanislav Sukhina Stanislav Valeryevich Sukhina (; born August 16, 1968, in Cherkasy, Ukraine, Soviet Union) is a Russian football official and a former referee and player. As a player, he played in the lower leagues for FC Avangard Kolomna (1989), FC Saturn Ramenskoye (1990) and FC Gigant Voskresensk (...
null
null
null
[EN Wikipedia] Acer washingtonense Acer washingtonense is an extinct maple species in the family Sapindaceae described from one fossil leaf and four fossil samaras. The species is solely known from the Early Eocene sediments exposed in northeast Washington state, United States. It is one of three species belonging to ...
null
null
null
null
Update the given CSS class statement.
.red_box { background-color: #AAFF00; margin: 10px; width: 20px; }
.red_box { background-color: #AAFF00; margin: 10px; padding: 15px; width: 20px; border-radius: 10px; }
null
How many continuous substrings are there in the string "Geeks"?
15
null
Read the following code and identify the type of loop it is.
for a in range(0, 10): print(a)
for loop.
null
Design a web page to display the first ten elements of a given 2D array.
A 2D array [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
<table> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>6</td> </tr> <tr> <td>7</td> <td>8</td> <td>9</td> </tr> <tr> <td>10</td> <td>11</td> <td>12</td> </tr> </table>
null
Write the code to print a given table format in Python.
Table with 4 columns and 5 rows
for i in range(1,6): print('{:<10}{:<10}{:<10}{:<10}'.format(i, i**2, i**3, i**4))
null
Build a neural network using Python
import numpy as np # Sample data X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) y = np.array([[0, 1, 1, 0]]).T
import keras # Create a neural network model = keras.Sequential([ keras.layers.Dense(2, activation='sigmoid'), keras.layers.Dense(1, activation='sigmoid') ]) # Compile the model model.compile(optimizer='adam', loss='mean_squared_error') # Train the model model.fit(X, y, epochs=1000)
null
Generate a code to create a Pyramid of stars with the given height.
def print_pyramid(height): for row in range(1, height + 1): for col in range(1, row + 1): print('*', end=" ") print('\n')
[DE Wikipedia] Beiseker Beiseker ist eine Gemeinde im südlichen Alberta, Kanada, mit dem Status eines Dorfes (). Geschichte Beiseker, das in einem fruchtbaren Gebiet liegt, wurde 1908 auf Bestreben der Calgary Colonization Company als landwirtschaftliches Zentrum gegründet. Aus Deutschland stammende Siedler, die zunäc...
null
null
null
[EN Wikipedia] Purakaunui River The Purakaunui River is a river in the western Catlins, New Zealand. It rises west of Houipapa and flows through the Pūrākaunui Bay Scenic Reserve into the Pacific Ocean at Pūrākaunui Bay. The river is best known for Purakaunui Falls. See also List of rivers of New Zealand References Ri...
null
null
null
null
Write a JavaScript program to check if two numbers are equal.
3 and 5
function areEqual(x, y){ if (x === y){ return true; } else{ return false; } }
null
Create a Python script that generates a random password.
Not applicable
import random import string def generate_password(): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for _ in range(15)) return password print(generate_password())
null
Write a Bash script to check if a given password matches the given regular expression.
Regular expression: ^[0-9][A-Z]+$ Password: 123ABC
#!/bin/bash if [[ "$1" =~ ^[0-9][A-Z]+$ ]]; then echo "Password matches the regular expression" else echo "Password does not match the regular expression" fi
[HI Wikipedia] गान्दरबल ज़िला गान्दरबल​ ज़िला भारत के जम्मू व कश्मीर राज्य का एक ज़िला है। यह पहले श्रीनगर ज़िले का हिस्सा हुआ करता था जिसकी दो तहसीलों (गान्दरबल​ और कंगन) को मिलाकर ६ जुलाई २००६ को इस ज़िले का गठन किया गया। तहसीलें ज़िले के गठन के बाद इसमें छह तहसीलें निर्धारित की गई- गान्दरबल तुलमुल, जहाँ खीर भवानी म...
null
null
null
null
Generate a random string of length 5 with only lowercase alphabetic characters.
import string import random def generate_random_string(length): allowed_characters = string.ascii_lowercase return ''.join(random.choices(allowed_characters, k=length)) random_string = generate_random_string(5) print(random_string)
null
Create a function named `parse_file` that takes a parameter named `datafile`. The function should read the input `datafile` line by line, and for the first 10 lines (not including the header) split each line on "," and then for each line, create a dictionary where the key is the header title of the field, and the value...
# Your task is to read the input DATAFILE line by line, and for the first 10 lines (not including the header) # split each line on "," and then for each line, create a dictionary # where the key is the header title of the field, and the value is the value of that field in the row. # The function parse_file should retur...
null
Given a list of lists, generate a single flattened list.
lst = [[1, 2], [3, 4], [5, 6]]
lst = [[1, 2], [3, 4], [5, 6]] flattened = [item for sublist in lst for item in sublist] print(flattened)
null
Generate a code to reverse a string without using any loop.
Input String = "Hello World!"
input_string = 'Hello World!' def reverse_string(input_string): if len(input_string) == 0: return "" else: return reverse_string(input_string[1:]) + input_string[0] res = reverse_string(input_string) print(res)
null
Create a python program that takes a keyword as an input and prints the top 10 relevant Wikipedia articles for that keyword
import wikipedia def get_top_ten_results(keyword): results = wikipedia.search(keyword, results=10) for result in results: print(result)
null
Edit the following Python code such that the function produces output in the format "<Name> said: '<Message>'.
def generate_message(name, message): print(name + ' said: ' + message)
def generate_message(name, message): print(name + ' said: ' + "'" + message + "'")
null
Write a regex expression to validate a username containing only letters, numbers, underscores, and hyphens.
/^[a-zA-Z0-9_\-]+$/
[HI Wikipedia] दार्दिस्तान दार्दिस्तान (पारसी-अरबी : داردستان) जी डब्ल्यू लिटनर द्वारा दिया गया एक भौगोलिक नाम है जो भारतीय कश्मीर, उत्तरी पाकिस्तान तथा उत्तर-पूर्वी अफगानिस्तान को सूचित करता है। इस भूभाग के निवासी दार्दी भाषाएँ बोलते हैं और 'दार्द' कहलाते हैं। इसके अंतर्गत चित्राल, यासिन, पेंन्याल, गिलगिट घाटी, हुजा ...
null
null
null
null
Create a _JSON serializer_ for a given Python data structure.
data = { 'name': 'Alice', 'age': 22, 'hobbies': ['coding', 'guitar'] }
import json data = { 'name': 'Alice', 'age': 22, 'hobbies': ['coding', 'guitar'] } json_data = json.dumps(data) print(json_data)
null
The given code is a Python implementation of kNN algorithm for classification. It includes functions for reading data from a file, normalizing the data, and implementing the kNN algorithm. To use this code, call the "datingClassTest" function, which reads data from a file, normalizes it, and tests the kNN algorithm on ...
#-*- coding: utf-8 -*- from numpy import * import operator # 读取数据到矩阵 def file2matrix(filename): # 打开数据文件,读取每行内容 fr = open(filename) arrayOLines = fr.readlines() # 初始化矩阵 numberOfLines = len(arrayOLines) returnMat = zeros((numberOfLines,3)) # 初始化类标签向量 classLabelVector = [] # 循环读取...
null
Create a while loop using the given conditions.
counter = 0 max_count = 5
while counter < max_count: counter += 1
null
Develop a Python web-crawler that takes a URL as input and returns the number of words on the page.
url = http://example.com
import requests from bs4 import BeautifulSoup def get_page_word_count(url): r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') words = soup.find_all(text=True) count = 0 for w in words: count += len(w.split()) return count url = "http://example.com" word_count = get_page_word_cou...
[DE Wikipedia] Arnold Cramer Arnold Cramer (* 2. Oktober 1941; † 26. August 2010) war ein deutscher Fußballspieler. Der Verteidiger hat in der Saison 1960/61 beim FC Schalke 04 in der damals erstklassigen Fußball-Oberliga West zehn Ligaspiele absolviert. Schalke belegte am Rundenende den dritten Platz. Spielerlaufbahn...
null
null
null
null
Create a function in Python that takes a string and returns a new string with the characters in reverse order.
"Hello World!"
def reverse_string(input_str): reversed_str = "" for i in range(len(input_str)-1,-1,-1): reversed_str += input_str[i] return reversed_str print (reverse_string("Hello World!"))
null
Use recursion to construct a list of the first 10 powers of two (1, 2, 4, 8, ...).
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
null
Write a Python program to return the first prime number greater than 5.
def prime_number(num): while True: is_prime = True for i in range(2,num): if (num % i == 0): is_prime = False if is_prime: return num num += 1 x = prime_number(5) print(x)
null
Write a Python program that takes in a list and outputs the sum of the elements in the list.
[1, 2, 3, 4, 5]
sum = 0 for x in [1,2,3,4,5]: sum += x print(sum)
null
Modify the given Python code to be more efficient.
def my_function(N): list1 = [] for i in range(N): list2 = [] for j in range(N): list2.append(i+j) list1.append(list2) return
def my_function(N): list1 = [[i+j for j in range(N)] for i in range(N)] return list1
null
Given a string s, write a program to classify it as a palindrome or not.
s = “malayalam”
def is_palindrome(s): n = len(s) for i in range(n//2): if s[i] != s[n-1-i]: return False return True