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

24msd7048(Python Lab-2).PDF (1)

Uploaded by

tarun.24msd7001
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

24msd7048(Python Lab-2).PDF (1)

Uploaded by

tarun.24msd7001
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

Reverse a String Problem: Write a program to reverse a string without using built-in
methods.
Algorithm:
1. Get the input string.
2. Use a loop to iterate from the end of the string to the start.
3. Append each character to a new string.
4. Print the reversed string.

Code:
def reverse_string(input_string):
reversed_string = ""
for i in range(len(input_string) - 1, -1, -1):
reversed_string += input_string[i]
return reversed_string

# Test the function


input_string = input("Enter a string: ")
print("Reversed string:", reverse_string(input_string))

Output:

2. Check for Palindrome Problem:


Check if a string is a palindrome without using built-in methods like lower() or replace().
Algorithm:
1. Get the input string.
2. Remove spaces manually by creating a new string without spaces.
3. Convert to lowercase by comparing characters directly (if they are ASCII letters).
4. Check if the string is the same when read backward.

Code:
def is_palindrome(input_string):
# Remove spaces manually
no_spaces_string = ""
for char in input_string:
if char != " ":
no_spaces_string += char

# Convert to lowercase manually


lowercase_string = ""
for char in no_spaces_string:
ascii_value = ord(char)
if 65 <= ascii_value <= 90: # ASCII values for uppercase letters
lowercase_string += chr(ascii_value + 32) # Convert to lowercase
else:
lowercase_string += char

# Check if the string is the same when read backward


reversed_string = ""
for i in range(len(lowercase_string) - 1, -1, -1):
reversed_string += lowercase_string[i]

return lowercase_string == reversed_string

# Test the function


input_string = input("Enter a string: ")
if is_palindrome(input_string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

Output:

3. Count Vowels and Consonants Problem:


Count the number of vowels and consonants in a string without using built-in methods
like count().
Algorithm:
1. Loop through each character of the string.
2. Check if the character is a vowel (both uppercase and lowercase).
3. If not a vowel and it’s a letter, count it as a consonant.

Code:
def count_vowels_and_consonants(input_string):
vowel_count = 0
consonant_count = 0

for char in input_string:


if char.isalpha(): # Check if the character is a letter
ascii_value = ord(char.lower()) # Convert to lowercase for simplicity
if ascii_value in [97, 101, 105, 111, 117]: # ASCII values for vowels (a, e, i, o, u)
vowel_count += 1
else:
consonant_count += 1

return vowel_count, consonant_count

# Test the function


input_string = input("Enter a string: ")
vowels, consonants = count_vowels_and_consonants(input_string)
print(f"Vowels: {vowels}, Consonants: {consonants}")

Output:

4. Find the Length of a String Problem:


Determine the length of a string without using the len() function.
Algorithm:
1. Initialize a counter to 0.
2. Use a loop to iterate over each character in the string and increment the counter.

Code:

def find_string_length(input_string):
length = 0
for char in input_string:
length += 1
return length

# Test the function


input_string = input("Enter a string: ")
print("Length of the string:", find_string_length(input_string))
5. Convert Uppercase to Lowercase Problem:
Convert all uppercase letters to lowercase manually.
Algorithm:
1. Iterate through each character.
2. If it’s an uppercase letter ('A' to 'Z'), convert it to lowercase using ord(char) + 32.

Code:
def convert_to_lowercase(input_string):
lowercase_string = ""
for char in input_string:
ascii_value = ord(char)
if 65 <= ascii_value <= 90: # ASCII values for uppercase letters
lowercase_string += chr(ascii_value + 32) # Convert to lowercase
else:
lowercase_string += char
return lowercase_string

# Test the function


input_string = input("Enter a string: ")
print("Original string:", input_string)
print("Converted string:", convert_to_lowercase(input_string))

Output:

6. Count the Occurrence of a Character Problem:


Count how many times a given character appears in a string.
Algorithm:
1. Initialize a counter to 0.
2. Loop through the string and compare each character with the target character.
3. Increment the counter when a match is found

Code:
def count_character_occurrence(input_string, target_char):
count = 0
for char in input_string:
if char == target_char:
count += 1
return count
# Test the function
input_string = input("Enter a string: ")
target_char = input("Enter a character to count: ")
print(f"The character '{target_char}' appears {count_character_occurrence(input_string,
target_char)} times in the string.")

Output:

7. Remove Spaces from a String Problem:


Remove all spaces from a string without using replace().
Algorithm:
1. Initialize an empty string.
2. Loop through the input string, adding non-space characters to the new string

Code:
def remove_spaces(input_string):
result_string = ""
for char in input_string:
if char != " ": # Check if the character is not a space
result_string += char # Add non-space characters to the result
return result_string

# Test the function


input_string = input("Enter a string: ")
print("String without spaces:", remove_spaces(input_string))

Output:

8. Count Words in a Sentence Problem:


Count the number of words in a sentence.
Algorithm:
1. Initialize a counter.
2. Count spaces between words (assuming one space between each word).
Code:
def count_words(sentence):
word_count = 0
for char in sentence:
if char == " ": # Check if the character is a space
word_count += 1 # Increment the word count
# Add 1 to account for the last word (since we're counting spaces)
if sentence.strip() != "": # Check if the sentence is not empty
word_count += 1
return word_count

