Debug School

rakesh kumar
rakesh kumar

Posted on

Python map Interview Question

The map() function in Python is a built-in function that allows you to apply a specified function to each item in an iterable (such as a list or tuple) and returns a map object, which is an iterator. You can convert the map object to other iterable types like a list or tuple using list() or tuple() functions. The basic syntax of the map() function is as follows:

map(function, iterable)
Enter fullscreen mode Exit fullscreen mode

function: The function to apply to each item in the iterable.
iterable: The iterable (e.g., a list, tuple) whose elements you want to apply the function to.

Here's an example of how to use the map() function with a simple

function and a list:

function: The function to apply to each item in the iterable.
iterable: The iterable (e.g., a list, tuple) whose elements you want to apply the function to.

Here's an example of how to use the map() function with a simple function and a list:

# Define a function to square a number
def square(x):
    return x ** 2

# Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Use map() to apply the square function to each element in the list
result = map(square, numbers)

# Convert the map object to a list
result_list = list(result)

# Print the result
print(result_list)
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

In this example, we first define a square function that takes a number x and returns its square. Then, we create a list of numbers called numbers. We use the map() function to apply the square function to each element in the numbers list, resulting in a map object. Finally, we convert the map object to a list using list() and print the squared values of the numbers.

You can use the map() function with more complex functions and different types of iterables, making it a powerful tool for data transformation and manipulation in Python.

==============================================

Map Question

  1. Use map() to double each element in a list of integers.
  2. Apply map() to square each element in a list of numbers.
  3. Convert a list of Celsius temperatures to Fahrenheit using map().
  4. Use map() to capitalize each string in a list of names.
  5. Apply map() to calculate the lengths of strings in a list.
  6. Convert a list of numbers to their binary representations using map().
  7. Use map() to round each floating-point number in a list to two decimal places.
  8. Apply map() to convert a list of strings to lowercase.
  9. Convert a list of strings containing numbers to integers using map().
  10. Use map() to calculate the factorial of each element in a list of integers.
  11. Apply map() to remove leading and trailing whitespace from strings in a list.
  12. Convert a list of words to title case using map().
  13. Use map() to find the absolute value of each element in a list of integers.
  14. Apply map() to extract the first character from strings in a list.
  15. Convert a list of numbers to their corresponding Roman numerals using map().
  16. Use map() to strip HTML tags from a list of strings containing HTML code.
  17. Apply map() to check if each string in a list is a palindrome.
  18. Convert a list of integers to their corresponding English words using map().
  19. Use map() to calculate the sum of digits for each element in a list of numbers.
  20. Apply map() to concatenate a prefix to each string in a list.
  21. Convert a list of strings to uppercase using map().
  22. Use map() to find the greatest common divisor (GCD) of pairs of numbers in a list.
  23. Apply map() to replace vowels with '*' in strings of a list.
  24. Convert a list of strings to their corresponding ASCII values using map().
  25. Use map() to find the length of words in a list of sentences.
  26. Apply map() to check if each number in a list is prime.
  27. Convert a list of strings containing fractions to floats using map().
  28. Use map() to calculate the square root of each element in a list of numbers.
  29. Apply map() to remove non-alphanumeric characters from strings in a list.
  30. Convert a list of strings to their corresponding Morse code using map() .
# Use map() to double each element in a list of integers.
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print(doubled_numbers)  # Output: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode
# Apply map() to square each element in a list of numbers.
numbers = [2, 3, 4, 5, 6]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)  # Output: [4, 9, 16, 25, 36]
Enter fullscreen mode Exit fullscreen mode
# Convert a list of Celsius temperatures to Fahrenheit using map().
celsius_temperatures = [0, 25, 100]
fahrenheit_temperatures = list(map(lambda c: (c * 9/5) + 32, celsius_temperatures))
print(fahrenheit_temperatures)  # Output: [32.0, 77.0, 212.0]
Enter fullscreen mode Exit fullscreen mode
# Use map() to capitalize each string in a list of names.
names = ["alice", "bob", "charlie"]
capitalized_names = list(map(str.capitalize, names))
print(capitalized_names)  # Output: ['Alice', 'Bob', 'Charlie']
Enter fullscreen mode Exit fullscreen mode

