[go: up one dir, main page]

0% found this document useful (0 votes)
3 views16 pages

CH 6,7 Assignment Soln

The document outlines various programming tasks and concepts in Python, including string manipulation, list methods, functions, and data handling. It covers topics such as extracting digits from strings, validating phone number formats, and performing operations like reversing strings and finding averages. Additionally, it discusses the differences between lists and strings, indexing versus slicing, and provides examples of functions and their benefits.

Uploaded by

jiya23022009
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)
3 views16 pages

CH 6,7 Assignment Soln

The document outlines various programming tasks and concepts in Python, including string manipulation, list methods, functions, and data handling. It covers topics such as extracting digits from strings, validating phone number formats, and performing operations like reversing strings and finding averages. Additionally, it discusses the differences between lists and strings, indexing versus slicing, and provides examples of functions and their benefits.

Uploaded by

jiya23022009
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/ 16

1.

Write a program that should do the following:


• prompt the user for a string
• extract all the digits from the string
• If there are digits:
o sum the collected digits together
o print out the original string, the digits, the sum of the digits
• If there are no digits: o print the original string and a message "has no
digits"
2. Write a program that prompts for a phone number of 10 digits and
two dashes, with dashes after the area code and the next three
numbers. For example, 017-555-1212 is a legal input. Display if the
phone number entered is valid format or not and display if the phone
number is valid or not (i.e., contains just the digits and dash at specific
places.)

3. What is the result of the following expression?


s = '0123456789'
print(s[3], ", ", s[0 : 3], " - ", s[2 : 5])
print(s[:3], " - ", s[3:], ", ", s[3:100])
print(s[20:], s[2:1], s[1:1])

3- not possible
4. Given a string S = "CARPE DIEM". If n is length/2 (length is the length
of the given string), then what would the following return?
(a) S[: n]
(b) S[n :]
(c) S[n : n]
(d) S[1 : n]
(e) S[n : length - 1]

5.What is the purpose of slicing in programming ?


Purpose of Slicing in Programming:
1. Extracting Substrings or Subarrays – Helps retrieve specific portions
of strings, lists, or tuples.
2. Efficient Data Manipulation – Allows easy access to subsets of data
without modifying the original.
3. Avoiding Loops – Provides a concise way to access multiple elements
instead of using loops.
4. Reversing Sequences – Used to reverse strings or lists ([::-1]).
5. Skipping Elements – Enables selecting elements with a step value
([::2] for every second item).
6. Copying Sequences – Creates a copy of a list or string ([:]).
6. List out all the string and list methods with appropriate examples.
Method Description Example Output
upper() Converts to uppercase "hello".upper() 'HELLO'
lower() Converts to lowercase "HELLO".lower() 'hello'
strip() Removes whitespace " hello ".strip() 'hello'
replace() Replaces substring "hello".replace('l', 'hexxo'
'x')
split() Splits into a list "a,b,c".split(',') ['a', 'b',
'c']
join() Joins elements with "-".join(['a', 'b', 'a-b-c'
'c'])
separator
find() Finds a substring index "hello".find('e') 1
startswith() Checks prefix "hello".startswith('he') True
endswith() Checks suffix "hello".endswith('lo') True
count() Counts occurrences "hello".count('l') 2
capitalize() Capitalizes first letter "hello".capitalize() 'Hello'

Method Description Example Output


append() Adds element at end lst = [1,2]; [1, 2, 3]
lst.append(3)
extend() Merges another list lst.extend([4,5]) [1, 2, 3, 4, 5]
insert() Inserts at specific index lst.insert(1, 99) [1, 99, 2, 3]
remove() Removes first occurrence lst.remove(2) [1, 3]
pop() Removes & returns lst.pop(1) 99 (and list [1, 2,
last/indexed 3])
index() Returns index of element lst.index(3) 2
count() Counts occurrences of lst.count(2) 1
element
reverse() Reverses the list lst.reverse() [3, 2, 1]
sort() Sorts the list lst.sort() [1, 2, 3]
clear() Empties the list lst.clear() []
copy() Returns a shallow copy lst.copy() [1, 2, 3]
7. What is functions in python and write down the benefits of using
function.
What is a Function in Python?
A function is a block of code that runs only when called. It helps
perform a specific task and can take input (parameters) and return
output.
Example:
def greet(name):
print("Hello,", name)

greet("Alice")
Output:
Hello, Alice

Benefits of Using Functions:


