text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
How do you create a new list in Python from a given list that contains the square of each element?
The following code creates a new list from the given list by squaring each element using a list comprehension: new_list = [el**2 for el in original_list]
null
Write pseudocode to sort a given list of integers using bubble sort.
# Set a swap flag to true swap = true # While the flag is true while swap # Set the swap flag to false swap = false # Iterate through the list for i in range(len(list) - 1): # Swap adjacent element if they are out of order if list[i] > list[i + 1]: temp = list[i] list[i] = list[i + 1] list[i + 1] = temp # Set the flag ...
null
Create a data structure to store records of students' attendance.
struct StudentAttendance { int studentId; // Unique identifier for each student int classId; // Unique identifier for each class int year; // Year of the class string month; // Month of the class int attendance; // Number of attendances };
[HI Wikipedia] मॉरिशस मॉरीशस गणराज्य (अंग्रेज़ी: Republic of Mauritius, फ़्रांसीसी : République de Maurice), अफ्रीकी महाद्वीप के तट के दक्षिणपूर्व में लगभग 900 किलोमीटर की दूरी पर हिंद महासागर में और मेडागास्कर के पूर्व में स्थित एक द्वीपीय देश है। मॉरीशस में हिंदुओं की आबादी तीसरे नंबर पर है दुनिया में मॉरीशस द्वीप क...
null
null
null
null
How would you output the average value of a given list of numbers?
list_int = [2, 7, 15, 25]
avg = sum(list_int) / len(list_int) # avg = 11.5
[DE Wikipedia] Atsushi Inaba Atsushi Inaba (jap. 稲葉 敦志 Inaba Atsushi; * 28. August 1971 in Kanazawa, Präfektur Ishikawa) ist ein japanischer Spieleentwickler, bekannt für mehrere populäre Videospiele. Heute arbeitet er für das unabhängige Entwicklerstudio Platinum Games (ehemals Seeds), welches er mit Shinji Mikami un...
null
null
null
null
Write a Python script to find the area of a triangle with sides 18, 24, and 30.
def triangle_area(a, b, c): '''This function computes the area of a triangle given its side lengths.''' # Calculate semi-perimeter s = (a + b + c) / 2 # Calculate the area area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 return area print("The area of the triangle is:", triangle_area(18, 24, 30))
null
How can you use a for loop to traverse a dictionary?
You can use a for loop to traverse a dictionary by iterating over the dictionary's keys or key-value pairs. For example, you can loop through all the keys of a dictionary like this: dictionary = { 'a':1, 'b':2, 'c':3 } for key in dictionary: print(key) Or you can loop through all the key-value pairs like this: dictiona...
[CS Wikipedia] Farní sbor Českobratrské církve evangelické v Sedlci-Prčicích Farní sbor Českobratrské církve evangelické v Sedlci-Prčicích je sborem Českobratrské církve evangelické v Sedlci-Prčicích. Sbor spadá pod Pražský seniorát. Farářem sboru je Josef Bartošek, kurátorem sboru Jindřich Souček. Faráři sboru Jarosl...
null
null
null
null
Convert the following SQL query to Python.
SELECT * FROM `employee_table` WHERE `salary` < 10000
import sqlite3 db = sqlite3.connect("employee_table.db") # Assumes the table is in a file named employee_table.db cur = db.cursor() # Execute the SQL command cur.execute("SELECT * FROM employee_table WHERE salary < 10000") # Commit your changes db.commit() # Get the results results = cur.fetchall() # Print the res...
[CS Wikipedia] Claude Piron Claude Piron (26. února 1931 Namur – 22. ledna 2008 Gland) byl přední švýcarský lingvista, docent psychologie na ženevské univerzitě, spisovatel a esperantista, v letech 1956–1961 překládal pro OSN. Pro svou uměleckou tvorbu v esperantu používá pseudonym Johán Valano. Esperantskou literatur...
null
null
null
null
Generate a HTML layout to make a basic website page.
<!Doctype html> <html> <head> <title>My Website</title> </head> <body> <h1>Welcome to My Website!</h1> <p>Content goes here.</p> </body> </html>
[DE Wikipedia] Ivo Zen Ivo Zen (1970 in Santa Maria im Münstertal) ist ein Schweizer Dokumentarfilmregisseur. Biografie Ausbildung Ivo Zen wuchs als Sohn eines italienischen Einwanderers und einer Bündnerin im Münstertal auf. 1992–1996 studierte er Architektur an der Eidgenössischen Technischen Hochschule ETH Zürich, ...
null
null
null
null
Generate a Python class with a constructor that initializes two variables - a list and a dictionary.
class MyClass: def __init__(self): self.list = [] self.dictionary = {}
null
Write a code to generate a random password with a given length.
import random import string def generate_password(length): chars = string.ascii_letters + string.digits + '!@#$%^&*()' random.seed = (random.SystemRandom().random()) return ''.join(random.choice(chars) for i in range(length)) print(generate_password(10)) # Output is an alphanumeric string of length 10
[CS Wikipedia] Václav Drchal Václav Drchal (* 25. července 1999 České Budějovice) je český profesionální fotbalista, který hraje na pozici útočníka za český klub FK Jablonec. Mezi jeho přednosti patří rychlost. Klubová kariéra AC Sparta Praha Do sparťanské juniorky přestoupil v červenci 2016. V sezoně 2017/18 v junior...
null
null
null
null
Create a Python script which takes a list containing items and their prices and calculates the total cost.
[('Bread', 5.99), ('Cheese', 4.99), ('Milk', 2.99)]
total = 0 items_with_price = [('Bread', 5.99), ('Cheese', 4.99), ('Milk', 2.99)] for item, price in items_with_price: total += price print(f'The total cost is ${total}')
null
Fix the following code so that it works without errors.
``` def remove_characters(name, characters): for c in characters: name.replace(c, '') return name name = "Alice" characters = ["A", "e"] ```
``` def remove_characters(name, characters): for c in characters: name = name.replace(c, '') return name name = "Alice" characters = ["A", "e"] ```
null
Create a Python program to replace all occurance of a target string in a sentence with a replacement string.
Sentence: “Hello world, this is a sample text. We needed to replace the word “world” with “Earth” Target: world Replacement: Earth
sentence = "Hello world, this is a sample text. We needed to replace the word “world' with “Earth”" target = "world" replacement = "Earth" def replace_string(sentence, target, replacement): return sentence.replace(target, replacement) updated_sentence = replace_string(sentence, target, replacement) print(updated_...
null
Create a Base64 encoder/decoder function in Python.
Not applicable
import base64 def encode(string): encoded = base64.b64encode(string.encode()) return encoded.decode('utf-8') def decode(encoded_string): decoded = base64.b64decode(encoded_string.encode()) return decoded.decode('utf-8') if __name__ == "__main__": original_string = "Hello World!" encoded_string = encode(origina...
null
Write a SQL query to list the name of customers and associated shipping addresses.
SELECT c.name, s.address FROM customers c INNER JOIN shipping_address s ON c.id = s.customer_id
null
Write a script that prints out the current value of environment variables
For example, using Node.js: Object.keys(process.env).forEach(key => { console.log(`${key}: ${process.env[key]}`); });
null
Name the grammar that is used to identify data in a Javascript string.
The grammar used to identify data in a JavaScript string is JSON (JavaScript Object Notation).
null
Can you build a linear regression model to predict the housing prices in the given dataset?
The dataset contains 15 columns with 3,000 records.
Yes, it is possible to build a linear regression model to predict the housing prices in the given dataset. You will have to split the dataset into a training and testing set and then use the training set to build a linear regression model. Once the model is built, use it to predict labels on the test set and then evalu...
null
Generate a python script to calculate the standard deviation of a given data set.
data_set = [2,4,4,4,5,5,7,9]
import statistics data_set = [2,4,4,4,5,5,7,9] print(round(statistics.stdev(data_set),2))
null
Write CSS code to style a web page with a white background and black text.
body { background-color: white; color: black; }
[CS Wikipedia] TJ Cement Hranice TJ Cement Hranice je klub házené z Hranic, účastník české nejvyšší soutěže – STRABAG RAIL Extraligy mužů. Národní házená se v hranickém Sokole provozovala od roku 1923. V roce 1957 byl založen klub TJ Tatran Hranice, hrající pod patronátem místní cementárny. V roce 1962 se tým přeorien...
null
null
null
null
How would you form a list from two lists by taking elements at same index from both the lists?
def form_list_from_list(list1, list2): return [list1[i] + list2[i] for i in range(len(list1))] if __name__ == '__main__': list1 = [1, 2, 3] list2 = [4, 5, 6] print(form_list_from_list(list1, list2))
null
Write a Python function to identify the longest word in a given list of strings.
def longest_word(word_list): longest_word = word_list[0] for word in word_list: if len(word) > len(longest_word): longest_word = word return longest_word
null
Write a SQL query to get the titles and release dates of all the movies from the Movies table released in the year 2019.
SELECT title, release_date FROM Movies WHERE YEAR(release_date) = 2019
null
Generate a list containing all multiples of 3 from 0 to 30.
multiples_of_3 = [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
[CS Wikipedia] Azua Azua je provincie Dominikánské republiky, ležící na jihozápadě krajiny. Rozlohou je to pátá největší provincie; Azua zabírá z celkové rozlohy státu 5,2 %. Počtem obyvatel je Azua desátý největší region a počet obyvatel Azuy k celkovému obyvatelstvu Dominikánské republiky je 2,4 %. Provincie Azua má...
null
null
null
null
Write a Python program to read a list of numbers and print them as a single string without any space.
[34, 32, 67, 85]
my_list = [34, 32, 67, 85] # using join() print(''.join(str(n) for n in my_list))
null
Create a Python program to parse data from an XML web service.
<?xml version="1.0"?> <data> <customer> <name>John Smith</name> <email>john@example.com</email> </customer> <customer> <name>Jane Doe</name> <email>jane@example.com</email> </customer> </data>
import xml.etree.ElementTree as ET data = '''<?xml version="1.0"?> <data> <customer> <name>John Smith</name> <email>john@example.com</email> </customer> <customer> <name>Jane Doe</name> <email>jane@example.com</email> </customer> </data>''' root = ET.fromstring(data) for customer in root.findall('customer'):...
[HI Wikipedia] चौराई चौराई (Chorai) भारत के राजस्थान राज्य के उदयपुर ज़िले में स्थित एक गाँव है। यह समुद्र तल से 540 मीटर ऊपर पहाड़ी क्षेत्र में स्थित है। विवरण चौराई गाँव ऋषभदेव तहसील में है जो उदयपुर जिले में स्थित है चौराई गाँव के पास कल्याणपुर, भगोर, बिच्छिवाडा, मसारों की ओबरी स्थित है। इस गाँव के मध्य एक वराई मात...
null
null
null
null
Create a HTML form with two input fields called 'name' and 'age'.
<form> <label for="name">Name:</label> <input type="text" name="name" id="name"> <label for="age">Age:</label> <input type="number" name="age" id="age"> <input type="submit" value="Submit"> </form>
null
Determine the number of columns and rows in a given 2D array.
The given 2D array is [[1,2,3], [4,5,6]].
// Function to determine the // number of columns and rows in a 2D array void getSize(int matrix[2][3]) { int row = sizeof(matrix) / sizeof(matrix[0]); int column = sizeof(matrix[0]) / sizeof(matrix[0][0]); // Print the number of rows and columns cout << "The number of rows is : " << row << endl; cout << "The number of...
null
Generate a list of all possible combinations of the given set of numbers.
Set of numbers: [1,2,3]
[[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
[CS Wikipedia] Tíhové zrychlení Tíhové zrychlení je zrychlení volného pádu těles zanedbatelných rozměrů (hmotných bodů) v dané vztažné soustavě a představuje superpozici gravitačních a setrvačných zrychlení působících na tělesa v této soustavě. Nejčastěji se tíhovým zrychlením míní speciální případ zrychlení volného p...
null
null
null
null
Write a function to check if a string contains either 'a' or 'e' or 'i' or 'o' or 'u'.
def contains_vowel(string): vowels = ['a', 'e', 'i', 'o', 'u'] for char in string.lower(): if char in vowels: return True return False
[HI Wikipedia] मुसलमान मुसलमान (अरबी: مسلم، مسلمة फ़ारसी: مسلمان،, अंग्रेजी: Muslim) का मतलब वह व्यक्ति है जो इस्लाम में विश्वास रखता हो। हालाँकि मुसलमानों की आस्था के अनुसार इस्लाम ईश्वर का धर्म है और यह धर्म हज़रत मुहम्मद से पहले मौजूद था। जो लोग अल्लाह के धर्म का पालन करते रहे वह मुसलमान हैं। जैसे कुरान के अनुसार ह...
null
null
null
null
Develop a Python program to print the following pattern.
for i in range(1, 6): for j in range(5-i): print(" ", end="") for j in range(2*i-1): print("*", end="") print()
null
Analyze the following data in R and identify the mean, median and mode of the data.
[Data] [2, 3, 5, 6, 4, 1, 3, 6, 4]
The mean of the data is 3.77, the median is 4 and the mode is 3.
null
Find the area of the following circle
Radius: 8 cm
Area = pi * r^2 Area = 3.14 * 8^2 Area = 201.06 cm^2
null
Create a hashmap (a key-value pair data structure) in Python that stores two values, "name" and "age".
dict = { 'name': 'John', 'age': 30 }
[EN Wikipedia] Mansur ibn Jumhur al-Kalbi Mansur ibn Jumhur al-Kalbi () was an 8th-century Arab commander and one of the main and most fanatical leaders of the south Arab ("Yaman") tribes in the Qays–Yaman rivalry of the period, playing a major role during the Third Fitna civil war. Patricia Crone describes Mansur as ...
null
null
null
[CS Wikipedia] Běh na 3000 metrů Běh na 3000 metrů je atletická disciplína, patřící mezi střední tratě. Tato vzdálenost je pak považována za nejdelší střední trať. Je odvozena od 2 anglosaských mil, vzdálenosti rovné 3218,70 m. Patří mezi méně vypisované a běhané tratě, není součástí olympijských her ani atletických m...
null
null
null
null
Explain the following Python code
def fun(a,b): return a+b
The given code defines a function named 'fun' which accepts two arguments, 'a' and 'b'. The function returns the sum of 'a' and 'b'.
null
Implement a Python program for the 0/1 knapsack problem.
weights = [10, 30, 20] values = [30, 90, 60] capacity = 50
def knapsack_0_1(weights, values, capacity): n = len(values) matrix = [ [0]*(capacity+1) for _ in range(n+1) ] for i in range(1, n+1): for c in range(capacity+1): if weights[i-1] > c: matrix[i][c] = matrix[i-1][c] else: matrix[i][c] = max(...
null
Create a dictionary from two lists with the same length.
mylist1 = ["a", "b", "c", "d"] mylist2 = ["1", "2", "3", "4"]
mydict = dict(zip(mylist1, mylist2)) print(mydict)
null
Create an HTML page that displays "Hello World!" when opened in a web browser.
<html> <head> <title>Hello World!</title> </head> <body> <h1>Hello World!</h1> </body> </html>
null
Construct the code which will generate addition equations with randomized numbers ranging from 0 to 5.
import random def generate_addition_equation(): a = random.randrange(0, 6) b = random.randrange(0, 6) equation = str(a) + " + " + str(b) + " = " return equation
null
Rewrite the following code using the try-catch statement
if (num!=0) result = 1/num; else result = 0;
try { result = 1 / num; } catch (err) { result = 0; }
null
Create a python program to fetch data from the website http://example.com
import requests url = 'http://example.com' resp = requests.get(url) data = resp.json() print(data)
[HI Wikipedia] लाल गलियारा लाल गलियारा भारत के पूर्वी भाग का एक क्षेत्र है जहाँ नक्सलवादी (साम्यवाद) उग्रवादी संगठन सक्रीय हैं। आंध्र प्रदेश, छत्तीसगढ़, उड़ीसा, झारखंड, मध्य प्रदेश, पश्चिम बंगाल और उत्तर प्रदेश के कुछ भागों पर विस्तृत इस क्षेत्र में आधुनिक भारत के सबसे ऊँचे निरक्षरता, निर्धनता और अतिजनसंख्या के दर मिल...
null
null
null
null
Write a function to calculate the average score of a list of numbers.
def get_average(numbers): """ Calculate and return the average of a list of numbers :param numbers: the list of numbers :return: the average of the numbers """ total = 0 for number in numbers: total += number return total / len(numbers)
null
Create a function in Python that takes an integer input and prints all combinations of the numbers.
4
def permutations(n): for i in range(n+1): for j in range(n+1): for k in range(n+1): for l in range(n+1): print(i,j,k,l) # Calling the function permutations(4)
null
Create a Python script to count the frequencies of each letter in a given string.
text = "Hello, World!"
def count_letter_frequency(text): frequency = {} for letter in text: if letter in frequency: frequency[letter] += 1 else: frequency[letter] = 1 return frequency text = "Hello, World!" print(count_letter_frequency(text))
[DE Wikipedia] Vilablareix Vilablareix ist eine katalanische Gemeinde in der Provinz Girona im Nordosten Spaniens. Sie liegt in der Comarca Gironès. Einzelnachweise Weblinks Information der Generalitat de Catalunya zu Vilablareix Ort in Katalonien
null
null
null
null
Create a Python code for printing the following pattern.
# Pattern for i in range(1,6): for j in range(1,i+1): print(i,end="") print("")
null
Generate a correct Python program that implements a depth-first search algorithm.
def dfs(graph, node, visited): if node not in visited: visited.append(node) for n in graph[node]: dfs(graph, n, visited) return visited
null
Write a Python function to predict the sentiment of a given text.
text = ‘I love this film’
import nltk import numpy as np from nltk.sentiment.vader import SentimentIntensityAnalyzer def sentiment_score(text): """ Computes the sentiment score of a given text. """ sid = SentimentIntensityAnalyzer() scores = sid.polarity_scores(text) sentiment = np.argmax(list(scores.values())) return sen...
[HI Wikipedia] ऊष्मा इंजन जो इंजन ऊष्मा को यांत्रिक ऊर्जा में बदलते हैं उन्हें ऊष्मा इंजन (थर्मल इंजन) कहते हैं। ये इंजन ऊष्मा के उच्च ताप से निम्न ताप पर प्रवाहित होने के गुण का उपयोग करके बनाए जाते हैं। इसके विपरीत वे इंजन जो यांत्रिक ऊर्जा की सहायता से ऊष्मा को अधिक ताप से कम ताप पर ले जाते हैं उन्हें 'ऊष्मा पम्प' ...
null
null
null
null
Create a for loop in Python to iterate through a given list of numbers and find the sum.
[11, 12 , 15, 20, 56]
nums = [11, 12, 15, 20, 56] total = 0 for num in nums: total += num print(total) # 110
[HI Wikipedia] ईद उल-फ़ित्र ईद उल-फ़ित्र या ईद उल-फितर (अरबी: عيد الفطر) मुस्लमान रमज़ान उल-मुबारक के एक महीने के बाद एक मज़हबी ख़ुशी का त्यौहार मनाते हैं। जिसे ईद उल-फ़ित्र कहा जाता है। ये यक्म शवाल अल-मुकर्रम्म को मनाया जाता है। ईद उल-फ़ित्र इस्लामी कैलेण्डर के दसवें महीने शव्वाल के पहले दिन मनाया जाता है। इसलामी कै...
null
null
null
[CS Wikipedia] Odstředivá síla Odstředivá síla (nebo také centrifugální) je síla působící na těleso resp. hmotný bod směrem od středu křivosti trajektorie. V případě pohybu po kružnici jde o střed této kružnice. V obecnějším případě pohybu po hladké křivce jde o střed oskulační kružnice. Existují dva odlišné typy sil,...
null
null
null
null
Generate an artificial neural network algorithm in Python for classification.
import numpy as np from keras.models import Sequential from keras.layers import Dense # Generate data X, y = np.random.rand(1000, 10), np.random.randint(2, size = (1000, 1)) # Define model model = Sequential() model.add(Dense(64, input_dim=10, activation='relu')) model.add(Dense(64, activation='relu')) model.add(Dens...
null
What is the maximum value of a byte in a binary system?
The maximum value of a byte in a binary system is 255. This is because there are 8 bits in a byte, and the maximum value each bit can have is 1, giving a maximum value of 8 ones, or 255 in the denary system.
null
Create a Python list in which each element is a dictionary containing customer data.
[ { 'name': 'John', 'age': 21 }, { 'name': 'Minh', 'age': 24 }, { 'name': 'Linda', 'age': 18 } ]
customers = [ { 'name': 'John', 'age': 21 }, { 'name': 'Minh', 'age': 24 }, { 'name': 'Linda', 'age': 18 } ]
null
How to find the minimum number in an array of integers in Java?
We can find the minimum number in an array of integers in Java using the Arrays.stream() method. The Arrays.stream() method takes an array and returns a stream of its elements. We can then use the Stream.min() function to find the minimum element in the array. Example: int[] arr = {2, 4, 6, 8, 10}; int min = Arrays.str...
null
Create a command line tool in Python that takes a numerical input (e.g. from user input) and prints out all prime numbers up to that number.
50
import sys def main(): try: number = int(sys.argv[1]) except (IndexError, ValueError): number = int(input('Please enter a number: ')) prime_list = [] for num in range(2, number + 1): for i in prime_list: if num % i == 0: break else: prime_list.append(num) print(prime_list) if __name__ == '__main__': mai...
null
Using HTML, write a code to display a table with two columns and three rows.
<table> <tr> <th>Column 1</th> <th>Column 2</th> </tr> <tr> <td>Row 1</td> <td>Row 1</td> </tr> <tr> <td>Row 2</td> <td>Row 2</td> </tr> <tr> <td>Row 3</td> <td>Row 3</td> </tr> </table>
null
Design a function 'sortString' which takes a string of words and sorts each word alphabetically.
string = "zebra cat dog"
def sortString(string): words = string.split(" ") sortedWords = [word for word in words] for i in range(len(sortedWords)): sortedWords[i] = "".join(sorted(sortedWords[i])) return " ".join(sortedWords) print(sortString("zebra cat dog")) OUTPUT: abcerz cdgot
[EN Wikipedia] Trichostegia (caddisfly) Trichostegia is a genus of insects belonging to the family Phryganeidae. The species of this genus are found in Europe and Northern America. Species: Trichostegia minor (Curtis, 1834) References Phryganeidae Trichoptera genera
null
null
null
null
How to write a CSS style to make a text larger?
.className { font-size: larger; }
null
Create a class in Python for creating a currency converter that can convert between any currencies.
Not applicable
import requests class CurrencyConverter: def __init__(self, source_currency, target_currency, amount): self.source_currency = source_currency self.target_currency = target_currency self.amount = amount def convert(self): """ This method returns the converted amount ...
null
Design a Python program that accepts an integer greater than 1 as input and prints out all prime numbers up to the given number.
Number = 10
def is_prime(num): prime = True if num <= 1: prime = False else: for i in range(2, num): if num % i == 0: prime = False return prime def main(): num = 10 print("All prime numbers up to", num, "are:") for i in range(2, num+1): if is_prime(...
null
Generate a short HTML div element.
<div></div>
null
Create a JavaScript array and add the following items: "dog", "cat", "mouse", "bird".
let animals = ["dog", "cat", "mouse", "bird"];
null
Write a code to generate all possible binary strings of length 5.
def gen_binary_strings(n): result = [] for i in range(2**n): s = bin(i)[2:] s = s.zfill(n) result.append(s) return result print(gen_binary_strings(5)) # Output: ['00000', '00001', '00010', '00011', '00100', '00101', '00110', '00111', '01000', '01001', '01010', '01011', '01100', '01101', '01110', '01111', '10000', '1000...
null
Create a C# program to sort a given array of integers.
int[] nums = {8, 5, 1, 3, 9};
int[] sorted = nums.OrderBy(n => n).ToArray();
null
Create a function in Python to apply a discount rate to a given price. This should accept two parameters, a float for the discount rate between 0 and 1 and the price. The function should return the discounted price.
discountRate = 0.9 price = 200
def applyDiscount(discountRate, price): discountedPrice = discountRate * price return discountedPrice print(applyDiscount(discountRate, price)) # 180
null
Suggest a function name for a function that reverses a string.
function reverseString(str) {...} or function reverseWord(str) {...}
null
Write a MySQL query to find all records whose name starts with 'A'.
SELECT * FROM tableName WHERE name LIKE 'A%';
null
Create a regular expression that matches the email address with the domain gmail.com
\S+@gmail\.com$
null
How do you retrieve the 3rd element of a set in Python?
In Python, you can retrieve the 3rd element of a set by using the index operator []. The 3rd element of a set can be accessed by using the syntax set[2]. Note that the indexing in Python starts from 0, so the 3rd element will have index 2.
[HI Wikipedia] इंडोनेशिया {{ज्ञानसन्दूक देश |native_name = इंडोनेशिया गणराज्य का एकात्मक राज्य |conventional_long_name = Negara Kesatuan Republik Indonesia |common_name = Indonesia |image_flag = Flag of Indonesia.svg |image_coat = National emblem of Indonesia Garuda Pancasila.svg |image_map = LocationIndonesia.svg |na...
null
null
null
[CS Wikipedia] Jean-Éric Vergne Jean-Éric Vergne (* 25. dubna 1990 v Pontoise, Francie) je francouzský automobilový závodník, pilot Formule E a bývalý pilot Formule 1. Momentálně jezdí v šampionátu Formule E za tým DS Techeetah. Kompletní výsledky Formule 1 Formule E Externí odkazy Francouzští automobiloví závodníci F...
null
null
null
null
Construct a loop to print all the numbers divisible by 3 between 1 and 20
for num in range(1, 21): if num % 3 == 0: print(num)
null
Change the following Python code to a generator.
def fibonacci(n): if n < 0: return; result = [] prev = 0 current = 1 result.append(prev) result.append(current) while(n - 2): temp = current current += prev prev = temp result.append(current) n = n - 1 return result
def fibonacci(n): prev, current = 0, 1 while(n): yield prev prev, current = current, prev + current n = n - 1 # Driver Code result = list(fibonacci(10)) print(result) # prints [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
null
Write a function in Python that takes an array of integers as an input and returns an array with only the distinct numbers from the input.
[1, 2, 3, 4, 4, 5, 5]
def distinct_numbers(arr): return list(set(arr))
null
Replace the following if-else statement with a ternary operator.
if n > 0: x = n * 10 else: x = n * 5
x = n * 10 if n > 0 else n * 5
[CS Wikipedia] Helen Binaová Helen Binaová (19. května 1912 – 15. března 1983) byla americká rychlobruslařka. Startovala v ukázkových ženských závodech na Zimních olympijských hrách 1932. Na distanci 500 m se umístila na šesté příčce, na trati 1000 m byla vyřazena v rozjížďkách a v závodě na 1500 m skončila na třetím ...
null
null
null
null
For the following list, print out the second element.
list = ["apple", "banana", "cherry"]
second_element = list[1] print(second_element) # prints banana
[HI Wikipedia] लातविया लातविया या लातविया गणराज्य (लातवियाई : Latvijas Republika) उत्तरपूर्वी यूरोप में स्थित एक देश है और उन तीन बाल्टिक गणराज्यों में से एक है जिनका द्वितीय विश्व युद्ध के बाद भूतपूर्व सोवियत संघ में विलय कर दिया गया। इसकी सीमाएं लिथुआनिया, एस्टोनिया, बेलारूस और रूस से मिलती हैं। यह आकार की दृष्टि से...
null
null
null
null
Write a python script to segregate a list of numbers into lists odd and even numbers.
list_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_numbers = [] even_numbers = [] for number in list_of_numbers: if number % 2 == 0: even_numbers.append(number) else: odd_numbers.append(number) print("Odd numbers: " + str(odd_numbers)) print("Even numbers: " + str(even_numbers))
null
Create a program to generate all possible pairs of a given list of numbers
[1, 2, 3]
""" Create a program to generate all possible pairs of a given list of numbers """ def generate_pairs(nums): pairs = [] for i in range(len(nums)): for j in range(i+1, len(nums)): pairs.append((nums[i], nums[j])) return pairs if __name__ == '__main__': print(generate_pairs([1, 2, 3]))
null
Parse a list of numbers from a string in Python.
s = "1, 2, 3, 4, 5, 6"
import re list = re.findall(r'\d+', s)
null
Write an algorithm in Python which reads a string and reorders it alphabetically.
string s = 'dcba'
def reorder_string(s): s = sorted(s) return ''.join(s) print(reorder_string('dcba'))
[DE Wikipedia] Hartmannstraße 28 (Bad Kissingen) Das Anwesen Hartmannstraße 28 in der Hartmannstraße in Bad Kissingen, der Großen Kreisstadt des unterfränkischen Landkreises Bad Kissingen, gehört zu den Bad Kissinger Baudenkmälern und ist unter der Nummer D-6-72-114-299 in der Bayerischen Denkmalliste registriert. Ges...
null
null
null