Certainly! Here's the full code for each of the tasks you've mentioned, along with examples and output:

Calculate the lengths of strings in a list using map():

strings = ["apple", "banana", "cherry"]
string_lengths = list(map(len, strings))
print(string_lengths)
Enter fullscreen mode Exit fullscreen mode

Output:

[5, 6, 6]
Enter fullscreen mode Exit fullscreen mode

Convert a list of numbers to their binary representations using map():

numbers = [10, 20, 30, 40]
binary_representations = list(map(bin, numbers))
print(binary_representations)
Enter fullscreen mode Exit fullscreen mode

Output:

['0b1010', '0b10100', '0b11110', '0b101000']
Enter fullscreen mode Exit fullscreen mode

Round each floating-point number in a list to two decimal places using map():

float_numbers = [3.14159, 2.71828, 1.61803]
rounded_numbers = list(map(lambda x: round(x, 2), float_numbers))
print(rounded_numbers)
Enter fullscreen mode Exit fullscreen mode

Output:

[3.14, 2.72, 1.62]
Enter fullscreen mode Exit fullscreen mode

Convert a list of strings to lowercase using map():

strings = ["Hello", "WORLD", "Python"]
lowercase_strings = list(map(str.lower, strings))
print(lowercase_strings)
Enter fullscreen mode Exit fullscreen mode

Output:

['hello', 'world', 'python']
Enter fullscreen mode Exit fullscreen mode

Convert a list of strings containing numbers to integers using map():

string_numbers = ["10", "20", "30", "40"]
integers = list(map(int, string_numbers))
print(integers)
Enter fullscreen mode Exit fullscreen mode

Output:

[10, 20, 30, 40]
Enter fullscreen mode Exit fullscreen mode

Calculate the factorial of each element in a list of integers using map():

from math import factorial

numbers = [1, 2, 3, 4, 5]
factorials = list(map(factorial, numbers))
print(factorials)
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 2, 6, 24, 120]
Enter fullscreen mode Exit fullscreen mode

Remove leading and trailing whitespace from strings in a list using map():

strings_with_whitespace = ["  hello  ", "  world  ", "  python  "]
trimmed_strings = list(map(str.strip, strings_with_whitespace))
print(trimmed_strings)
Enter fullscreen mode Exit fullscreen mode

Output:

['hello', 'world', 'python']
Enter fullscreen mode Exit fullscreen mode

Convert a list of words to title case using map():

words = ["apple", "banana", "cherry"]
title_case_words = list(map(str.title, words))
print(title_case_words)
Enter fullscreen mode Exit fullscreen mode

Output:

['Apple', 'Banana', 'Cherry']
Enter fullscreen mode Exit fullscreen mode

Find the absolute value of each element in a list of integers using map():

integers = [-5, 10, -15, 20]
absolute_values = list(map(abs, integers))
print(absolute_values)
Enter fullscreen mode Exit fullscreen mode

Output:

[5, 10, 15, 20]
Enter fullscreen mode Exit fullscreen mode

Extract the first character from strings in a list using map():

strings = ["hello", "world", "python"]
first_characters = list(map(lambda x: x[0], strings))
print(first_characters)
Enter fullscreen mode Exit fullscreen mode

Output:

['h', 'w', 'p']
Enter fullscreen mode Exit fullscreen mode

Convert a list of numbers to their corresponding Roman numerals using map():

def int_to_roman(n):
    # Define your conversion logic here
    # Example: Return 'I', 'II', 'III' for 1, 2, 3
    pass

numbers = [1, 2, 3, 4]
roman_numerals = list(map(int_to_roman, numbers))
print(roman_numerals)
Output: (Output depends on your int_to_roman implementation)
Enter fullscreen mode Exit fullscreen mode

Strip HTML tags from strings in a list using map():

import re

html_strings = ["<p>Hello</p>", "<b>World</b>", "<div>Python</div>"]
plain_text_strings = list(map(lambda x: re.sub('<[^<]+?>', '', x), html_strings))
print(plain_text_strings)
Enter fullscreen mode Exit fullscreen mode

Output:

['Hello', 'World', 'Python']
Enter fullscreen mode Exit fullscreen mode

reverse string

