From 74d0e4a2a7c84d8309d13b4f34ea9ac48aac3676 Mon Sep 17 00:00:00 2001 From: Salini Palanisamy Date: Sun, 11 Dec 2022 14:31:55 -0500 Subject: [PATCH 1/5] Solution added for Python-Practice Assignment --- 12_09_practice.py | 180 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 168 insertions(+), 12 deletions(-) diff --git a/12_09_practice.py b/12_09_practice.py index 7914563..7adc331 100644 --- a/12_09_practice.py +++ b/12_09_practice.py @@ -1,29 +1,185 @@ -#Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". Example: make_it_big([-1, 3, 5, -5]) returns that same list, #changed to [-1, "big", "big", -5]. +#Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". +# Example: make_it_big([-1, 3, 5, -5]) returns that same list, #changed to [-1, "big", "big", -5]. -#Count Positives - Given a list of numbers, create a function to replace last value with number of positive values. Example, count_positives([-1,1,1,1]) changes list #to [-1,1,1,3] and returns it. (Note that zero is not considered to be a positive number). +def make_it_big(list1): + for index,element in enumerate(list1): + if element >= 0: + list1[index] = "big" -#SumTotal - Create a function that takes a list as an argument and returns the sum of all the values in the list. For example sum_total([1,2,3,4]) should return 10 + return list1 + + +change_result = make_it_big([-1,3,5,-5]) +print(change_result) + +#Count Positives - Given a list of numbers, create a function to replace last value with number of positive values. +# Example, count_positives([-1,1,1,1]) changes list #to [-1,1,1,3] and returns it. (Note that zero is not considered to be a positive number). + +def count_positives(list1): + count = 0 + for i in list1: + if i > 0: + count += 1 + list1[-1] = count + return list1 + +result = count_positives([-1,1,1,1]) +print(result) + + +#SumTotal - Create a function that takes a list as an argument and returns the sum of all the values in the list. +# For example sum_total([1,2,3,4]) should return 10 + +def sum_total(list1): + sum = 0 + for i in list1: + sum += i + return sum + +sum_result = sum_total([1,2,3,4]) +print(sum_result) + +#Average - Create a function that takes a list as an argument and returns the average of all the values in the list. +# For example multiples([1,2,3,4]) should return #2.5 + +def avg_value(list1): + sum = 0 + for i in list1: + sum += i + return sum/len(list1) + +sum_result = avg_value([1,2,3,4]) +print(sum_result) -#Average - Create a function that takes a list as an argument and returns the average of all the values in the list. For example multiples([1,2,3,4]) should return #2.5 #Length - Create a function that takes a list as an argument and returns the length of the list. For example length([1,2,3,4]) should return 4 -#Minimum - Create a function that takes a list as an argument and returns the minimum value in the list. If the passed list is empty, have the function return false. #For example minimum([1,2,3,4]) should return 1; minimum([-1,-2,-3]) should return -3. -# -#Maximum - Create a function that takes a list as an argument and returns the maximum value in the list. If the passed list is empty, have the function return false. #For example maximum([1,2,3,4]) should return 4; maximum([-1,-2,-3]) should return -1. +def length_of_list(list1): + return len(list1) + +result = length_of_list([1,2,3,4]) +print(result) + +#Minimum - Create a function that takes a list as an argument and returns the minimum value in the list. +# If the passed list is empty, have the function return false. #For example minimum([1,2,3,4]) should return 1; +# minimum([-1,-2,-3]) should return -3. + +def minimum(list1): + if len(list1) == 0: + return False + else: + min_value = list1[0] + for i in range(1,len(list1)): + if min_value > list1[i]: + min_value = list1[i] + return min_value + +a =minimum([1,2,3,4]) +print(a) + + +#Maximum - Create a function that takes a list as an argument and returns the maximum value in the list. +# If the passed list is empty, have the function return false. +# #For example maximum([1,2,3,4]) should return 4; maximum([-1,-2,-3]) should return -1. + +def maximum(list1): + if len(list1) == 0: + return False + else: + max_value = list1[0] + for i in range(1,len(list1)): + if max_value < list1[i]: + max_value = list1[i] + return max_value + +a =maximum([1,2,3,4]) +print(a) + -#Ultimateaalyze - Create a function that takes a list as an argument and returns a dictionary that has the sumTotal, average, minimum, maximum ad length of the list. -#ReverseList - Create a function that takes a list as a argument and return a list in a reversed order. Do this without creating a empty temporary list. For example #reverse([1,2,3,4]) should return [4,3,2,1]. This challenge is known to appear during basic technical interviews. +#Ultimateaalyze - Create a function that takes a list as an argument +# and returns a dictionary that has the sumTotal, average, minimum, maximum ad length of the list. -#Ispalindrome- Given a string, write a python function to check if it is palindrome or not. A string is said to be palindrome if the reverse of the string is the same as string. For example, “radar” is a palindrome, but “radix” is not a palindrome. +def list_content(list1): + if len(list1) == 0: + return False + else: + d = {} + d["sum"] = sum_total(list1) + d["average"] = avg_value(list1) + d["minimum"] = minimum(list1) + d["maxmimum"] = maximum(list1) + d["length"] = length_of_list(list1) + return d + +a = list_content([-1,2,0,-8,0,6]) +print(a) + + + +#ReverseList - Create a function that takes a list as a argument and return a list in a reversed order. +# Do this without creating a empty temporary list. For example #reverse([1,2,3,4]) should return [4,3,2,1]. +# This challenge is known to appear during basic technical interviews. + +def reverse_list(list1): + list1 = list1[::-1] + return list1 + + +a = reverse_list([1,2,3,4]) +print(a) + + + +#Ispalindrome- Given a string, write a python function to check if it is palindrome or not. +# A string is said to be palindrome if the reverse of the string is the same as string. +# For example, “radar” is a palindrome, but “radix” is not a palindrome. + +def palindrome(string1): + if(string1 == string1[::-1]): + print("The given string is Palindrome") + else: + print("The given string is not a Palindrome") + +palindrome("radax") #Fizzbuzz- Create a function that will print numbers from 1 to 100, with certain exceptions: #If the number is a multiple of 3, print “Fizz” instead of the number. #If the number is a multiple of 5, print “Buzz” instead of the number. #If the number is a multiple of 3 and 5, print “FizzBuzz” instead of the number. -#Fibonacci- The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, #starting from 0 and 1. That is, +def fizzbizz(): + for i in range(1,101): + if (i%3 == 0) and (i%5 == 0): + print(i , "FizzBuzz") + elif i%3 == 0: + print(i, "Fizz") + elif i%5 == 0: + print(i, "Buzz") + else: + print(i) +fizzbizz() + + +#Fibonacci- The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, +# such that each number is the sum of the two preceding ones, #starting from 0 and 1. That is, #F(0) = 0, F(1) = 1 #F(n) = F(n - 1) + F(n - 2), for n > 1. - #Create a function that accepts any number and will create a sequence based on the fibonacci sequence. \ No newline at end of file + #Create a function that accepts any number and will create a sequence based on the fibonacci sequence. + +def fibonacci(n): + first = 0 + second = 1 + + for i in range(n): + print(first) + third = first + second + first = second + second = third + +number_for_fibo = int(input("Enter Number : ")) +fibonacci(number_for_fibo) + + + + From a20390d4b26b7136f87178ab60543768572df3f8 Mon Sep 17 00:00:00 2001 From: Salini Palanisamy Date: Mon, 12 Dec 2022 23:14:57 -0500 Subject: [PATCH 2/5] Solutions_Generator_Lambda_Exercises --- Generator_Lambda_Exercises.py | 63 +++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Generator_Lambda_Exercises.py diff --git a/Generator_Lambda_Exercises.py b/Generator_Lambda_Exercises.py new file mode 100644 index 0000000..e87b5c0 --- /dev/null +++ b/Generator_Lambda_Exercises.py @@ -0,0 +1,63 @@ +prog_lang = [ + ('Python', 3.8), + ('Java', 13), + ('JavaScript', 2019), + ('Scala', 2.13) + ] + +#1. Sort the list by each language's version in ascending order. + +prog_lang.sort(key=lambda item:item[1]) +print(prog_lang) + +#2. Sort the list by the length of the name of each language in descending order. + +prog_lang.sort(key=lambda item:len(item[0]),reverse= True) +print(prog_lang) + +#3. Filter the list so that it only contains languages with 'a' in it. +print(list(filter(lambda item : "a" in item[0], prog_lang))) + +#4. Filter the list so that it only contains languages whose version is in integer form. +print(list(filter(lambda item : type(item[1]) == int, prog_lang))) + + +#5. Transform the list so that it contains the tuples in the form, ("language in all lower case", length of the language string) +print(list(map(lambda item : (item[0].lower(), len(item[0])),prog_lang))) + +#6. Generate a tuple in the form, ("All languages separated by commas", "All versions separated by commas") +a = tuple(map(lambda item : (item[0]),prog_lang)) +b = tuple(map(lambda item : (str(item[1])),prog_lang)) +print((' '.join(a), ' '.join(b))) + + +# 2. Create a generator, unique_letters that generates unique letters from +# the input string. It should generate the letters in the same order as +# from the input string. + +def unique_letter(name): + a = [] + for i in name: + if i not in a: + yield i + a.append(i) + +for letter in unique_letter("hello"): + print(letter, end =" ") +print() + +# 1. Create a generator, primes_gen that generates prime numbers +# starting from 2. + +def prime_gen(): + end = int(input("Enter Number :")) + for i in range(2, end): + for j in range(2,i): + if i%j == 0: + break + else: + yield i + +gen = prime_gen() +for _ in range(10): + print(next(gen), end =" ") From 12cfb91b7e4191adff4e7cb1ef90ea84ceeaa693 Mon Sep 17 00:00:00 2001 From: Salini Palanisamy Date: Wed, 14 Dec 2022 00:30:00 -0500 Subject: [PATCH 3/5] Soloutions_Added_Closures_Decorators --- Closures_Decorators_Solutions.py | 155 +++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 Closures_Decorators_Solutions.py diff --git a/Closures_Decorators_Solutions.py b/Closures_Decorators_Solutions.py new file mode 100644 index 0000000..12ccbaa --- /dev/null +++ b/Closures_Decorators_Solutions.py @@ -0,0 +1,155 @@ +from datetime import datetime +#1.Using a closure, create a function, multiples_of(n) which we can use to +# create generators that generate multiples of n less than a given +# number. + + +def multiples_of(n): + def inner(n1): + count = 1 + for _ in range(n1): + table1 = count * n + if table1 < n1: + yield table1 + count += 1 + return inner + +m3 = multiples_of(3) +m3_under30 = m3(30) +m7_under30 = multiples_of(7)(30) + +print(type(m3_under30)) +print(*m3_under30) +print(*m7_under30) + +print(50 * "#") +#1. make_upper – make every letter of a string returned from the decorated +# function uppercase. + + +def make_upper(func): + def wrapper(): + str1 = func() + return str1.upper() + return wrapper + + +@make_upper +def hello_world(): + return "hello young, good day!!" + +print(hello_world()) + +print(50 * "#") + +#2. print_func_name – print the name of the decorated function before +# executing the function. + +def print_func_name(func): + def wrapper(): + print("my_func is running...") + str1 = func() + return str1 + return wrapper + +@print_func_name +def my_func(): + print('Python is fun!!') + +my_func() +print(50 * "#") + + +#3. give_name(name) – concatenate the given name at the end of a string +# returned from the decorated function. + +def give_name(val): + def innerfunc(func): + def wrapper(): + return func() + " " + val + return wrapper + return innerfunc + +@give_name('Therasa') +def greeting(): + return 'Hello' + +print(greeting()) +print(50 * "#") + + +#4. print_input_type – print a data type of the input argument before +# executing the decorated function. + + +def print_input_type(func): + def wrapper(n): + str1 = func(n) + str2 = type(str1) + return f"The input data type is {str2} \n{str1}" + return wrapper + +@print_input_type +def square(n): + return n ** 2 + +print(square(3.5)) +print(50 * "#") + +#5. check_return_type(return_type) – check if the return type of the +# decorated function is return_type and print the result before executing +# the function. + +def check_return_type(val): + def innerfunc(func): + def wrapper(n): + value = func(n) + type_value = type(value) + if type_value == val: + return f"The return type is {type_value} \n{value}" + return f"Error!! \nThe return type is NOT {type_value} \n{value}" + return wrapper + return innerfunc + + + +@check_return_type(str) +def square(n): + return n**2 + +print(square(6)) +print(50 * "#") + +@check_return_type(float) +def square(n): + return n**2 + +print(square(2.9)) +print(50 * "#") + +#6. execute_log – write a function execution log on the log file. + +def execute_log(func): + def wrapper(*args): + time_value = datetime.now() + function_name = func.__name__ + function_output = func(*args) + return function_output,f"{time_value} {function_name}" + return wrapper + +@execute_log +def multiply(*nums): + mult = 1 + for n in nums: + mult *= n + return mult + + +@execute_log +def hello_world(): + return 'hello world!!' + +print(multiply(6,2,3)) +print(hello_world()) +print(multiply(2.2,4)) +print(hello_world()) From 26f871c1b8dbb374d99308c4771b899cb746ce78 Mon Sep 17 00:00:00 2001 From: Salini Palanisamy Date: Thu, 15 Dec 2022 16:26:12 -0500 Subject: [PATCH 4/5] Assignment work completed --- movies.xml | 130 ++++++++++++++++++++++++++++++++++++++++++++++++++ xml_round2.py | 73 ++++++++++++++++++++++++++++ 2 files changed, 203 insertions(+) create mode 100644 movies.xml create mode 100644 xml_round2.py diff --git a/movies.xml b/movies.xml new file mode 100644 index 0000000..9444554 --- /dev/null +++ b/movies.xml @@ -0,0 +1,130 @@ + + + + + DVD + 1981 + PG + + 'Archaeologist and adventurer Indiana Jones + is hired by the U.S. government to find the Ark of the + Covenant before the Nazis.' + + + + DVD,Online + 1984 + PG + None provided. + + + Blu-ray + 1985 + PG + Marty McFly + + + + + Online + 1992 + R + WhAtEvER I Want!!!?! + + + + dvd, digital + 2000 + PG-13 + Two mutants come to a private academy for their kind whose resident superhero team must + oppose a terrorist organization with similar powers. + + + + + + + DVD + 1979 + R + """"""""" + + + + + DVD + 1986 + PG13 + Funny movie about a funny guy + + + blue-ray + 2000 + Unrated + psychopathic Bateman + + + + + + + + DVD,VHS + 1966 + PG + What a joke! + + + + + DVD + 2010 + PG--13 + Emma Stone = Hester Prynne + + + DVD,digital,Netflix + 2011 + Unrated + Tim (Rudd) is a rising executive + who 'succeeds' in finding the perfect guest, + IRS employee Barry (Carell), for his boss' monthly event, + a so-called 'dinner for idiots,' which offers certain + advantages to the exec who shows up with the biggest buffoon. + + + + + + Online,VHS + 1984 + PG + Who ya gonna call? + + + + + Blu_Ray + 1991 + Unknown + Robin Hood slaying + + + + + + + DVD + 2000s + R + A former Roman General sets out to exact vengeance against the corrupt emperor who murdered his family and sent him into slavery. + + + VHS + 1992 + PG13 + NA. + + + + \ No newline at end of file diff --git a/xml_round2.py b/xml_round2.py new file mode 100644 index 0000000..57903c2 --- /dev/null +++ b/xml_round2.py @@ -0,0 +1,73 @@ +import xml.etree.ElementTree as ET + +tree= ET.parse(r'C:\Users\Learner_XZHCG223\Documents\movies.xml') +root= tree.getroot() + +#print(tree) +#print(ET.tostring(root, encoding = 'utf8').decode('utf8')) +#print(root.tag) #giving us the name of the element tag +#print(root.attrib) #giving us the element attributes in a dictionary +################blank dicitonary means no attributes +#print(len(root)) ##how many children the element has +#print([elem.tag for elem in root.iter()]) #gives me a list of all the elements + +for rating in root.iter('rating'): +# print(rating.text) + pass + + +for rating_pg in root.findall("./genre/decade/movie/[rating='PG']"): + #print(rating_pg.attrib) + pass + +# kkid= root.find("./genre/decade/movie[@title= 'THE KARATE KID']") +# kkid.attrib['title']= "The Karate Kid" +# print(kkid.attrib) + +anime_genre = ET.SubElement(root, 'genre') +# print(ET.tostring(root, encoding = 'utf8').decode('utf8')) +anime_genre.attrib['category']='Anime' + +# print(ET.tostring(anime_genre, encoding='utf8').decode('utf8')) + +adding_decade = root.find("./genre[@category= 'Anime']") + +new_decade= ET.SubElement(adding_decade, 'decade') +new_decade.attrib['years']= '2000s' + +add_movie = root.find("./genre[@category='Anime']/decade[@years = '2000s']") +new_movie = ET.SubElement(add_movie, 'movie') +new_movie.attrib['favorite'] = 'True' +new_movie.attrib['title'] = 'Gladiator' + +movie_path = root.find("./genre[@category='Anime']/decade[@years = '2000s']/movie[@title = 'Gladiator']") +new_format = ET.SubElement(movie_path, 'format') +new_format.attrib['multiple'] = 'No' +new_format.text = 'DVD' + +new_year = ET.SubElement(movie_path, 'year') +new_year.text = '2000s' + +new_rating = ET.SubElement(movie_path, 'rating') +new_rating.text = 'R' + +new_description = ET.SubElement(movie_path, 'description') +new_description.text = 'A former Roman General sets out to exact vengeance against the corrupt emperor who murdered his family and sent him into slavery.' + +tree.write(r"C:\Users\Learner_XZHCG223\Documents\movies.xml") + +tree = ET.parse(r"C:\Users\Learner_XZHCG223\Documents\movies.xml") +root = tree.getroot() + +batman = root.find("./genre/decade/movie[@title= 'Batman Returns']") +decade_path = root.find("./genre[@category='Anime']/decade[@years= '2000s']") +decade_path.append(batman) + +# dec1990= root.find("./genre[@category='Action']/decade[@years= '1990s']") +# dec1990.remove(batman) +# action_path = root.find("./genre[@category= 'Action']") + +# print(ET.tostring(root, encoding='utf8').decode('utf8')) + +tree.write(r"C:\Users\Learner_XZHCG223\Documents\movies.xml") + From 1afaeed2960e931571b7ccd1957edf4dc95a6c57 Mon Sep 17 00:00:00 2001 From: Salini Palanisamy Date: Mon, 2 Jan 2023 19:47:19 -0500 Subject: [PATCH 5/5] Regex_Exercises --- regex_excercises.ipynb | 1370 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1370 insertions(+) create mode 100644 regex_excercises.ipynb diff --git a/regex_excercises.ipynb b/regex_excercises.ipynb new file mode 100644 index 0000000..1429613 --- /dev/null +++ b/regex_excercises.ipynb @@ -0,0 +1,1370 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "id": "lbrLwTw4r9jM" + }, + "outputs": [], + "source": [ + "import re" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "mtZQDWxxos3J" + }, + "source": [ + "# 30 REGULAR EXPRESSION EXERCISES!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6jEYHJH3os3Q" + }, + "source": [ + "Regex, you never know when they might come in handy. It's one of the \"good programmer\"'s fundamental yet a few people actually masters them.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "id": "ghj1l7sQos3R", + "trusted": true + }, + "outputs": [], + "source": [ + "import re" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "_tO-OHUBos3T" + }, + "source": [ + "1) Write a Python program to check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9)." + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "cXaMTykzos3V", + "outputId": "a73c9558-3ac4-44e9-ad0f-685a8f627983", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "False\n" + ] + } + ], + "source": [ + "# Solution\n", + "def is_allowed_specific_char(string):\n", + " # Define a regex pattern\n", + " pattern = r'[a-zA-Z0-9]'\n", + " # Use the pattern to search for ....\n", + " a = re.search(pattern, string)\n", + " if a!= None:\n", + " return True\n", + " else:\n", + " return False\n", + " \n", + " \n", + "print(is_allowed_specific_char(\"ABCDEFabcdef123450\")) # True\n", + "print(is_allowed_specific_char(\"*&%@#!}{\")) # False" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "2oae-B8tos3W" + }, + "source": [ + "2) Write a Python program that matches a string that has an a followed by zero or more b's" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 69, + "metadata": { + "id": "1LHEOOMkos3X", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found a match!\n", + "Found a match!\n", + "Found a match!\n", + "Not Matched\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " pattern = r\"ab*?\"\n", + " a = re.search(pattern, text)\n", + " # print(a)\n", + " if a:\n", + " return \"Found a match!\"\n", + " else:\n", + " return \"Not Matched\"\n", + "\n", + "print(text_match(\"ac\")) # Found a match!\n", + "print(text_match(\"abc\")) # Found a match!\n", + "print(text_match(\"abbc\")) # Found a match!\n", + "print(text_match(\"bbc\")) # Not matched" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "AQRTCmJZos3Z" + }, + "source": [ + "3) Write a Python program that matches a string that has an a followed by one or more b's" + ] + }, + { + "cell_type": "code", + "execution_count": 70, + "metadata": { + "id": "H1X2NPQYos3a", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found a match!\n", + "Found a match!\n", + "Not Matched\n", + "Not Matched\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " pattern = r\"ab+?\"\n", + " a = re.search(pattern, text)\n", + " # print(a)\n", + " if a:\n", + " return \"Found a match!\"\n", + " else:\n", + " return \"Not Matched\"\n", + "\n", + "print(text_match(\"ab\")) # Found a match!\n", + "print(text_match(\"abc\")) # Found a match!\n", + "print(text_match(\"ac\")) # Not matched\n", + "print(text_match(\"bbc\")) # Not matched" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "E902uTcRos3a" + }, + "source": [ + "4) Write a Python program that matches a string that has an a followed by zero or one 'b'" + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "metadata": { + "id": "xeva0fRNos3b", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found a match!\n", + "Found a match!\n", + "Found a match!\n", + "Found a match!\n", + "Found a match!\n", + "Not Matched\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " pattern = r\"ab*?\"\n", + " a = re.search(pattern, text)\n", + " # print(a)\n", + " if a:\n", + " return \"Found a match!\"\n", + " else:\n", + " return \"Not Matched\"\n", + " \n", + "print(text_match(\"ab\")) # Found a match!\n", + "print(text_match(\"abc\")) # Found a match!\n", + "print(text_match(\"abbc\")) # Found a match!\n", + "print(text_match(\"aabbc\")) # Found a match!\n", + "print(text_match(\"ac\")) # Found a match!\n", + "print(text_match(\"bbc\")) # Not matched" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "whnPaW2kos3c" + }, + "source": [ + "5) Write a Python program that matches a string that has an a followed by three 'b'" + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "metadata": { + "id": "0c_7S3h_os3d", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found a match!\n", + "Found a match!\n", + "Not Matched\n", + "Not Matched\n", + "Not Matched\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " pattern = r\"a*b{3}?\"\n", + " a = re.search(pattern, text)\n", + " # print(a)\n", + " if a:\n", + " return \"Found a match!\"\n", + " else:\n", + " return \"Not Matched\"\n", + "\n", + "print(text_match(\"abbb\")) # Found a match!\n", + "print(text_match(\"aabbbbbc\")) # Found a match!\n", + "print(text_match(\"aabbc\")) # Not matched\n", + "print(text_match(\"ac\")) # Not matched\n", + "print(text_match(\"bbc\")) # Not matched" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "V4AsjJiCos3e" + }, + "source": [ + "6) Write a Python program that matches a string that has an a followed by two to three 'b'." + ] + }, + { + "cell_type": "code", + "execution_count": 78, + "metadata": { + "id": "VjA5CXi1os3e", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Not Matched\n", + "Found a match!\n", + "Found a match!\n", + "Not Matched\n", + "Not Matched\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " pattern = r\"ab{2,3}\"\n", + " a = re.search(pattern, text)\n", + " # print(a)\n", + " if a:\n", + " return \"Found a match!\"\n", + " else:\n", + " return \"Not Matched\"\n", + "\n", + "print(text_match(\"ab\")) # Not matched\n", + "print(text_match(\"aabbbbbc\")) # Found a match!\n", + "print(text_match(\"aabbc\")) # Found a match!\n", + "print(text_match(\"ac\")) # Not matched\n", + "print(text_match(\"bbc\")) # Not matched" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "kX7sLRavos3f" + }, + "source": [ + "7) Write a Python program to find sequences of lowercase letters joined with a underscore." + ] + }, + { + "cell_type": "code", + "execution_count": 83, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "rbxk35n7os3g", + "outputId": "3ddca986-1bd6-45f1-902c-eee85e8853e8", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found a match!\n", + "Not Matched\n", + "Not Matched\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " pattern = r\"^[a-z]*_[a-z]+$\"\n", + " a = re.search(pattern, text)\n", + " # print(a)\n", + " if a:\n", + " return \"Found a match!\"\n", + " else:\n", + " return \"Not Matched\"\n", + "\n", + "print(text_match(\"aab_cbbbc\")) # Found a match!\n", + "print(text_match(\"aab_Abbbc\")) # Not matched\n", + "print(text_match(\"Aaab_abbbc\")) # Not matched" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "H4sat-Rfos3g" + }, + "source": [ + "8) Write a Python program to find the sequences of one upper case letter followed by lower case letters." + ] + }, + { + "cell_type": "code", + "execution_count": 84, + "metadata": { + "id": "oeUiVHGVos3h", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Not Matched\n", + "Found a Match\n", + "Found a Match\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " result = re.search(r'[A-Z][a-z]+', text)\n", + " if result is None:\n", + " return 'Not Matched'\n", + " else: \n", + " return 'Found a Match' \n", + "\n", + "\n", + "print(text_match(\"aab_cbbbc\")) # Not matched\n", + "print(text_match(\"aab_Abbbc\")) # Found a match!\n", + "print(text_match(\"Aaab_abbbc\")) # Found a match!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "RgNBl7aEos3h" + }, + "source": [ + "9) Write a Python program that matches a string that has an 'a' followed by anything, ending in 'b'." + ] + }, + { + "cell_type": "code", + "execution_count": 85, + "metadata": { + "id": "YbCsos7Jos3i", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Not Matched\n", + "Not Matched\n", + "Found a Match\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " result = re.match(r'^a.*?b$', text)\n", + " if result is None:\n", + " return 'Not Matched'\n", + " else:\n", + " return 'Found a Match' \n", + "\n", + "print(text_match(\"aabbbbd\")) # Not matched\n", + "print(text_match(\"aabAbbbc\")) # Not matched\n", + "print(text_match(\"accddbbjjjb\")) # Found a match!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0oHZnx0Gos3i" + }, + "source": [ + "10) Write a Python program that matches a word at the beginning of a string." + ] + }, + { + "cell_type": "code", + "execution_count": 86, + "metadata": { + "id": "1tlZiGMaos3j", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found a match!\n", + "Not Matched\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " pattern = r\"[^ ]\"\n", + " a = re.match(pattern, text)\n", + " # print(a)\n", + " if a:\n", + " return \"Found a match!\"\n", + " else:\n", + " return \"Not Matched\"\n", + "\n", + "print(text_match(\"The quick brown fox jumps over the lazy dog.\")) # Found a match!\n", + "print(text_match(\" The quick brown fox jumps over the lazy dog.\")) # Not matched" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "mG0jspZFos3j" + }, + "source": [ + "11) Write a Python program that matches a word at the end of string, with optional punctuation." + ] + }, + { + "cell_type": "code", + "execution_count": 88, + "metadata": { + "id": "cmhnhbZnos3j", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found a Match\n", + "Not Matched\n", + "Not Matched\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " result = re.search(r'\\w+\\S*$', text)\n", + " if result is None:\n", + " return 'Not Matched'\n", + " else: \n", + " return 'Found a Match'\n", + "\n", + "print(text_match(\"The quick brown fox jumps over the lazy dog.\")) # Found a match!\n", + "print(text_match(\"The quick brown fox jumps over the lazy dog. \")) # Not matched\n", + "print(text_match(\"The quick brown fox jumps over the lazy dog \")) # Not matched" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "DBgbyYHXos3k" + }, + "source": [ + "12) Write a Python program that matches a word containing 'z'" + ] + }, + { + "cell_type": "code", + "execution_count": 89, + "metadata": { + "id": "WxuMRyCbos3k", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found a match!\n", + "Not matched\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " if \"z\" in text:\n", + " return \"Found a match!\"\n", + " else:\n", + " return \"Not matched\"\n", + "\n", + " \n", + "print(text_match(\"The quick brown fox jumps over the lazy dog.\")) # Found a match!\n", + "print(text_match(\"Python Exercises.\")) # Not matched" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "V_9_nk8Kos3l" + }, + "source": [ + "13) Write a Python program that matches a word containing 'z', not at the start or end of the word." + ] + }, + { + "cell_type": "code", + "execution_count": 90, + "metadata": { + "id": "VEhCCh7yos3l", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found a Match\n", + "Not Matched\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " result = re.search(r'\\Bz\\B', text)\n", + " if result is None:\n", + " return 'Not Matched'\n", + " else: \n", + " return 'Found a Match' \n", + "\n", + "print(text_match(\"The quick brown fox jumps over the lazy dog.\")) # Found a match!\n", + "print(text_match(\"Python Exercises.\")) # Not matched" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "L0lV07OCos3m" + }, + "source": [ + "14) Write a Python program to match a string that contains only upper and lowercase letters, numbers, and underscores." + ] + }, + { + "cell_type": "code", + "execution_count": 91, + "metadata": { + "id": "E9NcoWDhos3m", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Not Matched\n", + "Found a Match\n" + ] + } + ], + "source": [ + "# Solution\n", + "def text_match(text):\n", + " result = re.search(r'^[A-Za-z0-9_]*$', text)\n", + " if result is None:\n", + " return 'Not Matched'\n", + " else: \n", + " return 'Found a Match' \n", + "\n", + "print(text_match(\"The quick brown fox jumps over the lazy dog.\")) # Not matched\n", + "print(text_match(\"Python_Exercises_1\")) # Found a match!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "EvKJ8WOoos3n" + }, + "source": [ + "15) Write a Python program where a string will start with a specific number. " + ] + }, + { + "cell_type": "code", + "execution_count": 92, + "metadata": { + "id": "nWp5QysTos3n", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "False\n" + ] + } + ], + "source": [ + "# Solution\n", + "def match_num(string):\n", + " patt = re.match(r'^5', string)\n", + " if patt is None:\n", + " return False\n", + " else: \n", + " return True \n", + " \n", + " \n", + "print(match_num('5-2345861')) # True\n", + "print(match_num('6-2345861')) # False" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "r_I1cbvios3t" + }, + "source": [ + "16) Write a Python program to remove leading zeros from an IP address" + ] + }, + { + "cell_type": "code", + "execution_count": 93, + "metadata": { + "id": "cRLX4hc3os3u", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "216.8.94.196\n" + ] + } + ], + "source": [ + "# Solution\n", + "def rewrite_ip(ip):\n", + " # your code here\n", + " result = re.sub(r'\\.0*', '.', ip)\n", + " if result is None:\n", + " return ''\n", + " else: \n", + " return result \n", + "\n", + "ip = \"216.08.094.196\"\n", + "string = rewrite_ip(ip)\n", + "print(string) # 216.8.94.196" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ZCn9r3o2os3u" + }, + "source": [ + "17) Write a Python program to check for a number at the end of a string." + ] + }, + { + "cell_type": "code", + "execution_count": 94, + "metadata": { + "id": "Q5t9U6n8os3u", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n", + "True\n" + ] + } + ], + "source": [ + "# Solution\n", + "def end_num(string):\n", + " result = re.search(r'\\d$', string)\n", + " if result is None:\n", + " return False\n", + " else: \n", + " return True\n", + "\n", + "print(end_num('abcdef')) # False\n", + "print(end_num('abcdef6')) # True" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0tM4eW8Wos3v" + }, + "source": [ + "18) Write a Python program to search the numbers (0-9) of length between 1 to 3 in a given string. " + ] + }, + { + "cell_type": "code", + "execution_count": 95, + "metadata": { + "id": "7QGwzVxDos3v", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number of length 1 to 3\n", + "1\n", + "12\n", + "13\n", + "345\n" + ] + } + ], + "source": [ + "# Solution\n", + "def print_digits(string):\n", + " result = re.finditer(r'([0-9]{1,3})', string)\n", + " if result is None:\n", + " return 'Match not Found'\n", + " else: \n", + " print('Number of length 1 to 3') \n", + " for text in result:\n", + " print(text.group(0))\n", + "\n", + "string = \"Exercises number 1, 12, 13, and 345 are important\"\n", + "print_digits(string)\n", + "# Number of length 1 to 3\n", + "# 1\n", + "# 12\n", + "# 13\n", + "# 345" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "43nNb7d_os3v" + }, + "source": [ + "19) Write a Python program to search some literals strings in a string. \n", + "Sample text : 'The quick brown fox jumps over the lazy dog.'\n", + "Searched words : 'fox', 'dog', 'horse'" + ] + }, + { + "cell_type": "code", + "execution_count": 98, + "metadata": { + "id": "KIVHxWN9os3w", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Searching for \"fox\" in \"The quick brown fox jumps over the lazy dog.\" ->\n", + "Matched!\n", + "Searching for \"dog\" in \"The quick brown fox jumps over the lazy dog.\" ->\n", + "Matched!\n", + "Searching for \"horse\" in \"The quick brown fox jumps over the lazy dog.\" ->\n", + "Not Matched\n" + ] + } + ], + "source": [ + "# Solution\n", + "def print_match(patterns, text):\n", + " for string in patterns:\n", + " result = re.search(string, text) \n", + " print('Searching for \"{}\" in \"{}\" ->'.format(string, text))\n", + " if result is None:\n", + " print(\"Not Matched\")\n", + " else: \n", + " print(\"Matched!\") \n", + "\n", + "\n", + "patterns = [ 'fox', 'dog', 'horse' ]\n", + "text = 'The quick brown fox jumps over the lazy dog.'\n", + "print_match(patterns, text)\n", + "# Searching for \"fox\" in \"The quick brown fox jumps over the lazy dog.\" ->\n", + "# Matched!\n", + "# Searching for \"dog\" in \"The quick brown fox jumps over the lazy dog.\" ->\n", + "# Matched!\n", + "# Searching for \"horse\" in \"The quick brown fox jumps over the lazy dog.\" ->\n", + "# Not Matched!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "XjdROmMhos3w" + }, + "source": [ + "20) Write a Python program to search a literals string in a string and also find the location within the original string where the pattern occurs\n", + "\n", + "Sample text : 'The quick brown fox jumps over the lazy dog.'\n", + "Searched words : 'fox'" + ] + }, + { + "cell_type": "code", + "execution_count": 99, + "metadata": { + "id": "vWViImYios3w", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found \"fox\" in \"The quick brown fox jumps over the lazy dog.\" from 16 to 19\n" + ] + } + ], + "source": [ + "# Solution\n", + "def print_match_location(pattern, text):\n", + " result = re.search(pattern, text)\n", + " if result is None:\n", + " result = ''\n", + " print('Not Found \"{}\" in \"{}\"'.format(pattern, text))\n", + " else: \n", + " result = result.span() \n", + " print('Found \"{}\" in \"{}\" from {} to {}'.format(pattern, text, result[0], result[1]))\n", + "\n", + "pattern = 'fox'\n", + "text = 'The quick brown fox jumps over the lazy dog.'\n", + "print_match_location(pattern, text)\n", + "# Found \"fox\" in \"The quick brown fox jumps over the lazy dog.\" from 16 to 19" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "lLRotk-Oos3x" + }, + "source": [ + "21) Write a Python program to find the substrings within a string.\n", + "\n", + "Sample text :\n", + "\n", + "'Python exercises, PHP exercises, C# exercises'\n", + "\n", + "Pattern :\n", + "\n", + "'exercises'\n", + "\n", + "Note: There are three instances of exercises in the input string." + ] + }, + { + "cell_type": "code", + "execution_count": 100, + "metadata": { + "id": "XU8613rTos3x", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found \"exercises\"\n", + "Found \"exercises\"\n", + "Found \"exercises\"\n" + ] + } + ], + "source": [ + "# Solution\n", + "def find_all_matches(pattern, text):\n", + " result = re.findall(pattern, text)\n", + " if len(result) == 0:\n", + " print('Not Found \"{}\"'.format(pattern))\n", + " else: \n", + " for string in result:\n", + " print('Found \"{}\"'.format(pattern))\n", + "\n", + "text = 'Python exercises, PHP exercises, C# exercises'\n", + "pattern = 'exercises'\n", + "find_all_matches(pattern, text)\n", + "# Found \"exercises\"\n", + "# Found \"exercises\"\n", + "# Found \"exercises\"" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "uvAY6v7Oos3x" + }, + "source": [ + "22) Write a Python program to find the occurrence and position of the substrings within a string." + ] + }, + { + "cell_type": "code", + "execution_count": 101, + "metadata": { + "id": "UFg6rXJnos3y", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found \"exercises\" at 7:16\n", + "Found \"exercises\" at 22:31\n", + "Found \"exercises\" at 36:45\n" + ] + } + ], + "source": [ + "# Solution\n", + "def find_all_matches_location(pattern, text):\n", + " result = re.finditer(pattern, text)\n", + " if result is None:\n", + " result = ''\n", + " print('Not Found \"{}\" in \"{}\"'.format(pattern, text))\n", + " else: \n", + " for string in result:\n", + " result1 = string.span() \n", + " print('Found \"{}\" at {}:{}'.format(pattern, result1[0], result1[1]))\n", + "\n", + "\n", + "text = 'Python exercises, PHP exercises, C# exercises'\n", + "pattern = 'exercises'\n", + "find_all_matches_location(pattern, text)\n", + "# Found \"exercises\" at 7:16\n", + "# Found \"exercises\" at 22:31\n", + "# Found \"exercises\" at 36:45" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Sb3zKxE-os3y" + }, + "source": [ + "23) Write a Python program to replace whitespaces with an underscore and vice versa." + ] + }, + { + "cell_type": "code", + "execution_count": 102, + "metadata": { + "id": "nUxR5Xvjos3z", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Python_Exercises\n", + "Python Exercises\n" + ] + } + ], + "source": [ + "text = 'Python Exercises'\n", + "\n", + "# Your code\n", + "text = re.sub(r'\\s', '_', text)\n", + "\n", + "print(text) # Python_Exercises\n", + "\n", + "\n", + "# Your code\n", + "text = re.sub('_', ' ', text)\n", + "\n", + "print(text) # Python Exercises" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "grqoW-pgos3z" + }, + "source": [ + "24) Write a Python program to extract year, month and date from a an url. " + ] + }, + { + "cell_type": "code", + "execution_count": 103, + "metadata": { + "id": "K2-pacqmos3z", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[('2016', '09', '02')]\n" + ] + } + ], + "source": [ + "# Solution\n", + "def extract_date(url):\n", + " result = re.findall(r'/(\\d{4})/(\\d{1,2})/(\\d{1,2})/', url)\n", + " if len(result) == 0:\n", + " return 'No date Found in \"{}\"'.format(url)\n", + " else: \n", + " return result\n", + " \n", + "url1= \"https://www.washingtonpost.com/news/football-insider/wp/2016/09/02/odell-beckhams-fame-rests-on-one-stupid-little-ball-josh-norman-tells-author/\"\n", + "print(extract_date(url1)) # [('2016', '09', '02')]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "gyD5AZW7os3z" + }, + "source": [ + "25) Write a Python program to convert a date of yyyy-mm-dd format to dd-mm-yyyy format." + ] + }, + { + "cell_type": "code", + "execution_count": 104, + "metadata": { + "id": "bo-jpYqZos30", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Original date in YYY-MM-DD Format: 2026-01-02\n", + "New date in DD-MM-YYYY Format: 02-01-2026\n" + ] + } + ], + "source": [ + "# Solution\n", + "def change_date_format(dt):\n", + " return re.sub(r'(\\d{4})-(\\d{1,2})-(\\d{1,2})', r'\\3-\\2-\\1', dt1) \n", + "\n", + "dt1 = \"2026-01-02\"\n", + "print(\"Original date in YYY-MM-DD Format: \",dt1) # Original date in YYY-MM-DD Format: 2026-01-02\n", + "print(\"New date in DD-MM-YYYY Format: \",change_date_format(dt1)) # New date in DD-MM-YYYY Format: 02-01-2026" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "IQ2SNL-gos30" + }, + "source": [ + "26) Write a Python program to match if any words from a list of words starting with letter 'P'." + ] + }, + { + "cell_type": "code", + "execution_count": 105, + "metadata": { + "id": "2hP4Twe0os31", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "('Python', 'PHP')\n" + ] + } + ], + "source": [ + "# Sample strings.\n", + "def print_words_starting_with_P(words):\n", + " for string in words:\n", + " result = re.match(\"(P\\w+)\\W(P\\w+)\", string)\n", + " if result:\n", + " print(result.groups())\n", + "\n", + "words = [\"Python PHP\", \"Java JavaScript\", \"c c++\"]\n", + "print_words_starting_with_P(words) # ('Python', 'PHP')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "MEUMKMn0os31" + }, + "source": [ + "27) Write a Python program to separate and print the numbers of a given string." + ] + }, + { + "cell_type": "code", + "execution_count": 106, + "metadata": { + "id": "xG8c9PtUos32", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "10\n", + "20\n", + "30\n" + ] + } + ], + "source": [ + "# Solution\n", + "def print_all_numbers(text):\n", + " result = re.split('\\D+', text)\n", + " for string in result:\n", + " print(string)\n", + "# Sample string.\n", + "text = \"Ten 10, Twenty 20, Thirty 30\"\n", + "print_all_numbers(text)\n", + "# 10\n", + "# 20\n", + "# 30" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "krdKu3Mvos32" + }, + "source": [ + "28) Write a Python program to find all words starting with 'a' or 'e' in a given string." + ] + }, + { + "cell_type": "code", + "execution_count": 107, + "metadata": { + "id": "3hsR5278os32", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['example', 'eates', 'an', 'ayList', 'apacity', 'elements', 'elements', 'are', 'en', 'added', 'ayList', 'and', 'ayList', 'ed', 'accordingly']\n" + ] + } + ], + "source": [ + "# Solution\n", + "def get_all_words_containing_a_or_e(text):\n", + " return (re.findall (r'[ae]\\w+', text))\n", + "\n", + "\n", + "# Input.\n", + "text = \"The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly.\"\n", + "print(get_all_words_containing_a_or_e(text))\n", + "# ['example', 'eates', 'an', 'ayList', 'apacity', 'elements', 'elements', 'are', 'en', 'added', 'ayList', 'and', 'ayList', 'ed', 'accordingly']" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "CxfIZ5o9os33" + }, + "source": [ + "29) Write a Python program to separate and print the numbers and their position of a given string." + ] + }, + { + "cell_type": "code", + "execution_count": 108, + "metadata": { + "id": "XIuiRvmAos33", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "50\n", + "Index position: 62\n" + ] + } + ], + "source": [ + "# Solution\n", + "def print_all_numbers_and_their_position(text):\n", + " result = re.finditer(r'\\d+', text)\n", + " for string in result:\n", + " print(string.group(0))\n", + " print(\"Index position:\", string.start())\n", + " \n", + "\n", + "# Input.\n", + "text = \"The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly.\"\n", + "print_all_numbers_and_their_position(text)\n", + "# 50\n", + "# Index position: 62" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "JguO0fUjos34" + }, + "source": [ + "30) Write a Python program to abbreviate 'Road' as 'Rd.' in a given string." + ] + }, + { + "cell_type": "code", + "execution_count": 109, + "metadata": { + "id": "VJE1Xm2Bos34", + "trusted": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "21 Ramkrishna Rd.\n" + ] + } + ], + "source": [ + "# Solution\n", + "def abbreviate_road(street):\n", + " return re.sub(r'Road', 'Rd.', street)\n", + "\n", + "street = '21 Ramkrishna Road'\n", + "\n", + "print(abbreviate_road(street)) # 21 Ramkrishna Rd.\n" + ] + } + ], + "metadata": { + "colab": { + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.8" + }, + "vscode": { + "interpreter": { + "hash": "4c200c4a165fd8d2fb1310c0c6ae97ff25c524357f0619d7e6a6f623b01384d4" + } + } + }, + "nbformat": 4, + "nbformat_minor": 0 +}