0% found this document useful (0 votes)
5 views

AssignmentQuestions(sampleQuestionswithAnswers)_7ab1ae7fda537733eb109f9fc955886a

The document outlines various Python functions for performing operations on numbers, strings, and lists. It includes functions for checking perfect squares, cubes, and palindromes, as well as string manipulations like reversing, sorting, and checking for anagrams. Additionally, it describes functions for working with nested lists to find the smallest, largest, and those with maximum or minimum sums and averages.

Uploaded by

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

AssignmentQuestions(sampleQuestionswithAnswers)_7ab1ae7fda537733eb109f9fc955886a

The document outlines various Python functions for performing operations on numbers, strings, and lists. It includes functions for checking perfect squares, cubes, and palindromes, as well as string manipulations like reversing, sorting, and checking for anagrams. Additionally, it describes functions for working with nested lists to find the smallest, largest, and those with maximum or minimum sums and averages.

Uploaded by

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

1.

Construct a function perfect_square(number) that returns a number if it is a perfect


square otherwise it returns -1
For example:
perfect_square(1) returns 1
perfect_square(1) returns -1.
Solution:
import math

def perfect_square(number):
if number < 0:
return -1
sqrt = int(math.sqrt(number))
if sqrt * sqrt == number:
return number
else:
return -1

# Taking input from the user


user_input = int(input("Enter a number: "))
result = perfect_square(user_input)

# Display the result