1. Avoids Repetition – Write code once, use it many times.
2. Makes Code Shorter – Reduces the length of the program.
3. Easier to Read – Organizes code into smaller parts.
4. Simplifies Debugging – Fixing errors becomes easier.
5. Allows Inputs (Parameters) – Makes the function more flexible.
6. Helps in Large Programs – Divides big tasks into smaller,
manageable ones.
8. what is the difference between list and string in python.
Difference Between List and String in Python
Feature List String
Definition A collection of items A sequence of characters
(mutable) (immutable)
Data Type Can store different data Stores only characters
types (text)
Mutability Mutable (can be changed) Immutable (cannot be
changed)
Modification Items can be added, Characters cannot be
removed, or modified changed directly
Indexing Supports indexing and Supports indexing and
slicing slicing
Example my_list = [1, 2, 3] my_string = "hello"
Methods .append(), .remove(), .upper(), .lower(),
.sort() .replace()
Iteration Iterates over elements Iterates over characters

9. Difference between indexing and slicing in python.


Difference Between Indexing and Slicing in Python
Feature Indexing Slicing
Definition Accesses a single Extracts a part (subsequence)
element of a sequence
Syntax variable[index] variable[start:stop:step]
Returns A single item A new sequence
(string/list/tuple)
Mutability Lists allow Creates a new copy, doesn't
modification modify original
Usage Used to fetch one Used to fetch multiple values
value
Negative Works (e.g., -1 gives Works (e.g., [::-1] reverses
Indexing last element) sequence)
Example "Python"[2] → 't' "Python"[1:4] → 'yth'

10)Given a list of numbers, how would you find the average, maximum,
and minimum values?
You can find the average, maximum, and minimum values in a list using
Python's built-in sum(), max(), and min() functions.
Example Code:
numbers = [10, 20, 30, 40, 50]

# Find average using sum() and len()


average = sum(numbers) / len(numbers)
# Find maximum using max()
maximum = max(numbers)

# Find minimum using min()


minimum = min(numbers)

print("Average:", average)
print("Maximum:", maximum)
print("Minimum:", minimum)
Keywords Used:
• sum() → Adds all elements in the list.
• len() → Counts the total number of elements.
• max() → Finds the highest value.
• min() → Finds the lowest value.
10)You have a string containing a sentence. How would you reverse the
order of the words in the sentence? Hint: Use string methods like split(),
reverse(), and join() to manipulate the string.
You can reverse the order of words in a sentence using split(), reverse(),
and join() as follows:
Python Code:
sentence = "Hello world this is Python"
# Split the sentence into words
words = sentence.split()

# Reverse the list of words


words.reverse()

# Join the words back into a sentence


reversed_sentence = " ".join(words)

print(reversed_sentence)
Output:
"Python is this world Hello"
Alternative (Using Slicing [::-1]):
reversed_sentence = " ".join(sentence.split()[::-1])
print(reversed_sentence)
Explanation of Keywords:
• split() → Splits the string into a list of words.
• reverse() → Reverses the list in place.
• [::-1] → An alternative way to reverse a list using slicing.
• join() → Combines the list of words back into a string.
11. Create a function that takes a string as input and returns a new
string with the following modifications:
1. Reverse the order of words.
2. Convert all characters to uppercase.
3. Remove all punctuation marks.
import string

def modify_string(input_string):
# 1. Reverse the order of words
words = input_string.split()
reversed_words = words[::-1]

# 2. Convert all characters to uppercase


uppercased_string = " ".join(reversed_words).upper()

# 3. Remove all punctuation marks


cleaned_string = uppercased_string.translate(str.maketrans("", "",
string.punctuation))

return cleaned_string

# Example usage:
input_string = "Hello, world! This is Python."
result = modify_string(input_string)
print(result)
12. Check if a String is a Palindrome

13. Find a Character in a String.


14. Reverse a String ● Problem: Write a function to reverse a given
string.[Without using built-in methods] ● Example: Input: "hello" →
Output: "olleh"
def reverse_string(s):
reversed_str = "" # Initialize an empty string
for char in s: # Loop through each character
reversed_str = char + reversed_str # Add each character at the
beginning
return reversed_str # Return the reversed string

# Example usage
input_string = "hello"
output_string = reverse_string(input_string)
print(output_string) # Output: "olleh"
15. Remove Duplicates from a String ● Problem: Write a function to
remove duplicate characters in a string. ● Example: Input:
"programming" → Output: "progamin"

16. Problem: Given a list of numbers, create a new list containing only
the even numbers using list comprehension.
17. Given a list of numbers, implement a function that sorts the list in
ascending order, removes all duplicate elements, inserts a new element
at a specific index, and then extends the list with another list.
#Algorithm [Steps/hints]:
1. Sort the list in ascending order.
2. Remove duplicate elements using a set and then convert it back to a
list.
3. Insert a new element at the specified index.
4. Extend the list by appending another list

You might also like