0% found this document useful (0 votes)
8 views5 pages

Python Solutions-1

Python language core for data science

Uploaded by

vaseemzain77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views5 pages

Python Solutions-1

Python language core for data science

Uploaded by

vaseemzain77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# 10.

Use reduce() with a lambda function to find the product of all elements in a
list
from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print("Product:", product)

# 11. Python script to sum two numbers from command-line arguments


import sys

if len([Link]) != 3:
print("Usage: python sum_numbers.py <num1> <num2>")
[Link](1)

num1, num2 = map(int, [Link][1:3])


print("Sum:", num1 + num2)

# 12. Count lines in a file


if len([Link]) != 2:
print("Usage: python count_lines.py <filename>")
[Link](1)

filename = [Link][1]

try:
with open(filename, 'r') as file:
print("Number of lines:", sum(1 for _ in file))
except FileNotFoundError:
print("Error: File not found")

# 13. Find the maximum value from command-line arguments


if len([Link]) < 2:
print("Usage: python max_value.py <num1> <num2> ...")
[Link](1)

numbers = list(map(int, [Link][1:]))


print("Maximum Value:", max(numbers))

# 14. Using argparse to accept a --name argument and print a greeting


import argparse

parser = [Link](description="Greet the user")


parser.add_argument("--name", type=str, required=True, help="Enter your name")
args = parser.parse_args()

print(f"Hello, {[Link]}!")

# 15. Print the first n Fibonacci numbers from command-line arguments


if len([Link]) != 2:
print("Usage: python [Link] <n>")
[Link](1)

n = int([Link][1])
def fibonacci(n):
if n <= 0:
return []
fib_seq = [0, 1]
for _ in range(2, n):
fib_seq.append(fib_seq[-1] + fib_seq[-2])
return fib_seq[:n]

print("Fibonacci Sequence:", fibonacci(n))

# 20. Remove duplicates from a list


def remove_duplicates(lst):
return list(set(lst))

# 21. Capitalize the first letter of every word in a sentence


def capitalize_words(sentence):
return ' '.join([Link]() for word in [Link]())

# 22. Find the second largest element in a list


def find_second_largest(lst):
unique_lst = list(set(lst))
if len(unique_lst) < 2:
return None
unique_lst.sort(reverse=True)
return unique_lst[1]

# 23. Lambda function to check if a number is even or odd


is_even_or_odd = lambda x: "Even" if x % 2 == 0 else "Odd"

# 24. Convert Celsius to Fahrenheit using map()


celsius_temps = [0, 20, 37, 100]
fahrenheit_temps = list(map(lambda c: (c * 9/5) + 32, celsius_temps))

# 25. Extract words that start with "a" using filter()


words = ["apple", "banana", "avocado", "grape", "apricot"]
a_words = list(filter(lambda word: [Link]().startswith('a'), words))

# 26. Sort a list of tuples based on the second element


tuples_list = [(1, 3), (4, 1), (2, 2), (5, 0)]
sorted_tuples = sorted(tuples_list, key=lambda x: x[1])

# 27. Compute the sum of all elements in a list using reduce()


sum_numbers = reduce(lambda x, y: x + y, numbers)

# 28. Sort a list of strings by length using sorted()


words = ["banana", "apple", "kiwi", "grapefruit"]
sorted_words = sorted(words, key=lambda x: len(x))
# 29. Script to take a name as a command-line argument and print a greeting message
if len([Link]) != 2:
print("Usage: python [Link] <name>")
[Link](1)

name = [Link][1]
print(f"Hello, {name}!")

# 30. Script to take a list of numbers as command-line arguments and print their
sum
if len([Link]) < 2:
print("Usage: python sum_numbers.py <num1> <num2> ...")
[Link](1)

numbers = list(map(int, [Link][1:]))


print("Sum:", sum(numbers))

# 31. Script to accept a filename as a command-line argument and print its content
if len([Link]) != 2:
print("Usage: python print_file.py <filename>")
[Link](1)

filename = [Link][1]

try:
with open(filename, 'r') as file:
print([Link]())
except FileNotFoundError:
print("Error: File not found")

# 32. Script to accept multiple command-line arguments and print the largest number
if len([Link]) < 2:
print("Usage: python max_number.py <num1> <num2> ...")
[Link](1)

numbers = list(map(int, [Link][1:]))


print("Largest Number:", max(numbers))

# 33. Script to count the number of words in a file


if len([Link]) != 2:
print("Usage: python count_words.py <filename>")
[Link](1)

filename = [Link][1]

try:
with open(filename, 'r') as file:
text = [Link]()
words = [Link]()
print("Word Count:", len(words))
except FileNotFoundError:
print("Error: File not found")

# 34. Python script using argparse to accept two numbers and an operator
parser = [Link](description="Simple Calculator")
parser.add_argument("num1", type=float, help="First number")
parser.add_argument("num2", type=float, help="Second number")
parser.add_argument("operator", choices=["+", "-", "*", "/"], help="Operator (+, -,
*, /)")

args = parser.parse_args()

if [Link] == "+":
result = args.num1 + args.num2
elif [Link] == "-":
result = args.num1 - args.num2
elif [Link] == "*":
result = args.num1 * args.num2
elif [Link] == "/":
result = args.num1 / args.num2 if args.num2 != 0 else "Error: Division by zero"

print("Result:", result)

# 35. Python script to accept a list of names and print them sorted alphabetically
if len([Link]) < 2:
print("Usage: python sort_names.py <name1> <name2> ...")
[Link](1)

names = [Link][1:]
sorted_names = sorted(names)

print("Sorted Names:", sorted_names)

# 36. Merge two sorted lists into one sorted list


def merge_sorted_lists(lst1, lst2):
merged = []
i, j = 0, 0

while i < len(lst1) and j < len(lst2):


if lst1[i] < lst2[j]:
[Link](lst1[i])
i += 1
else:
[Link](lst2[j])
j += 1

[Link](lst1[i:])
[Link](lst2[j:])

return merged

# 37. Find the longest word in a sentence


def longest_word(sentence):
words = [Link]()
return max(words, key=len) if words else None
# 1. Check if a number is prime
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True

# 2. Compute the factorial of a number


def factorial(n):
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result

# 3. Reverse a string
def reverse_string(s):
return s[::-1]

# 4. Count vowels in a string


def count_vowels(s):
vowels = "aeiouAEIOU"
return sum(1 for char in s if char in vowels)

# 5. Generate Fibonacci sequence up to n elements


def fibonacci(n):
if n <= 0:
return []
fib_seq = [0, 1]
for _ in range(2, n):
fib_seq.append(fib_seq[-1] + fib_seq[-2])
return fib_seq[:n]

# 6. Lambda function to square a number


square = lambda x: x ** 2

# 7. Lambda function to return the maximum of two numbers


maximum = lambda a, b: a if a > b else b

# 8. Use map() with a lambda function to double all elements in a list


numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))

# 9. Use filter() with a lambda function to get only even numbers


even_numbers = list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6, 7, 8]))

You might also like