if result == -1:
print(f"{user_input} is not a perfect square.")
else:
print(f"{user_input} is a perfect square.")
OR
def perfect_square(number):
if number < 0:
return -1
sqrt = int(number ** 0.5)
if sqrt * sqrt == number:
return number
else:
return -1
# Taking input from the user
user_input = int(input("Enter a number: "))
result = perfect_square(user_input)
# Display the result
if result == -1:
print(f"{user_input} is not a perfect square.")
else:
print(f"{user_input} is a perfect square."
2. Construct a function sum_of_even_numbers(n) that calculates the sum of all even
numbers from 1 to n. If n is less than 1, the function should return -1.
3. Construct a function is_perfect_cube(number) that checks if a given number is a
perfect cube. The function should return True if the number is a perfect cube,
otherwise return False.
4. Construct a function reverse_string(input_str) that reverses a given string input_str
and returns the reversed string.
5. Construct a function is_palindrome_number(number) that checks if a given number is
a palindrome. A number is a palindrome if it reads the same backward as forward.
6. Construct a function calculate_power(base, exponent) that calculates the value of
base raised to the power of exponent.
7. Construct a function calculate_square_root(number) that calculates the square root
of a given positive number. If the number is negative, the function should return -1.
8. Construct a function is_armstrong_number(number) that checks if a given number is
an Armstrong number. An Armstrong number (or narcissistic number) is a number that
is equal to the sum of its own digits each raised to the power of the number of digits.
9. Construct a function calculate_factorial(n) that calculates the factorial of a non-
negative integer n.

1. Construct a program that accepts a comma seperated sequence of words as input


and prints the words in a comma-seperated sequence after sorting them
alphabetically.
Suppose the following input is supplied to the program:
without, hello, bag, world
Then, the output should be:
bag, hello, without, world

def sort_words(input_str):
# Split the input string into a list of words
words = input_str.split(', ')

# Sort the list of words alphabetically


sorted_words = sorted(words)

# Join the sorted words into a comma-separated string


sorted_str = ', '.join(sorted_words)

# Print the sorted string


print(sorted_str)

# Example usage:
input_sequence = input("Enter a comma-separated sequence of words: ")
sort_words(input_sequence)
2. Construct a program that accepts a comma-separated sequence of words as input and
prints the words in a comma-separated sequence after sorting them in reverse
alphabetical order.
Input: without, hello, bag, world
Output: world, without, hello, bag
3. Construct a program that accepts a comma-separated sequence of words as input and
prints the words in a comma-separated sequence after sorting them based on their
length (shortest to longest).
Input: without, hello, bag, world
Output: bag, hello, world, without
4. Construct a program that accepts a comma-separated sequence of words as input and
prints each word along with its frequency of occurrence in the input sequence.
Input: hello, world, hello, python, world
Output:
hello: 2
world: 2
python: 1
5. Construct a program that accepts a comma-separated sequence of words as input and
prints the unique words in a comma-separated sequence.
Input: hello, world, hello, python, world
Output: hello, world, python
6. Construct a program that accepts a comma-separated sequence of words as input and
concatenates them into a single string without spaces between them.
Input: without, hello, bag, world
Output: withouthellobagworld
7. Construct a program that accepts a comma-separated sequence of words as input and
counts and displays the number of uppercase and lowercase letters in the entire
sequence.
Input: Hello, WoRlD, Python
Output:
Uppercase letters: 5
Lowercase letters: 10
8. Construct a program that accepts a comma-separated sequence of words as input and
checks and prints if each word is a palindrome or not.
Input: radar, level, hello, world
Output:
radar: True
level: True
hello: False
world: False
9. Construct a program that accepts two comma-separated sequences of words as input
and checks if they are anagrams of each other.(anagram: a word, phrase, or name
formed by rearranging the letters of another, such as spar, formed from rasp.)
Input 1: listen, silent
Input 2: hello, world
Output:
listen and silent are anagrams.
hello and world are not anagrams.

1. Determine a python function removenth(s,n) that takes an input a string and an


integer n>=0 and removes a character at index n. If n is beyond the length of s, the
whole s is returned. For example:
removenth("MANGO",1) returns MNGO
removenth("MANGO",3) returns MANO

def removenth(s, n):


if n >= len(s):
return s
return s[:n] + s[n+1:]

# Get input from the user


input_string = input("Enter a string: ")
input_index = int(input("Enter an index to remove: "))

# Call the function with user input and print the result
result = removenth(input_string, input_index)
print("Resulting string:", result)

2. Construct a function remove_nth_word(s, n) that takes a string s containing a


sentence and an integer n >= 0, and removes the word at index n (0-based index). If n
is beyond the number of words, the entire string is returned.
remove_nth_word("The quick brown fox jumps over the lazy dog", 3) returns "The
quick brown fox over the lazy dog"
remove_nth_word("The quick brown fox", 5) returns "The quick brown fox"

3. Construct a function replace_nth_char(s, n, char) that takes a string s, an integer n >=


0, and a character char, and replaces the character at index n with char. If n is beyond
the length of s, the entire string is returned.
replace_nth_char("MANGO", 1, 'X') returns "MXNGO"
replace_nth_char("MANGO", 5, 'X') returns "MANGO"

4. Construct a function insert_nth_char(s, n, char) that takes a string s, an integer n >= 0,


and a character char, and inserts char at index n. If n is beyond the length of s, char is
appended at the end.
insert_nth_char("MANGO", 1, 'X') returns "MXANGO"
insert_nth_char("MANGO", 5, 'X') returns "MANGOX"
5. Construct a function remove_nth_occurrence(s, char, n) that takes a string s, a
character char, and an integer n >= 0, and removes the nth occurrence of char from
the string. If n is beyond the number of occurrences, the entire string is returned.
remove_nth_occurrence("banana", 'a', 1) returns "bnana"
remove_nth_occurrence("banana", 'a', 3) returns "banana"
6. Construct a function toggle_nth_case(s, n) that takes a string s and an integer n >= 0,
and toggles the case of the character at index n. If the character is uppercase, it
becomes lowercase, and vice versa. If n is beyond the length of s, the entire string is
returned.
toggle_nth_case("MANGO", 1) returns "MaNGO"
toggle_nth_case("MANGO", 5) returns "MANGO"
7. Construct a function swap_nth_mth_chars(s, n, m) that takes a string s and two
integers n and m (both >= 0), and swaps the characters at indices n and m. If either n
or m is beyond the length of s, the entire string is returned.
swap_nth_mth_chars("MANGO", 1, 3) returns "MGNAO"
swap_nth_mth_chars("MANGO", 1, 5) returns "MANGO"
8. Construct a function remove_nth_vowel(s, n) that takes a string s and an integer n >=
0, and removes the nth vowel from the string. If n is beyond the number of vowels,
the entire string is returned.
remove_nth_vowel("hello world", 1) returns "hllo world"
remove_nth_vowel("hello world", 5) returns "hello world"
9. Construct a function extract_nth_word(s, n) that takes a string s containing a sentence
and an integer n >= 0, and returns the nth word of the string. If n is beyond the number
of words, an empty string is returned.
extract_nth_word("The quick brown fox jumps over the lazy dog", 3) returns "jumps"
extract_nth_word("The quick brown fox", 5) returns ""

1. Construct a function retsmaller(1) that returns smallest list from a nested list. If two
lists have same length then return the first list that is encountered.
For example:
retsmaller([ [-2, -1, 0, 0.12, 1, 2], [3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]])
returns [3,4,5]

retsmaller([ [-2, -1, 0, 0.12, 1, 2], ['a', 'b', 'c', 'd', 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13,
14, 15]] )
returns [6, 7, 8, 9, 10]

def ret_smaller(nested_list):
# Initialize the smallest list with the first list in the nested list
smallest_list = nested_list[0]

# Iterate over the rest of the lists in the nested list


for lst in nested_list[1:]:
# Compare lengths and update smallest_list if current list is smaller
if len(lst) < len(smallest_list):
smallest_list = lst

return smallest_list

# Get input from the user


input_nested_list = input("Enter a nested list (e.g., [[1, 2, 3], [4, 5], [6]]): ")

# Evaluate the input to convert it from string to a list


nested_list = eval(input_nested_list)

# Call the function with user input and print the result
result = ret_smaller(nested_list)
print("The smallest list is:", result)

2. Construct a function ret_larger(nested_list) that returns the largest list from a nested
list. If two lists have the same length, then return the first list that is encountered.
ret_larger([ [-2, -1, 0, 0.12, 1, 2], [3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]])
returns [11, 12, 13, 14, 15]

ret_larger([ [-2, -1, 0, 0.12, 1, 2], ['a', 'b', 'c', 'd', 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14,
15]] )
returns ['a', 'b', 'c', 'd', 3, 4, 5]

3. Construct a function ret_max_sum(nested_list) that returns the list with the maximum
sum of elements from a nested list. If two lists have the same sum, then return the
first list that is encountered.
ret_max_sum([[1, 2, 3], [4, 5], [1, 1, 1, 1]])
returns [4, 5]

ret_max_sum([[1, 2, 3], [1, 1, 1, 1], [2, 2, 2]])


returns [1, 2, 3]

4. Construct a function ret_min_sum(nested_list) that returns the list with the minimum
sum of elements from a nested list. If two lists have the same sum, then return the
first list that is encountered.
ret_min_sum([[1, 2, 3], [4, 5], [1, 1, 1, 1]])
returns [1, 1, 1, 1]

ret_min_sum([[1, 2, 3], [4, 5], [-1, 0, 1]])


returns [-1, 0, 1]
5. Construct a function ret_max_product(nested_list) that returns the list with the
maximum product of elements from a nested list. If two lists have the same product,
then return the first list that is encountered.
ret_max_product([[1, 2, 3], [2, 2, 2], [1, 1, 1, 1]])
returns [2, 2, 2]

ret_max_product([[1, 2, 3], [4, 1], [1, 1, 1, 1]])


returns [4, 1]

6. Construct a function ret_max_avg(nested_list) that returns the list with the highest
average value from a nested list. If two lists have the same average, then return the
first list that is encountered.
ret_max_avg([[1, 2, 3], [4, 5], [10, 20]])
returns [10, 20]

ret_max_avg([[1, 2, 3], [4, 5], [3, 4, 5]])


returns [4, 5]

7. Construct a function ret_min_avg(nested_list) that returns the list with the lowest
average value from a nested list. If two lists have the same average, then return the
first list that is encountered.
ret_min_avg([[1, 2, 3], [0, 0, 0], [1, 1, 1]])
returns [0, 0, 0]

ret_min_avg([[1, 2, 3], [4, 5], [1, 1, 1, 1]])


returns [1, 1, 1, 1]

8. Construct a function ret_max_median(nested_list) that returns the list with the


highest median value from a nested list. If two lists have the same median, then return
the first list that is encountered.
ret_max_median([[1, 3, 2], [4, 5, 6], [7, 8, 9]])
returns [7, 8, 9]

ret_max_median([[1, 2, 3], [4, 5, 6], [1, 3, 5]])


returns [4, 5, 6]

9. Construct a function ret_min_median(nested_list) that returns the list with the lowest
median value from a nested list. If two lists have the same median, then return the
first list that is encountered.
ret_min_median([[1, 2, 3], [0, 0, 0], [1, 1, 1]])
returns [0, 0, 0]

ret_min_median([[1, 3, 2], [4, 5, 6], [7, 8, 9]])


returns [1, 3, 2]
1. A website requires the users to input username and password to register.
Construct a program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
3. At least 1 letter between [A-Z]
4. At least 1 character from [$#@]
5. Minimum length of transaction password: 6
6.. Maximum length of transaction password: 12
Your program should accept sequence of comma seperated passwords and will
check them according to the above criteria. Passwords that match the criteria
are to be printed, each seperated by a comma.

def check_password_validity(passwords):
valid_passwords = []

for password in passwords:


if 6 <= len(password) <= 12:
has_lower = False
has_upper = False
has_digit = False
has_special = False
special_characters = "$#@"

for char in password:


if 'a' <= char <= 'z':
has_lower = True
elif 'A' <= char <= 'Z':
has_upper = True
elif '0' <= char <= '9':
has_digit = True
elif char in special_characters:
has_special = True

if has_lower and has_upper and has_digit and has_special:


valid_passwords.append(password)

return valid_passwords

# Get input from the user


input_passwords = input("Enter passwords (comma separated): ")

# Split the input into a list of passwords


password_list = [p.strip() for p in input_passwords.split(',')]
# Check the validity of each password
valid_passwords = check_password_validity(password_list)

# Print the valid passwords


print("Valid passwords: " + ", ".join(valid_passwords))

2. A website requires the users to input their email addresses to register. Construct
a program to check the validity of email inputs by users. Following are the criteria
for checking the email:
i. It should contain '@'.
ii. It should contain at least one '.' after the '@'.
iii. The '@' should not be at the beginning or end of the email.
iv. The '.' should not be at the beginning or end of the email and should be
after '@'.
v. The email should not contain spaces.
Your program should accept a sequence of comma-separated emails and check
them according to the above criteria. Emails that match the criteria are to be
printed, each separated by a comma.

3. A website requires the users to input a username to register. Construct a program


to check the validity of username inputs by users. Following are the criteria for
checking the username:
i. It should start with a letter.
ii. It should only contain alphanumeric characters and underscores (_).
iii. The length should be between 5 and 15 characters.
Your program should accept a sequence of comma-separated usernames and
check them according to the above criteria. Usernames that match the criteria are
to be printed, each separated by a comma.

4. A website requires users to input their phone number to register. Construct a


program to check the validity of the phone number input by users. The criteria for
checking the phone number are:
i. It must be exactly 10 digits long.
ii. It should only contain digits from 0 to 9.
Your program should accept a sequence of comma-separated phone numbers and
check them according to the above criteria. Valid phone numbers should be
printed, each separated by a comma.

5. A website requires users to input their credit card number for making transactions.
Construct a program to check the validity of credit card numbers input by users.
The following are the criteria for checking the credit card number:
i. Must be exactly 16 digits long.
ii. Must contain only numbers.
iii. The first digit must be a 4, 5, or 6.
Your program should accept a sequence of comma-separated credit card numbers
and will check them according to the above criteria. Credit card numbers that
match the criteria are to be printed, each separated by a comma.

6. A website requires users to input their birth date for registration. Construct a
program to check the validity of birth dates input by users. The following are the
criteria for checking the date:
i. Must be in the format DD/MM/YYYY.
ii. Day must be between 01 and 31.
iii. Month must be between 01 and 12.
iv. Year must be a four-digit number.
Your program should accept a sequence of comma-separated dates and will check
them according to the above criteria. Dates that match the criteria are to be
printed, each separated by a comma.

7. A website requires users to input a strong password for registration. Construct a


program to check the validity of passwords input by users. The following are the
criteria for checking the password:
i. At least 1 lowercase letter.
ii. At least 1 uppercase letter.
iii. At least 1 number.
iv. At least 1 special character from !@#$%^&*()_+.
v. Minimum length of the password: 8.
vi. Maximum length of the password: 16.
Your program should accept a sequence of comma-separated passwords and will
check them according to the above criteria. Passwords that match the criteria are
to be printed, each separated by a comma.

1. Illustrate different list slicing constructs for the following operations on the
following list:
L=[1,2,3,4,5,6,7,8,9]
i. Return a list of numbers starting from the last to second item of the list.
ii. Return a list that starts from 3rd item to second last item.
iii. Return a list that has only even position elements of list L to List M.
iv. Return a list that starts from the middle of the list L.
v. Return a list that reverses all the elements starting from element at index
0 to middle index only and return the entire list.
Divide each element of the list by 2 and replace it with the remainder.

i. Return a list of numbers starting from the last to second item of the list:
L=[1,2,3,4,5,6,7,8,9]
result = L[-1:1:-1]
print(result) # Output: [9, 8, 7, 6, 5, 4, 3]
ii. Return a list that starts from 3rd item to second last item:
L=[1,2,3,4,5,6,7,8,9]
result = L[2:-1]
print(result) # Output: [3, 4, 5, 6, 7, 8]

iii. Return a list that has only even position elements of list L to List M:
L=[1,2,3,4,5,6,7,8,9]
M = L[1::2]
print(M) # Output: [2, 4, 6, 8]

iv. Return a list that starts from the middle of the list L:
L=[1,2,3,4,5,6,7,8,9]
middle_index = len(L) // 2
result = L[middle_index:]
print(result) # Output: [5, 6, 7, 8, 9]

v. Return a list that reverses all the elements starting from element at index 0
to middle index only and return the entire list:
L=[1,2,3,4,5,6,7,8,9]
middle_index = len(L) // 2
result = L[:middle_index][::-1] + L[middle_index:]
print(result) # Output: [4, 3, 2, 1, 5, 6, 7, 8, 9]

Divide each element of the list by 2 and replace it with the remainder:
L=[1,2,3,4,5,6,7,8,9]
result = [x % 2 for x in L]
print(result) # Output: [1, 0, 1, 0, 1, 0, 1, 0, 1]

1. List Slicing for Temperature Data:


You have a list temperature_data containing daily temperatures for a month.
Write Python code to:
i. Return the last 10 days of temperature data.
ii. Return temperature data starting from the 5th day to the 25th day.
iii. Extract temperatures from even-numbered days into a new list
even_day_temps.
iv. Return temperatures from the middle of the month to the end.
v. Reverse the temperatures from the beginning up to the middle index and
return the entire list.

2. List Slicing for Financial Data:


You are given a list stock_prices containing daily closing prices of a stock.
Write Python code to:
i. Return the last 20 days of closing prices.
ii. Extract closing prices from the 10th day to the 30th day.
iii. Create a new list even_index_prices with prices at even indices.
iv. Retrieve prices from the middle of the list to the end.
v. Reverse the prices from the start up to the middle index and return the entire
list.

3. List Slicing for Student Records:


You have a list student_records containing tuples of student information (name, age,
grade).
Write Python code to:
i. Return the last 5 student records.
ii. Extract records starting from the 3rd student to the 15th student.
iii. Create a new list even_position_students with records at even positions (2nd,
4th, 6th, ...).
iv. Retrieve student records from the middle of the list to the end.
v. Reverse the student records from the beginning up to the middle index and
return the entire list.

4. List Slicing for Product Inventory:


You have a list product_inventory containing dictionaries representing product details
(name, price, quantity). Write Python code to:
i. Return details of the last 15 products in the inventory.
ii. Extract product details starting from the 5th product to the 25th product.
iii. Create a new list even_quantity_products with products having even
quantities.
iv. Retrieve product details from the middle of the inventory to the end.
v. Reverse the product details from the start up to the middle index and return
the entire list.

5. List Slicing for Text Processing:


You have a list text_data containing strings of sentences. Write Python code to:

i. Return the last 5 sentences in the text data.


ii. Extract sentences starting from the 3rd sentence to the 15th sentence.
iii. Create a new list even_length_sentences with sentences having even lengths.
iv. Retrieve sentences from the middle of the list to the end.
v. Reverse the sentences from the beginning up to the middle index and return
the entire list.

You might also like