51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
# File: OneDrive/Documents/Python%20Code/using_kwargs.py
|
|
# Using map to apply a function to each item in an iterable
|
|
def square(x):
|
|
return x * x
|
|
|
|
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # List of numbers from 1 to 10
|
|
squared_numbers = map(square, numbers)
|
|
|
|
# Convert the map object to a list
|
|
squared_numbers_list = list(squared_numbers)
|
|
print(squared_numbers_list)
|
|
|
|
# Using map to cube numbers
|
|
def cube(x):
|
|
return x * x * x
|
|
|
|
cubed_numbers = map(cube, numbers)
|
|
cubed_numbers_list = list(cubed_numbers)
|
|
print(cubed_numbers_list)
|
|
|
|
# Using filter to filter out even numbers
|
|
def is_even(x):
|
|
return x % 2 == 0
|
|
|
|
even_numbers = filter(is_even, numbers)
|
|
even_numbers_list = list(even_numbers)
|
|
print(even_numbers_list)
|
|
# Using filter to filter out odd numbers
|
|
def is_odd(x):
|
|
return x % 2 != 0
|
|
|
|
odd_numbers = filter(is_odd, numbers)
|
|
odd_numbers_list = list(odd_numbers)
|
|
print(odd_numbers_list)
|
|
|
|
# Step 1: Define the list of temperatures in Celsius
|
|
temp_celsius = [-40, 0, 25, 30, 40, 100]
|
|
|
|
# Step 2: Define a custom function to convert Celsius to Fahrenheit
|
|
def celsius_to_fahrenheit(celsius):
|
|
"""Convert temperature from Celsius to Fahrenheit."""
|
|
fahrenheit = (celsius * 9/5) + 32
|
|
return fahrenheit
|
|
|
|
# Step 3: Use map() with the custom function
|
|
temp_fahrenheit = map(celsius_to_fahrenheit, temp_celsius)
|
|
|
|
# Step 4: Convert the map object to a list and print
|
|
temp_fahrenheit_list = list(temp_fahrenheit)
|
|
print(temp_fahrenheit_list)
|