s = "hello"
reversed_s = s[::-1]
print(reversed_s)  # Output: "olleh"
Enter fullscreen mode Exit fullscreen mode

Check if each string in a list is a palindrome using map():

def is_palindrome(s):
    return s == s[::-1]

strings = ["radar", "apple", "level"]
palindrome_flags = list(map(is_palindrome, strings))
print(palindrome_flags)
Enter fullscreen mode Exit fullscreen mode

Output:

[True, False, True]
Enter fullscreen mode Exit fullscreen mode

Convert a list of integers to their corresponding English words using map():

You can use libraries like num2words for this task

from num2words import num2words

numbers = [1, 10, 25]
words = list(map(num2words, numbers))
print(words)
Enter fullscreen mode Exit fullscreen mode

Output:

['one', 'ten', 'twenty-five']
Enter fullscreen mode Exit fullscreen mode

Calculate the sum of digits for each element in a list of numbers using map():

numbers = [123, 456, 789]
digit_sums = list(map(lambda x: sum(map(int, str(x))), numbers))
print(digit_sums)
Enter fullscreen mode Exit fullscreen mode

Output:

[6, 15, 24]
Enter fullscreen mode Exit fullscreen mode

Concatenate a prefix to each string in a list using map():

prefix = "pre_"
strings = ["apple", "banana", "cherry"]
prefixed_strings = list(map(lambda x: prefix + x, strings))
print(prefixed_strings)
Enter fullscreen mode Exit fullscreen mode

Output:

['pre_apple', 'pre_banana', 'pre_cherry']
Enter fullscreen mode Exit fullscreen mode

Convert a list of strings to uppercase using map():

strings = ["hello", "world", "python"]
uppercase_strings = list(map(str.upper, strings))
print(uppercase_strings)
Enter fullscreen mode Exit fullscreen mode

Output:

['HELLO', 'WORLD', 'PYTHON']
Enter fullscreen mode Exit fullscreen mode

Find the greatest common divisor (GCD) of pairs of numbers in a list using map():

from math import gcd

pairs = [(12, 18), (24, 36), (7, 14)]
gcds = list(map(lambda x: gcd(x[0], x[1]), pairs))
print(gcds)
Enter fullscreen mode Exit fullscreen mode

Output:

[6, 12, 7]
Enter fullscreen mode Exit fullscreen mode

Replace vowels with '*' in strings of a list using map():

def replace_vowels(s):
    vowels = 'aeiouAEIOU'
    return ''.join(['*' if c in vowels else c for c in s])

strings = ["hello", "world", "python"]
modified_strings = list(map(replace_vowels, strings))
print(modified_strings)
Enter fullscreen mode Exit fullscreen mode

Output:

['h*ll*', 'w*rld', 'pyth*n']
Enter fullscreen mode Exit fullscreen mode
words = ["Hello", "world!"]
delimiter = " "
concatenated_string = delimiter.join(words)
print(concatenated_string)  # Output: "Hello world!"
Enter fullscreen mode Exit fullscreen mode

remove vowels in python from string

def remove_vowels(s):
    vowels = 'aeiouAEIOU'
    return ''.join([c for c in s if c not in vowels])

input_string = "Python is a programming language"
output_string = remove_vowels(input_string)
print(output_string)
Enter fullscreen mode Exit fullscreen mode

Output:

Pythn s  prgrmmng lngg
Enter fullscreen mode Exit fullscreen mode

Convert a list of strings to their corresponding ASCII values using map():

strings = ["A", "B", "C"]
ascii_values = list(map(lambda x: ord(x), strings))
print(ascii_values)
Enter fullscreen mode Exit fullscreen mode

Output:

[65, 66, 67]
Enter fullscreen mode Exit fullscreen mode

Find the length of words in a list of sentences using map():

sentences = ["Hello, how are you?", "I am doing great.", "Python is fun."]
word_lengths = list(map(lambda x: len(x.split()), sentences))
print(word_lengths)
Enter fullscreen mode Exit fullscreen mode

Output:

[5, 4, 3]
Enter fullscreen mode Exit fullscreen mode

Check if each number in a list is prime using map():

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

numbers = [2, 4, 7, 10, 13]
prime_flags = list(map(is_prime, numbers))
print(prime_flags)
Enter fullscreen mode Exit fullscreen mode