# Test the function


sentence = input("Enter a sentence: ")
print("Number of words:", count_words(sentence))

Output:

9. Replace a Character in a String Problem:


Replace all occurrences of a specific character with another character without using
replace().
Algorithm:
1. Loop through the string and build a new string.
2. If a character matches the target, replace it with the new character

Code:
def replace_character(input_string, target_char, new_char):
result_string = ""
for char in input_string:
if char == target_char:
result_string += new_char # Replace the target character with the new character
else:
result_string += char # Add non-target characters to the result
return result_string

# Test the function


input_string = input("Enter a string: ")
target_char = input("Enter a character to replace: ")
new_char = input("Enter a character to replace with: ")
print("String after replacement:", replace_character(input_string, target_char, new_char))
Output:

10. Find the Largest Word in a Sentence Problem:


Find the longest word in a given sentence.
Algorithm:
1. Loop through the sentence and manually extract words (based on spaces).
2. Keep track of the longest word encountered.

Code:
def find_longest_word(sentence):
longest_word = ""
current_word = ""
for char in sentence:
if char == " ": # Check if the character is a space
if len(current_word) > len(longest_word):
longest_word = current_word # Update the longest word
current_word = "" # Reset the current word
else:
current_word += char # Add characters to the current word
# Check the last word
if len(current_word) > len(longest_word):
longest_word = current_word
return longest_word

# Test the function


sentence = input("Enter a sentence: ")
print("Longest word:", find_longest_word(sentence))

Output:
11. Check if Two Strings are Anagrams Problem:
Check if two strings are anagrams (i.e., they contain the same characters in a different
order).
Algorithm:
1. Count the occurrences of each character in both strings.
2. If the counts match, the strings are anagrams.

Code:
from collections import Counter

def are_anagrams(str1, str2):


# Normalize the strings
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()

# Count character occurrences


count1 = Counter(str1)
count2 = Counter(str2)

# Compare counts
return count1 == count2

# Example usage
string1 = "listen"
string2 = "silent"
print(are_anagrams(string1, string2)) # Output: True

Output:

12. Remove Vowels from a String Problem:


Remove all vowels (a, e, i, o, u) from a given string.
Algorithm:
1. Loop through the string.
2. Append only non-vowel characters to a new string

Code:
def remove_vowels(input_string):
vowels = "aeiouAEIOU" # Include both lowercase and uppercase vowels
result = [] # Using a list for efficient string building
for char in input_string:
if char not in vowels:
result.append(char) # Append non-vowel characters

return ''.join(result) # Join the list into a string

# Example usage
original_string = "Hello World"
no_vowels_string = remove_vowels(original_string)
print(no_vowels_string) # Output: Hll Wrld

Output:

13. Find the First Non-Repeated Character Description:


Find the first non-repeated character in a string without using built-in methods.
Algorithm:
1. Create an empty string to hold characters that have been repeated.
2. Iterate through the string and keep track of seen characters.
3. Return the first character that has not been repeated.

Code:

def first_non_repeated_character(input_string):
seen = [] # To track characters that have been seen
repeated = [] # To track repeated characters

for char in input_string:


if char in seen:
if char not in repeated:
repeated.append(char) # Mark as repeated
else:
seen.append(char) # Mark as seen

# Find the first non-repeated character


for char in seen:
if char not in repeated:
return char
return None # Return None if all characters are repeated

# Example usage
original_string = "swiss"
result = first_non_repeated_character(original_string)
print(result) # Output: "w"

Output:

14. String Compression Description:


Compress a string by replacing consecutive repeated characters with the character
followed by the count.
Algorithm:
1. Initialize an empty string for the result and a counter for consecutive characters.
2. Iterate through the string, counting consecutive characters.
3. Append the character and its count to the result string.
Input: "aaabbbcccaa"
Output: a3b3c3a2

Code:
def string_compression(input_string):
if not input_string: # Handle empty input
return ""

result = [] # Use a list for efficient string concatenation


count = 1 # Start the count at 1

# Iterate through the string


for i in range(1, len(input_string)):
if input_string[i] == input_string[i - 1]:
count += 1 # Increment count for consecutive characters
else:
# Append the previous character and its count
result.append(input_string[i - 1])
result.append(str(count))
count = 1 # Reset count for the new character

# Handle the last character and its count


result.append(input_string[-1])
result.append(str(count))
return ''.join(result) # Join the list into a final string

# Example usage
original_string = "aaabbbcccaa"
compressed_string = string_compression(original_string)
print(compressed_string) # Output: a3b3c3a2

Output:

15. Remove All Occurrences of a Character Description:


Remove all occurrences of a specified character from a string without using built-in
methods.
Algorithm:
1. Initialize an empty string for the result.
2. Iterate through the original string.
3. Append each character to the result string unless it matches the specified character.
Input: "Hello, World!"
Output: Hell, Wrld!

Code:
def remove_character(input_string, char_to_remove):
result = "" # Initialize an empty string for the result

# Iterate through the original string


for char in input_string:
if char != char_to_remove: # Check if the character should be removed
result += char # Append non-matching characters to the result

return result # Return the modified string

# Example usage
original_string = "Hello, World!"
character_to_remove = 'o'
modified_string = remove_character(original_string, character_to_remove)
print(modified_string) # Output: Hell, Wrld!

Output:

You might also like