text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Create a for loop for printing out the elements in a given list in reverse order.
my_list = [1,2,3,4]
for i in range(len(my_list)-1, -1, -1): print(my_list[i])
null
Suggest an additional function needed to complete the following programme.
class Node: def __init__(self, data): self.data = data self.next = None
class Node: def __init__(self, data): self.data = data self.next = None def getData(self): return self.data
null
Refactor a Python program to concatenate two strings without using the string.concat() function
// Python program str1 = "Hello " str2 = "World" result = str1.concat(str2) print("Concatenated string: ", result)
str1 = "Hello " str2 = "World" result = str1 + str2 print("Concatenated string: ", result)
null
Given a string, develop a function to find out how many words are present in it.
string = 'Hello world!'
def countWords(string): return len(string.split())
null
Build a Python program to detect credit card fraud. The program should ingest a batch of transactions, analyze the data, and output the predicted probability of each transaction being fraudulent.
Not applicable
import pandas as pd from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier # Create a dataframe of the transactions transactions = pd.DataFrame({ 'amount': [3.23, 5.41, 2.34, 8.45, 10.67, 16.23, 7.68, 18.9], 'from_ac...
null
Generate Python code to find the compound interest for a given principal amount, rate, and time period.
# Python program to find compound interest def compound_interest(p,r,t): # p is the principal amount # r is the rate # t is the time period # Calculating compound interest CI = p * (pow((1 + r / 100), t)) print("Compound interest is", CI) p=1000 r=10 t=2 compound_interest(p,r,t)
null
Create a Python program that generates a histogram from a list of integers.
import matplotlib.pyplot as plt def plot_histogram(data): plt.hist(data) plt.title("Histogram") plt.xlabel("Values") plt.ylabel("Frequency") plt.show() if __name__ == "__main__": data = [1, 2, 5, 7, 9, 4, 5, 9, 10, 12] plot_histogram(data)
[DE Wikipedia] Felberbach (Mur) Der Felberbach ist ein gut 4,5 Kilometer langer Bach im Gebiet der Marktgemeinde Gratkorn im Bezirk Graz-Umgebung in der Steiermark. Er entspringt in einem südöstlichen Ausläufer des östlichen Grazer Berglandes, durchfließt den östlichen Teil des Gratkorner Becken sowie das Ortsgebiet v...
null
null
null
null
Write a Python program to find the maximum sum of a contiguous subarray in a given array of integers.
[-2,1,-3,4,-1,2,1,-5,4].
def max_sum_contiguous_subarray(arr): max_sum = 0 curr_sum = 0 for i in range(len(arr)): curr_sum = max(curr_sum + arr[i], arr[i]) max_sum = max(max_sum, curr_sum) return max_sum
null
Design a Python Program to calculate the harmonic mean of two numbers, given their product and sum.
product = 12 summation = 8
def harmonic_mean(product, summation): # calculate denominator by subtracting sum from product denominator = product - summation # calculate harmonic mean by dividing sum by denominator harmonic_mean = summation/denominator return harmonic_mean
null
Write a Python program to identify numbers from a comma-separated string.
mystring = "1,2,3,4,5,6,7,8,9"
mystring = "1,2,3,4,5,6,7,8,9" numbers = mystring.split(",") for num in numbers: print(int(num))
null
Create a function that sorts a dictionary of words and their frequencies alphabetically.
dict = { 'the': 10, 'at': 3, 'hello': 5, 'cat': 1, 'counter': 2 }
""" Create a function that sorts a dictionary of words and their frequencies alphabetically. """ def sort_dictionary(dictionary): return dict(sorted(dictionary.items(), key=lambda x: x[0])) if __name__ == "__main__": dict = { 'the': 10, 'at': 3, 'hello': 5, 'cat': 1, 'counter': 2 } print(sort_dictionary(dict))
null
Generate Python code to get the maximum element in a list.
List of integers [7, 2, 3, 6, 5]
list = [7, 2, 3, 6, 5] print("Max element is:", max(list))
null
Write a python function to search a list of numbers for a given number and output the position if found.
numbers=[1,2,3,4,5], search=3
def search_list(numbers, search): for index, num in enumerate(numbers): if num == search: return index return -1
null
Create a function in JavaScript that takes in two arrays and returns an object. The object should contain elements where the two arrays have coinciding elements.
[1,3,5], [2,4,1]
function findCommon(arr1, arr2) { let result = {}; for (let i = 0; i < arr1.length; i++) { for (let j = 0; j< arr2.length; j++) { if(arr1[i] === arr2[j]) { result[arr1[i]] = arr2[j]; } } } return result; } console.log(findCommon([1,3,5], [2,4,1])); // Output: {1: 1}
null
Write a Python 3 script to print out all the words in the string 'I love coding'.
words = "I love coding" for word in words.split(): print(word)
null
Compare two strings and return the index of the first character that is unequal in the two strings.
string1 = "Hello world!" string2 = "Howdy world!"
def get_index_of_first_diff(string1, string2): # Get the length of the strings len_1 = len(string1) len_2 = len(string2) # Get the length of the shorter string len_shorter = min(len_1, len_2) # Compare the two strings character by character for i in range(len_shorter): if string1[i] != string2[i]: # Return the index of...
null
Create a script to convert a number in scientific notation into a float
Number: 6.02e23
x = float(6.02e23) print(x) # 6.02E+23
null
Create a class for a basketball team.
class BasketballTeam: def __init__(self, name, players): self.name = name self.players = players def get_name(self): return self.name def get_players(self): return self.players def add_player(self, player): self.players.append(player) return self.players
null
Design a JavaScript class to instantiate objects for student records.
The student records should store the student name, age, and score of the last test.
class Student { constructor(name, age, lastScore) { this.name = name; this.age = age; this.lastScore = lastScore; } }
null
Using HTML, create a simple table showing a list of countries and their population.
<table> <tr> <th>Country</th> <th>Population</th> </tr> <tr> <td>United States</td> <td>328.2 million</td> </tr> <tr> <td>China</td> <td>1.44 billion</td> </tr> <tr> <td>India</td> <td>1.39 billion</td> </tr> <tr> <td>Indonesia</td> <td>269.9 million</td> </tr> </table>
null
Can you design an algorithm in Python to find the longest palindrome in a given string?
def longest_palindrome(s): n = len(s) T = [[False for i in range(n)] for i in range(n)] maxLength = 0 # Find palindromes of single characters for i in range(n): T[i][i] = True # Find palindromes of double characters for i in range(n-1): if s[i] == s[i+1]: T[i][i+1] =...
[EN Wikipedia] Shams al-Din 'Ali ibn Mas'ud Shams al-Din 'Ali ibn Mas'ud ibn Khalaf ibn Mihraban (died March/April 1255) was the first Mihrabanid Malik of Sistan. He ruled from 1236 until his death. Biography Shams al-Din likely came from one of the eminent families of Sistan. In mid-1236 he was hailed as malik by the...
null
null
null
null
Given a list of valid times, return the duration in seconds between two times.
time1 = "23:45:17" time2 = "01:30:12"
def calculate_duration_in_seconds(time1, time2): start = datetime.strptime(time1, "%H:%M:%S") end = datetime.strptime(time2, "%H:%M:%S") duration = end-start return int(duration.total_seconds())
null
Edit the given Python program to use for loop instead of while loop.
i = 0 while i < 10: print(i) i = i + 1
for i in range(10): print(i)
null
Create a function in Python to convert integer inputs to their binary representation.
def int_to_binary(n): """ Returns the binary representation of an integer. """ return "{0:b}".format(n)
null
Generate a function to check for palindrome strings in Python.
def check_palindrome(string): reversed_string = string[::-1] if string == reversed_string: return True else: return False
null
Generate a Python class that overides the default methods of a list.
class MyList(list): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def append(self, element): super().append(element) print('Element {} is added to the list'.format(element)) def insert(self, index, element): super().insert(index, element) pr...
null
Write a Python function that the user can call to pseudorandomly shuffle a given list
import random def shuffle_list(lst): if len(lst) > 1: random.shuffle(lst) return lst
[CS Wikipedia] Mike Stock Mike Stock (* 3. prosince 1951 Margate, Kent, Velká Británie) je anglický skladatel a producent. Je znám díky působení v triu Stock, Aitken & Waterman. Pomáhal napsat či ko-produkovat nespočetné množství celosvětových hitů, včetně šestnácti #1 nahrávek ve Velké Británii V roce 2003 založil no...
null
null
null
[DE Wikipedia] Westermalms IF Westermalms IF ist ein schwedischer Fußballverein aus Kungsholmen, dem Zentrum Stockholms. Der Verein ist vor allem für seine Fußballmannschaft bekannt, die in den Anfängen des schwedischen Fußballs zu den bedeutendsten Mannschaften gehörte und Ende der 1920er Jahre zwei Spielzeiten in de...
null
null
null
[CS Wikipedia] Integrovaný dopravní systém Pardubického kraje Integrovaný dopravní systém Pardubického kraje (IDS Pk) fungoval od 1. února 2008 do 10. prosince 2011 v Pardubickém kraji na území okresů Pardubice a Chrudim Okres Pardubice byl zaintegrován k 1. únoru 2008 a okres Chrudim k 14. prosinci 2008. Cílem integr...
null
null
null
null
Create a Java program to multiply two given matrices
public class MatrixMultiplication { // Method to multiply two matrices public static double[][] multiply(double[][] A, double[][] B) { int aRows = A.length; int aColumns = A[0].length; int bRows = B.length; int bColumns = B[0].length; if (aColumns != bRows) { throw new IllegalArgumentException("A:Rows: " + aColumns + "...
null
Write a Python program to predict the probability of an employee leaving the company given their age.
def predict_probability(age): # Fit your model and get predicted probabilities probabilities = model.predict_proba(age) # Return probability for leaving class return probabilities[0][1]
null
Erkläre kurz, was eine Variable in der Programmierung ist.
Eine Variable ist ein benannter Speicherplatz, der einen Wert hält, der sich während der Programmausführung ändern kann.
null
Modify the given code so it prints a prime number table.
table_size = 10
# Include the necessary library from prime_generator import get_prime # Get a list of prime numbers primes = get_prime(table_size) # Print the prime number table print(" Prime Number Table") print(" --------------------") for i in range(table_size): print(f"{primes[i]:>4} {(i+1)*primes[i]:>4}")
null
Find the 5 most frequent words in the given text.
Text: Python is a high-level programming language.
from collections import Counter text = " Python is a high-level programming language." words = text.split() frequencies = Counter(words) # printing five most frequent words frequent_words = frequencies.most_common(5) print(frequent_words)
null
Create a function that takes in a string and returns a dictionary with each word as a key and its count as the value.
string = "This is a test string"
def word_count_dict(string): word_list = string.split() word_dict = {} for word in word_list: if word in word_dict: word_dict[word] += 1 else: word_dict[word] = 1 return word_dict string = "This is a test string" print(word_count_dict(string))
null
Generate a random hexadecimal string with a length of 8 characters.
import random def generate_hex(): hex_values = '0123456789ABCDEF' string_length = 8 hex_string = '' for _ in range(string_length): hex_character = random.choice(hex_values) hex_string += hex_character return hex_string if __name__ == '__main__': print(generate_hex())
null
Create a Flask API endpoint in Python that accepts an array of numbers and returns the average of the numbers
Not applicable
from flask import Flask, request, jsonify app = Flask(name) @app.route('/calculate_average', methods=['POST']) def calculate_average(): numbers = request.json['numbers'] # calculate the sum total = 0 for number in numbers: total += number # calculate the average average = total / len(numbers) return jsonif...
null
Edit the following code so that it prints an appropriate error message.
def divide(num1, num2): result = num1 // num2 return result
def divide(num1, num2): if num2 == 0: print('Error: Invalid operation. num2 cannot be zero.') else: result = num1 // num2 return result
null
How can you generate a random array of 10 integers between 1 and 100?
import random def generate_random_array(): array = [] for i in range(10): array.append(random.randint(1,100)) return array
null
Implement a stack class in Python.
class Stack: def __init__(self): self.stack = [] def push(self, x): self.stack.append(x) def pop(self): if self.stack == []: raise IndexError("pop from an empty stack") else: return self.stack.pop() def is_empty(self): return self.sta...
null
Generate a Python program to produce a poem given a few keywords as input
sky, moon, stars
def create_poem(keywords): poem = "The night sky is so beautiful \nFill with stars, moon and " + keywords[0] + ".\nNo matter how dark it is now,\nHope will come if we look above." poem += "\n\nThe " + keywords[0] + " will shining its light,\nBring calm and peace in the night.\nAlong with the stars, and the " + ...
[EN Wikipedia] Gmina Belsk Duży Gmina Belsk Duży is a rural gmina (administrative district) in Grójec County, Masovian Voivodeship, in east-central Poland. Its seat is the village of Belsk Duży, which lies approximately south-west of Grójec and south of Warsaw. The gmina covers an area of , and as of 2006 its total po...
null
null
null
null
Edit the following code to print out all even numbers from 1 to 10.
for i in range(1,11): print(i)
for i in range(1,11): if i % 2 == 0: print(i)
[CS Wikipedia] Cyril a Metoděj – Apoštolové Slovanů Cyril a Metoděj – Apoštolové Slovanů je dokumentární drama o příchodu věrozvěstů Cyrila a Metoděje na Velkou Moravu natočený u příležitosti 1150. výročí počátku šíření křesťanství slovanským jazykem ve slovanských zemích. Dobrodružně naučné výpravné televizní dokumen...
null
null
null
null
Write a class in Python that encodes a DataFrame object.
class DataFrameEncoder: def __init__(self, data): self.data = data def encode(self): encoded = [] for row in self.data: encoded_row = [] for column in row: encoded_column = str(column) encoded_row.append(encoded_column) ...
null
Create an algorithm and its corresponding code implementation in Python that counts the number of words in a string.
This is a sentence
def word_count(string): words = string.split() return len(words) print(word_count("This is a sentence"))
null
Redesign the following Python program with functions.
my_list = [5, 10, 15, 20] sum = 0 for number in my_list: sum = sum + number
def sum_of_list(my_list): sum = 0 for number in my_list: sum = sum + number return sum my_list = [5, 10, 15, 20] result = sum_of_list(my_list)
null
Write a Python function that takes a list of n strings and a number k and returns the longest string with length of k or less.
def find_longest_at_length(lst, k): longest_str = lst[0] for s in lst[1:]: if len(s) <= k and len(s) > len(longest_str): longest_str = s return longest_str
null
Write a Python function to find the maximum profit when given a list of stock prices per day.
stock_prices = [7, 1, 5, 3, 6, 4]
def max_profit(stock_prices): max_profit = 0 for i in range(len(stock_prices) - 1): for j in range(i + 1, len(stock_prices)): if stock_prices[j] - stock_prices[i] > max_profit: max_profit = stock_prices[j] - stock_prices[i] return max_profit if __name__ == "__main__": ...
[HI Wikipedia] शीराज़ा डोगरी शीराज़ा डोगरी एक द्विमासिक साहित्यिक पत्रिका है जो डोगरी भाषा में जम्मू व कश्मीर में छपती है। इसे जम्मू व कश्मीर कला, संस्कृति व भाषा अकादेमी प्रकाशित करती है। इसे १९६४ में एक छहमासिक पत्रिका (यानि वर्ष में दो बार) के रूप में शुरू किया गया था लेकिन १९७० में इसकी प्रकाशन-गति बढ़ाकर त्रिमासि...
null
null
null
null
Develop a machine learning model in Python using support vector machines (SVM) to detect sentiment in movie reviews.
Not applicable
import numpy as np import pandas as pd from sklearn.svm import SVC # Read the data data = pd.read_csv('data.csv') # Split into train and test data X_train = data.iloc[:1000, :].review y_train = data.iloc[:1000, :].sentiment X_test = data.iloc[1000:, :].review y_test = data.iloc[1000:, :].sentiment # Vectorize the te...
null
Create a HTML form that takes 3 inputs: first name, last name, and age.
<form> <label>First Name:</label> <input type="text" name="firstname" /><br> <label>Last Name:</label> <input type="text" name="lastname" /><br> <label>Age:</label> <input type="text" name="age" /><br> <input type="submit" value="Submit" /> </form>
null
Create a class in Python to represent a circle in a Euclidean plane.
class Circle: def __init__(self, radius, x=0, y=0): self.x = x self.y = y self.radius = radius def area(self): return (self.radius ** 2) * math.pi def circumference(self): return 2 * math.pi * self.radius def __str__(self): return f'Circle at ({self.x}...
[HI Wikipedia] चेतेश्वर पुजारा चेतेश्वर अरविंद पुजारा (जन्म : २५ जनवरी १९८८, राजकोट, गुजरात) एक भारतीय टेस्ट क्रिकेट खिलाड़ी हैं। पुजारा एक दाँये हाथ के बल्लेबाज हैं, जो घरेलू क्रिकेट में सौराष्ट्र और इंडियन प्रीमियर लीग में रॉयल चैलेंजर्स बैंगलुरू की ओर से खेलते हैं। टेस्ट क्रिकेट में पुजारा ने ऑस्ट्रेलिया के ख़िलाफ़...
null
null
null
null
Generate a python program that implements the insertion sort algorithm.
Not applicable
def insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key # Driver code to test above arr = [12, 11, 13, 5, 6] inserti...
null
Write the SQL query to select the last element of a table
table_name: users
SELECT * FROM users ORDER BY id DESC LIMIT 1;
null
Reverse the following string without using in-built functions in Python.
Hello World
dlroW olleH
[DE Wikipedia] Marge Dodson Marge Dodson (* um 1935) ist eine US-amerikanische Pop- und Jazzsängerin. Leben und Wirken Dodson spielte 1959 für Columbia Records ihr Debütalbum In the Still of the Night ein, begleitet von Mike Colicchio (Piano); die Arrangements stammten u. a. von Coleridge Parkinson. Darauf interpretie...
null
null
null
null
Write a code to extract the odd numbers from a given array in JavaScript.
[1, 2, 3, 4, 5, 6, 7, 8, 9]
function oddNumbers(arr) { let oddNumbers = arr.filter(function(element) { return element % 2 !== 0; }); return oddNumbers; }
[CS Wikipedia] Mezinárodní policejní asociace Mezinárodní policejní asociace, anglicky International Police Association (IPA), je největší světová organizace sdružující policisty jako jednotlivce. Založil ji 1. ledna 1950 britský seržant Arthur Troop (1914–2000) s cílem vytvořit přátelské vztahy a podpořit spolupráci ...
null
null
null
null
Generate a Python program to generate multiplication table of a given number.
5
def multiplication_table(num): for i in range(1, 11): print(num, 'x', i, '=', num*i) num = int(input("Enter a number: ")) multiplication_table(num)
null
Write a Java program to accept two integers and find the sum of the two numbers.
import java.util.Scanner; public class SumIntegers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter two integers: "); int first = scanner.nextInt(); int second = scanner.nextInt(); int sum = first + second; System.out.println("The sum of the two numbers is: ...
null
Compute the maximum and minimum number from the following list.
my_list = [2, 4, 5, 7, 9]
my_list = [2, 4, 5, 7, 9] # Program to compute maximum and minimum number max_num = max(my_list) min_num = min(my_list) print(f"The maximum number from the list is {max_num} and the minimum number is {min_num}.")
null
Write a Python script to pad a matrix to a given size.
matrix = [[1, 2], [3, 4], [5, 6]] pad_size = 3
def pad_matrix(matrix, pad_size): rows = len(matrix) cols = len(matrix[0]) new_matrix = [[0 for j in range(pad_size)] for i in range(pad_size)] for i in range(rows): for j in range(cols): new_matrix[i][j] = matrix[i][j] return new_matrix print(pad_matrix(matrix, pad_size...
[CS Wikipedia] Fletschhorn Fletschhorn je hora ve Walliských Alpách ve Švýcarsku. Nachází se ve skupině Weissmiesgruppe na území okresu Visp (kanton Valais) nad vesnicí Saas-Balen asi 16,5 km jižně od města Brig. Leží v hřebeni mezi údolími Saastal a Simplontal, kde na severozápadě sousedí s vrcholem Senggchuppa (3607...
null
null
null
null
Parse the following HTML string and return the list of id's.
<form> <input name="user_id" type="text" id="user_id" value="123456"> <input name="name" type="text" id="name" value="John Doe"> <input name="email" type="text" id="email" value="john@example.com"> <input name="password" type="password" id="password" value="password123"> </form>
import lxml.html input_html = ''' <form> <input name="user_id" type="text" id="user_id" value="123456"> <input name="name" type="text" id="name" value="John Doe"> <input name="email" type="text" id="email" value="john@example.com"> <input name="password" type="password" id="password" value="password123"> </form> ''' de...
[EN Wikipedia] Nella Walker Nella Walker (March 6, 1886 – March 22, 1971) was an American actress and vaudeville performer of the 1920s through the 1950s. Biography The daughter of Mr. and Mrs. Charles Walker, she was born and raised in Chicago. In 1910, she married Wilbur Mack. In 1912, they formed the vaudeville tea...
null
null
null
[DE Wikipedia] Bamberg Baskets Die Bamberg Baskets sind eine deutsche Basketballmannschaft aus Bamberg, die neunmal die Deutsche Meisterschaft und sechsmal den Deutschen Pokal gewann. Bamberg tritt in der Basketball-Bundesliga an. Lizenzinhaber ist die Bamberger Basketball GmbH. Geschichte Basketballanfänge in Bamberg...
null
null
null
null
Analyze the following data and build a linear regression model in Python.
x = [1, 2, 3, 4, 5, 6, 7] y = [2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]
import numpy as np x = np.array([1,2,3,4,5,6,7]) y = np.array([2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]) m = ((np.mean(x)*np.mean(y)) - np.mean(x*y))/((np.mean(x)**2) - np.mean(x**2)) c = np.mean(y) - (m*np.mean(x)) print("slope =", m) print("intercept =", c)
null
Create an algorithm that sorts a given list of numbers.
[1, 5, -3, 0, 8]
def bubble_sort(list): for i in range(len(list)): for j in range(len(list)-1-i): if list[j] > list[j+1]: list[j], list[j+1] = list[j+1], list[j] return list bubble_sort([1,5,-3,0,8])
null
Develop a Chatbot that can respond to the user's queries about programming languages.
def chatbot(): while True: # User's query query = input("What would you like to know about programming languages? ") # Checking if query is relevant if "language" in query: # Provide response print("There are many different programming languages, and these can range from low-level languages such as assembly, to high-le...
null
Create a class in Java that comprises of a date, a location and temperature reading associated with that location on that particular date.
public class TemperatureReading { private Date date; private String location; private int temperature; public TemperatureReading(Date date, String location, int temperature) { this.date = date; this.location = location; this.temperature = temperature; } public Date getDate() { return date; } public String getLocation()...
null
Write a JavaScript function to safe an array at the local storage.
[10, 20, 30]
function saveArrayToLocalStorage(arr) { localStorage.setItem('array', JSON.stringify(arr)); }
null
Debug a Java program to correct a compile-time error.
public class Debug { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Hello"); list.add("World"); } System.out.println(list); }
public class Debug { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Hello"); list.add("World"); for(String str : list){ System.out.println(str); } } }
[EN Wikipedia] Christy Clark (Montana politician) Christy Clark (born March 1, 1966) was a Republican member of the Montana Legislature. She served as vice-chair of the Montana Republican Party. She was elected to House District 17 which represents Teton County, Augusta, and part of Lincoln. References External links ...
null
null
null
[DE Wikipedia] Beerten Beerten ist der Familienname folgender Personen: Anneke Beerten (* 1982), niederländische Mountainbikerin Els Beerten (* 1959), flämische Kinder- und Jugendbuchautorin
null
null
null
null
Develop a Python function that can detect loops in a given linked list.
Linked List: head -> 1 -> 2 -> 3 -> 4 -> 5
def detectLoop(head): slow_p = head fast_p = head while(slow_p and fast_p and fast_p.next): slow_p = slow_p.next fast_p = fast_p.next.next if slow_p == fast_p: return True return False
null
What is the Python equivalent of the C++ code snippet?
#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; }
print("Hello, World!")
[DE Wikipedia] Wassili Wassiljewitsch Kapnist Wassili Wassiljewitsch Kapnist (; * in Welikaja Obuchowka, Regiment Mirgorod bei Poltawa, Hetmanat, Russisches Reich; † Kibinzy, Gouvernement Poltawa, Russisches Reich) war ein russischer Dichter und Dramaturg; Adelsmarschall des Gouvernements Poltawa. Die im 19. Jahrhunde...
null
null
null
[EN Wikipedia] Minister for Housing (Australia) The Minister for Housing is an Australian Government cabinet position which is currently held by Julie Collins following the swearing in of the full Albanese ministry on 1 June 2022. In the Government of Australia, the minister administers this portfolio through the Depa...
null
null
null
null
Write a function in Python to get the IPv6 address of a given domain name.
import socket def get_IPv6_address(domain_name): """ Function to get the IPv6 address of a given domain name """ # get the ip_addres ip_address = socket.getaddrinfo(domain_name, 0, socket.AF_INET6) # return the ip address return ip_address[0][4][0]
null
Write a function in Python that takes a list of integers as an argument and calculates the mean average.
def calculate_mean(numbers): total_sum = 0; for num in numbers: total_sum += num mean_average = total_sum / len(numbers) return mean_average
null
Write a Python program to categorize a given set of movie ratings.
[9, 6, 7, 5, 4, 8]
def movie_rating_categorizer(ratings): categorized_ratings = [] for rating in ratings: if rating > 8: categorized_ratings.append("Excellent") elif rating > 6: categorized_ratings.append("Good") elif rating > 4: categorized_ratings.append("Average") ...
null
Design a Python class to represent a Triangle and its properties, such as area, perimeter, and angles.
class Triangle: def __init__(self, side_a, side_b, side_c): self.side_a = side_a self.side_b = side_b self.side_c = side_c def get_area(self): s = (self.side_a+self.side_b+self.side_c)/2 return (s*(s-self.side_a)*(s-self.side_b)*(s-self.side_c)) ** 0.5 def get_perimeter(self): return self.side_a + self.side_b + self.si...
null
Using a for-in loop, print out the keys and values of a given dictionary.
mydict = { "name": "John", "age": 30, "city": "New York" }
for key,value in mydict.items(): print("Key: " + key + "; Value: " + str(value)) # Output: # Key: name; Value: John # Key: age; Value: 30 # Key: city; Value: New York
[CS Wikipedia] Vetřelec (Hvězdná brána: Atlantida) Vetřelec (v anglickém originále The Intruder) je druhý díl druhé řady sci-fi seriálu Hvězdná brána: Atlantida. Obsah epizody Daidalos se vrací na Atlantidu. Posádku (mezi níž je Weirová, Sheppard, McKay i Beckett) čeká osmnáctidenní cesta. Během ní se každý snaží vyro...
null
null
null
null
Create a content aggregator application in Python.
import requests import json def content_aggregator(): api_url = "https://www.example.com/api/" response = requests.get(api_url) response_data = json.loads(response.text) for item in response_data: print(item) if __name__ == '__main__': content_aggregator()
null
Create a list in Python to store the first 10 numbers that are divisible by 4.
divisible_by_four = [i for i in range(1,11) if i%4 == 0]
null
Write a Java method to calculate the total marks of a student given their marks of 5 subjects.
int marks_sub1 = 80; int marks_sub2 = 90; int marks_sub3 = 85; int marks_sub4 = 92; int marks_sub5 = 87;
public static int calculateTotalMarks(int marks_sub1, int marks_sub2, int marks_sub3, int marks_sub4, int marks_sub5) { return marks_sub1 + marks_sub2 + marks_sub3 + marks_sub4 + marks_sub5; }
null
Reverse a given array without using a loop.
arr = [1,2,3,4]
[4, 3, 2, 1]
[HI Wikipedia] गुरुत्व विभव गुरुत्व विभव या गुरुत्वीय विभव () चिरसम्मत यांत्रिकी में उस कार्य को कहा जाता है जो किसी इकाई द्रव्यमान वाली वस्तु को प्रेक्षण बिन्दु तक लाने गुरुत्वीय बल के विरूध करना पडता है। यह विद्युत विभव के समान ही है, केवल आवेश के स्थान पर यहाँ द्रव्यमान का उपयोग होता है। इसकी विमा विद्युत विभव के स...
null
null
null
[HI Wikipedia] मुम्बई मुम्बई (अंग्रेजी: Mumbai), जिसका पुराना नाम बम्बई (Bombay बॉम्बे) था(१९९५ तक), भारत के महाराष्ट्र राज्य की राजधानी है। सन् २०१८ में यह दिल्ली के बाद जनगणना की दृष्टि से भारत का दूसरा सबसे बड़ा और विश्व का सातवाँ सबसे बड़ा शहर था। भारत की २०११ की जनगणना के अनुसार बृहन्मुम्बई महानगरपालिका द्वारा प्...
null
null
null
[HI Wikipedia] दाखश्टाइन दाखश्टाइन (Dachstein) आस्ट्रिया देश में पूर्व से पश्चिम को फैले हुए ऐल्प्स पर्वत के उत्तर में चूने के पत्थरों द्वारा निर्मित पर्वतीय श्रेणी का यह उच्चतम पठार है। इसकी ऊँचाई लगभग १०,००० फुट है। इसका विस्तार उत्तर में हैल्स्टाट तथा दक्षिण में श्लैडमिंग (Schladming) तक है। इसके चारों ओर लंबे चौड़...
null
null
null
null
Optimize a code snippet in Python. The code snippet is a function for computing the factorial of a number.
def factorial(n): if n < 1: return 1 else: return n*factorial(n-1)
def factorial(n): if n == 0: return 1 else: result = 1 for i in range(1, n+1): result *= i return result
null
Generate an HTML page on the browser with the text "Hello world."
<html> <head> </head> <body> Hello world. </body> </html>
[EN Wikipedia] Soil sealing Soil sealing or soil surface sealing is the loss of soil resources due to the covering of land for housing, roads or other construction work. Covering or replacing the topsoil with impervious materials like asphalt and cement as a result of urban development and infrastructure construction ...
null
null
null
null
Edit the Python code snippet to remove the syntax error.
def calculate_area(length, width): area = length * width return “The area is” + area
def calculate_area(length, width): area = length * width return "The area is " + str(area)