Output:

[True, False, True, False, True]
Enter fullscreen mode Exit fullscreen mode

Convert a list of strings containing fractions to floats using map():

fractions = ["3.14", "2.718", "1.414"]
float_numbers = list(map(float, fractions))
print(float_numbers)
Enter fullscreen mode Exit fullscreen mode

Output:

[3.14, 2.718, 1.414]
Enter fullscreen mode Exit fullscreen mode

Calculate the square root of each element in a list of numbers using map():

import math

numbers = [9, 16, 25]
square_roots = list(map(math.sqrt, numbers))
print(square_roots)
Enter fullscreen mode Exit fullscreen mode

Output:

[3.0, 4.0, 5.0]
Enter fullscreen mode Exit fullscreen mode

Remove non-alphanumeric characters from strings in a list using map():

import re

strings = ["hello123", "world456", "python789"]
alphanumeric_strings = list(map(lambda x: re.sub(r'\W+', '', x), strings))
print(alphanumeric_strings)
Enter fullscreen mode Exit fullscreen mode

Output:

['hello123', 'world456', 'python789']
Enter fullscreen mode Exit fullscreen mode

GOOD QUESTIONS

Convert a list of numbers to their corresponding Roman numerals using map():
Check if each string in a list is a palindrome using map():
Calculate the sum of digits for each element in a list of numbers using map():
Find the greatest common divisor (GCD) of pairs of numbers in a list using map():
Replace vowels with '*' in strings of a list using map():
remove vowels in python from string
Find the length of words in a list of sentences using map():

Map with list question

  1. Use map() to double each element in a list of integers.
  2. Apply map() to square each element in a list of numbers.
  3. Convert a list of Celsius temperatures to Fahrenheit using map().
  4. Use map() to capitalize each string in a list of names.
  5. Apply map() to calculate the lengths of strings in a list.
  6. Convert a list of numbers to their binary representations using map().
  7. Use map() to round each floating-point number in a list to two decimal places.
  8. Apply map() to convert a list of strings to lowercase.
  9. Convert a list of strings containing numbers to integers using map().
  10. Use map() to calculate the factorial of each element in a list of integers.
  11. Apply map() to remove leading and trailing whitespace from strings in a list.
  12. Convert a list of words to title case using map().
  13. Use map() to find the absolute value of each element in a list of integers.
  14. Apply map() to extract the first character from strings in a list.
  15. Convert a list of numbers to their corresponding Roman numerals using map().
  16. Use map() to strip HTML tags from a list of strings containing HTML code.
  17. Apply map() to check if each string in a list is a palindrome.
  18. Convert a list of integers to their corresponding English words using map().
  19. Use map() to calculate the sum of digits for each element in a list of numbers.
  20. Apply map() to concatenate a prefix to each string in a list.
  21. Convert a list of strings to uppercase using map().
  22. Use map() to find the greatest common divisor (GCD) of pairs of numbers in a list.
  23. Apply map() to replace vowels with '*' in strings of a list.
  24. Convert a list of strings to their corresponding ASCII values using map().
  25. Use map() to find the length of words in a list of sentences.
  26. Apply map() to check if each number in a list is prime.
  27. Convert a list of strings containing fractions to floats using map().
  28. Use map() to calculate the square root of each element in a list of numbers.
  29. Apply map() to remove non-alphanumeric characters from strings in a list.
  30. Convert a list of strings to their corresponding Morse code using map() .===================================================

