Question

In: Computer Science

Python Questions: Q1. list_1= ['wind', 'spring', 'summer', 'purse', 'great', 'sports'] Use re.search() in the re package...

Python Questions:

Q1. list_1= ['wind', 'spring', 'summer', 'purse', 'great', 'sports']

Use re.search() in the re package and list comprehension to find all words in list_1 that does not contain the letter "r".

Q2.

str_1= '''I live in a room by the sea,
where the view is great and the food is free.
Some of the tenants come and go.
Some I eat, if they're too slow.
One end of me is firmly locked.
The other end just gently rocks.
I live in a room by the sea.
It's perfect for an anemone. '''
Use re.search() in the re package to find all lines that does not start with the letter "s", "S", or "I".

Q3. list_1= ['attitudes', 'ab\nchild', '2!apologies', 'echess', 'fly\n', 'cheer']
Use list comprehension and functions in re package to filter all elements that start with "ch" or end with "es".

Q4. Remove everything from the first occurrence of "e" till end of the string, using the function .sub() from the "re" package

str_1 = 'Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.'

Solutions

Expert Solution

Before we start coding we have to know the basics of re

.   (dot) represents any character except \n

^ represents starts with ex: '^h' will satisfy "helloworld"

$ represents  ends with ex: 'i$' will satisfy "hii"

| represents or ex: '^h|o$'  will satisfy for both "hi" and "hello"

*   Zero or more occurrences

ex: '.*' will satisfy any string

here ->

  • . means one character
  • * means any no of times


So ( .* ) finally represents any number of characters.


List comprehension in python :

  • [ ] this symbol represents list type and here the contents placed inside these symbols directly converted to list type
  • [ i for i in range(5) ] this statement generates integers from 0 to 5
  • 0 1 2 3 4

Solutions

Q1

import re

list_1= ['wind', 'spring', 'summer', 'purse', 'great', 'sports']

print([i for i in list_1 if not re.search('r',i)])


[ i for i in list_1 if not re.search('r',i) ]
this statement is equivalent to

for word in list_1:

if not re.search('r',word): #if r is not found in word

print(word)

Hope you understand how list comprehension internally works!

Q2 Solution

import re

str_1= '''I live in a room by the sea,
where the view is great and the food is free.
Some of the tenants come and go.
Some I eat, if they're too slow.
One end of me is firmly locked.
The other end just gently rocks.
I live in a room by the sea.
It's perfect for an anemone. '''

print(*[line for line in str_1.split('\n') if not re.search('^S|^s|^I',line)])


#^s|^s|^I means if line starts with s or S or I
#str_1.split means total string is splitted into lines and matches with re

Q3 Solution

import re

list_1= ['attitudes', 'ab\nchild', '2!apologies', 'echess', 'fly\n', 'cheer']

print([word for word in list_1 if re.match('^ch|.*es$',word)])


#re will match word startswith ch  ^ch  | or ends with es .*es$

Q4 Solution

import re

str_1 = 'Two things are infinite: the universe and human stupidity; and I\'m not sure about the universe.'
        
print("".join([str_1[i] for i in range(re.search('e',str_1).start())]))


#start() method in re search will say the first position that e appears
#''.join will join all the characters obtained in the list comprehension
#we will traverse through str_1 and prints upto first appearance of character e 


Thank You
post your doubts in comment section so that i can modify answer if u need
please support by giving a thumbs up


Related Solutions

Please use the python 3.7 for this assigments Q1 Write a program that accepts the lengths...
Please use the python 3.7 for this assigments Q1 Write a program that accepts the lengths of three sides of a triangle as inputs. The program output should indicate whether or not the triangle is an equilateral triangle. Q2 Write a program that accepts the lengths of three sides of a triangle as inputs. The program output should indicate whether or not the triangle is a right triangle. Recall from the Pythagorean theorem that in a right triangle, the square...
Type the Python code for all the questions. 1 2 Q1: Using DataFrame, with Figure 1...
Type the Python code for all the questions. 1 2 Q1: Using DataFrame, with Figure 1 data, store the hypermarket data for rows and columns. Display the output as shown in Figure 1. 0 ITEMS NAME DISCOUNT 1 Grocery Rice 56 2 Electronics Mobile 25% 3 Food Apple 30% Figure 1 Q2: Update and display the "Rice" discount from 5% to 10%. Your output should be like Figure 2 now. 1 2 0 ITEMS NAME DISCOUNT 1 Grocery Rice 108...
1) Use Python to answer the below questions. a) What is the output of the following...
1) Use Python to answer the below questions. a) What is the output of the following python code?                         def function(x):                              return x * 5                        print(func(7) * func(5)) b) What is the output of the following code fragment?     required_course = "Programming", "Security", "Cybersecurity"         a,b,c = required_course         print(b)
USE PYTHON-LIST Q1 - You need to keep track of book titles. Write code using function(s)...
USE PYTHON-LIST Q1 - You need to keep track of book titles. Write code using function(s) that will allow the user to do the following. 1. Add book titles to the list. 2. Delete book titles anywhere in the list by value. 3. Delete a book by position. Note: if you wish to display the booklist as a vertical number booklist , that is ok (that is also a hint) 4. Insert book titles anywhere in the list. 5. Clear...
Use python simulations to answer the following questions. You should be able to make minor modifications...
Use python simulations to answer the following questions. You should be able to make minor modifications to previous simulations to estimate these probabilities: 1) Suppose the pocket contains one fair coin and one two-headed coin. Find the approximate probability that the coin is fair given that it came up heads on the first flip. 2) Suppose the pocket contains one fair coin and one two-headed coin. Find the approximate probability that the coin is fair given that it came up...
Use Python, please type. A multiple-choice quiz with 5 questions. Each question has 4 possible answers...
Use Python, please type. A multiple-choice quiz with 5 questions. Each question has 4 possible answers labelled A, B, C and D.    After displaying the first question and the 4 possible answers, the user is asked to enter their choice. If their choice is correct, add 1 to the score, then display the next question and its 4 possible answers. At the end of the quiz, display their score out of 5, their score as a percentage, and if...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT