def calculate_percentage_by_group(data): total_sum = sum(data.values()) percentages = {key: (value / total_sum) * 100 for key, value in data.items()} return percentages data = {'Group A': 500, 'Group B': 800, 'Group C': 1200} percentage_by_group = calculate_percentage_by_group(data) for group, percentage in percentage_by_group.items(): print(f"{group}: {percentage:.2f}%")
Calculate percentage change
def calculate_percentage_change(old_value, new_value): return ((new_value - old_value) / old_value) * 100 old_value = 50 new_value = 70 percentage_change = calculate_percentage_change(old_value, new_value) print("Percentage change:", percentage_change, "%")
Calculate byte size of string
import sys def calculate_byte_size(string): return sys.getsizeof(string) my_string = "Hello, world!" byte_size = calculate_byte_size(my_string) print("Byte size of the string:", byte_size, "bytes")
Calculate distance between two coordinates
from math import radians, sin, cos, sqrt, atan2 def calculate_distance(lat1, lon1, lat2, lon2): lat1 = radians(lat1) lon1 = radians(lon1) lat2 = radians(lat2) lon2 = radians(lon2) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = 6371 * c return distance lat1, lon1 = 40.7128, -74.0060 lat2, lon2 = 34.0522, -118.2437 distance = calculate_distance(lat1, lon1, lat2, lon2) print("Distance between New York City and Los Angeles:", distance, "km")
Calculate time difference
from datetime import datetime start_time = datetime(2024, 4, 22, 10, 0, 0) end_time = datetime(2024, 4, 22, 12, 30, 0) time_difference = end_time - start_time print("Time difference:", time_difference)
Display all images in folder
scandir() function
<?php $directory = "images/"; $files = scandir($directory); $imageFiles = array_filter($files, function($file) use ($directory) { $filePath = $directory . $file; return is_file($filePath) && in_array(pathinfo($filePath, PATHINFO_EXTENSION), array("jpg", "jpeg", "png", "gif")); }); foreach ($imageFiles as $imageFile) { echo '<img src="' . $directory . $imageFile . '" alt="' . $imageFile . '">'; } ?>
Display array as string
toString()
const myArray = [1, 2, 3, 4, 5]; const arrayAsString = myArray.toString(); console.log(arrayAsString);
join()
const myArray = [1, 2, 3, 4, 5]; const arrayAsString = myArray.join(', '); console.log(arrayAsString);
Evaluate the equation and display the result
eval() function
equation = "2 * (3 + 4)" result = eval(equation) print("Result:", result)
Display execution time
import time start_time = time.time() result = 0 for i in range(1000000): result += i end_time = time.time() execution_time = end_time - start_time print("Execution time:", execution_time, "seconds")
Display elapsed time
time module
import time start_time = time.time() time.sleep(5) elapsed_time = time.time() - start_time print("Elapsed time:", elapsed_time, "seconds")