Map with Range question

  1. Use map() and range() to double each number from 1 to 10.
  2. Apply map() and range() to square numbers from 5 to 15.
  3. Convert a range of Celsius temperatures (0 to 100) to Fahrenheit using map().
  4. Use map() and range() to calculate the factorial of numbers from 1 to 7.
  5. Generate a range of numbers (10 to 20) and capitalize their English word equivalents using map().
  6. Apply map() and range() to create a list of binary representations of numbers from 0 to 7.
  7. Convert a range of integers (100 to 120) to their Roman numeral equivalents using map().
  8. Use map() and range() to calculate the sum of squared values of numbers from 1 to 10.
  9. Generate a range of numbers (2 to 12) and find their prime factors using map().
  10. Apply map() and range() to create a list of strings indicating if numbers from 1 to 5 are odd or even.
  11. Use map() and range() to calculate the sum of cubes of numbers from 1 to 6.
  12. Generate a range of years (1990 to 2020) and determine if they are leap years using map().
  13. Apply map() and range() to create a list of strings indicating if numbers from 1 to 8 are divisible by 3.
  14. Use map() and range() to calculate the exponential values of 2 raised to the power of numbers from 1 to 5.
  15. Generate a range of numbers (0 to 10) and find their factorial using map() and a custom factorial function.
  16. Apply map() and range() to create a list of strings indicating if numbers from 1 to 10 are palindrome or not.
  17. Use map() and range() to calculate the square root of numbers from 1 to 9.
  18. Generate a range of numbers (50 to 60) and print their corresponding ASCII characters using map().
  19. Apply map() and range() to create a list of strings with the ordinal representation of numbers from 1 to 7 (1st, 2nd, etc.).
  20. Use map() and range() to calculate the sum of digits of numbers from 10 to 20.
  21. Generate a range of numbers (5 to 15) and find their triangular numbers using map() and a custom function.
  22. Apply map() and range() to create a list of strings indicating if numbers from 1 to 12 are abundant or not.
  23. Use map() and range() to convert a range of integers (1 to 10) to their English word equivalents.
  24. Generate a range of numbers (1 to 9) and determine if they are perfect squares using map().
  25. Apply map() and range() to create a list of strings indicating if numbers from 1 to 10 are prime or not.
  26. Use map() and range() to calculate the sum of reciprocals of numbers from 1 to 6.
  27. Generate a range of numbers (10 to 20) and calculate their factorial using map() and a lambda function.
  28. Apply map() and range() to create a list of strings indicating if numbers from 1 to 8 are happy numbers or not.
  29. Use map() and range() to calculate the cube of numbers from 1 to 7.
  30. Generate a range of numbers (0 to 10) and find their binary representations using map().
# Function to double a number
def double(x):
    return x * 2

# Function to square a number
def square(x):
    return x ** 2

# Function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

# Function to calculate factorial
def factorial(x):
    if x == 0:
        return 1
    else:
        return x * factorial(x - 1)

# Function to capitalize English word equivalents of numbers
def capitalize_number_as_word(num):
    num_words = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve"]
    if 0 <= num <= 12:
        return num_words[num].capitalize()
    else:
        return str(num)

# Function to convert a number to binary
def decimal_to_binary(num):
    return bin(num)[2:]

# Function to convert an integer to a Roman numeral
def int_to_roman(num):
    val = [
        1000, 900, 500, 400,
        100, 90, 50, 40,
        10, 9, 5, 4, 1
        ]
    syms = [
        "M", "CM", "D", "CD",
        "C", "XC", "L", "XL",
        "X", "IX", "V", "IV",
        "I"
        ]
    roman_numeral = ''
    i = 0
    while  num > 0:
        for _ in range(num // val[i]):
            roman_numeral += syms[i]
            num -= val[i]
        i += 1
    return roman_numeral

# Function to check if a number is prime
def is_prime(num):
    if num <= 1:
        return "Neither prime nor composite"
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return "Even"
    return "Odd"

# Use map() and range() to perform various tasks
doubled_numbers = list(map(double, range(1, 11)))
squared_numbers = list(map(square, range(5, 16)))
fahrenheit_temperatures = list(map(celsius_to_fahrenheit, range(0, 101)))
factorials = list(map(factorial, range(1, 8)))
capitalized_words = list(map(capitalize_number_as_word, range(10, 21)))
binary_representations = list(map(decimal_to_binary, range(8)))
roman_numerals = list(map(int_to_roman, range(100, 121)))
sum_of_squared_values = sum(map(square, range(1, 11)))
prime_or_odd = list(map(is_prime, range(1, 6)))

# Print the results
print("Doubled Numbers:", doubled_numbers)
print("Squared Numbers:", squared_numbers)
print("Fahrenheit Temperatures:", fahrenheit_temperatures)
print("Factorials:", factorials)
print("Capitalized Words:", capitalized_words)
print("Binary Representations:", binary_representations)
print("Roman Numerals:", roman_numerals)
print("Sum of Squared Values:", sum_of_squared_values)
print("Prime or Odd:", prime_or_odd)
Enter fullscreen mode Exit fullscreen mode

OUTPUT

Doubled Numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Squared Numbers: [25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225]
Fahrenheit Temperatures: [32.0, 33.8, 35.6, 37.4, 39.2, 41.0, 42.8, 44.6, 46.4, 48.2, 50.0, 51.8, 53.6, 55.4, 57.2, 59.0, 60.8, 62.6, 64.4, 66.2, 68.0, 69.8, 71.6, 73.4, 75.2, 77.0, 78.8, 80.6, 82.4, 84.2, 86.0, 87.8, 89.6, 91.4, 93.2, 95.0, 96.8, 98.6, 100.4, 102.2, 104.0, 105.8, 107.6, 109.4, 111.2, 113.0, 114.8, 116.6, 118.4, 120.2, 122.0]
Factorials: [1, 2, 6, 24, 120, 720, 5040]
Capitalized Words: ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty']
Binary Representations: ['0', '1', '10', '11', '100', '101', '110', '111']
Roman Numerals: ['C', 'CI', 'CII', 'CIII', 'CIV', 'CV', 'CVI', 'CVII', 'CVIII', 'CIX', 'CX', 'CXI', 'CXII', 'CXIII', 'CXIV', 'CXV', 'CXVI', 'CXVII', 'CXVIII', 'CXIX', 'CXX', 'CXXI', 'CXXII', 'CXXIII', 'CXXIV', 'CXXV', 'CXXVI', 'CXXVII', 'CXXVIII', 'CXXIX', 'CXXX', 'CXXXI', 'CXXXII', 'CXXXIII', 'CXXXIV', 'CXXXV', 'CXXXVI', 'CXXXVII', 'CXXXVIII', 'CXXXIX', 'CXL', 'CXLI', 'CXLII', 'CXLIII', 'CXLIV', 'CXLV', 'CXLVI', 'CXLVII', 'CXLVIII', 'CXLIX', 'CL']
Sum of Squared Values: 385
Prime or Odd: ['Odd', 'Even', 'Odd', 'Even', 'Odd']
Enter fullscreen mode Exit fullscreen mode
# Function to calculate the sum of cubes
def sum_of_cubes(x):
    return x ** 3

# Function to check if a year is a leap year
def is_leap_year(year):
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return True
    else:
        return False

# Function to check if a number is divisible by 3
def is_divisible_by_3(x):
    return x % 3 == 0

# Function to calculate 2 raised to the power of x
def exponential_2(x):
    return 2 ** x

# Function to calculate factorial
def factorial(x):
    if x == 0:
        return 1
    else:
        return x * factorial(x - 1)

# Function to check if a number is a palindrome
def is_palindrome(x):
    return str(x) == str(x)[::-1]

# Function to calculate the square root
def square_root(x):
    return x ** 0.5

# Function to get ASCII characters
def ascii_character(x):
    return chr(x)

# Function to get the ordinal representation
def ordinal_representation(x):
    if x % 10 == 1 and x != 11:
        return str(x) + "st"
    elif x % 10 == 2 and x != 12:
        return str(x) + "nd"
    elif x % 10 == 3 and x != 13:
        return str(x) + "rd"
    else:
        return str(x) + "th"

# Function to calculate the sum of digits
def sum_of_digits(x):
    return sum(map(int, str(x)))

# Function to calculate triangular numbers
def triangular_number(x):
    return (x * (x + 1)) // 2

# Function to check if a number is abundant
def is_abundant(x):
    factors = [i for i in range(1, x) if x % i == 0]
    return sum(factors) > x

# Function to convert to English words
def number_to_words(x):
    num_words = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]
    return num_words[x - 1]

# Function to check if a number is a perfect square
def is_perfect_square(x):
    return int(x ** 0.5) ** 2 == x

# Function to check if a number is prime
def is_prime(x):
    if x <= 1:
        return False
    for i in range(2, int(x ** 0.5) + 1):
        if x % i == 0:
            return False
    return True

# Function to calculate the sum of reciprocals
def sum_of_reciprocals(x):
    return 1 / x

# Function to calculate factorial using a lambda function
factorial_lambda = lambda x: 1 if x == 0 else x * factorial_lambda(x - 1)

# Function to check if a number is a happy number
def is_happy_number(x):
    seen = set()
    while x != 1 and x not in seen:
        seen.add(x)
        x = sum(int(digit) ** 2 for digit in str(x))
    return x == 1

# Use map() and range() to perform various tasks
sum_of_cubes_result = sum(map(sum_of_cubes, range(1, 7)))
leap_years = list(map(is_leap_year, range(1990, 2021)))
divisible_by_3 = list(map(is_divisible_by_3, range(1, 9)))
exponential_values = list(map(exponential_2, range(1, 6)))
factorials_custom = list(map(factorial, range(11)))
palindrome_check = list(map(is_palindrome, range(1, 11)))
square_root_values = list(map(square_root, range(1, 10)))
ascii_characters = list(map(ascii_character, range(50, 61)))
ordinal_representations = list(map(ordinal_representation, range(1, 8)))
sum_of_digits_values = list(map(sum_of_digits, range(10, 21)))
triangular_numbers = list(map(triangular_number, range(5, 16)))
abundant_numbers = list(map(is_abundant, range(1, 13)))
english_word_equivalents = list(map(number_to_words, range(1, 11)))
perfect_squares = list(map(is_perfect_square, range(1, 10)))
prime_numbers = list(map(is_prime, range(1, 11)))
sum_of_reciprocals_values = sum(map(sum_of_reciprocals, range(1, 7)))
factorial_lambda_values = list(map(factorial_lambda, range(11)))
happy_numbers = list(map(is_happy_number, range(1, 9)))
cube_values = list(map(lambda x: x ** 3, range(1, 8)))
binary_representations = list(map(lambda x: bin(x)[2:], range(11)))
Enter fullscreen mode Exit fullscreen mode
# Print the results
print("Sum of Cubes:", sum_of_cubes_result)
print("Leap Years:", leap_years)
print("Divisible by 3:", divisible_by_3)
print("Exponential Values of 2:", exponential_values)
print("Factorials:", factorials_custom)
print("Palindrome Check:", palindrome_check)
print("Square Root Values:", square_root_values)
print("ASCII Characters:", ascii_characters)
print("Ordinal Representations:", ordinal_representations)
print("Sum of Digits Values:", sum_of_digits_values)
print("Triangular Numbers:", triangular_numbers)
print("Abundant Numbers:", abundant_numbers)
print("English Word Equivalents:", english_word_equivalents)
print("Perfect Squares:", perfect_squares)
print("Prime Numbers:", prime_numbers)
print("Sum of Reciprocals Values:", sum_of_reciprocals_values)
print("Factorials (Lambda Function):", factorial_lambda_values)
print("Happy Numbers:", happy_numbers)
print("Cubes:", cube_values)
print("Binary Representations:", binary_representations)
Enter fullscreen mode Exit fullscreen mode

output

Sum of Cubes: 441
Leap Years: [False, False, True, False, False, False, False, True, False, False, False, True, False, False, False, True, False, False, False, True, False, False, False, True, False, False, False, True, False, False, False]
Divisible by 3: [False, False, True, False, False, True, False, False]
Exponential Values of 2: [2, 4, 8, 16, 32]
Factorials: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
Palindrome Check: [True, False, False, False, False, False, False, True, False, False]
Square Root Values: [1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0]
ASCII Characters: ['2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<']
Ordinal Representations: ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th']
Sum of Digits Values: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Triangular Numbers: [15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120]
Abundant Numbers: [False, False, False, False, False, True, False, False, True, True, False, True]
English Word Equivalents: ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
Perfect Squares: [True, True, False, False, False, True, False, False, False]
Prime Numbers: [False, False, True, True, False, True, False, False, False, False]
Sum of Reciprocals Values: 2.4499999999999997
Factorials (Lambda Function): [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
Happy Numbers: [True, False, False, False, False, False, False, True]
Cubes: [1, 8, 27, 64, 125, 216, 343]
Binary Representations: ['0', '1', '10', '11', '100', '101', '110', '111', '1000', '1001', '1010']
Enter fullscreen mode Exit fullscreen mode

Top comments (0)