Question

In: Computer Science

Please read the following restrictions before answering the question below: Restrictions: – Do not import any...

Please read the following restrictions before answering the question below:

  • Restrictions:

    • Do not import any modules other than math and check.

    • – You are always allowed to define your own helper/wrapper functions. Do not use Python constructs from later modules (e.g. dictionaries, zip, anything with sets or enumerators, list comprehension, commands continue or break).

    • – Abstract list functions and recursion will not be allowed.

    • Use only the functions and methods as follows:

      • ∗ abs, len, max, min, sum, range and sorted

      • ∗ Any method or constant in the math module

      • ∗ Type casting including int(), str(), float(), bool(), list()

      • ∗ The command type()

      • ∗ Any basic arithmetic operation (including +, -, *, /, //, %, **)

      • ∗ String or list slicing and indexing as well as string or list operations using the operators above.

      • ∗ Any string or list methods including the in operator.

      • ∗ input and print as well as the formatting parameter end and method format. Note that all prompts must match exactly in order and so ensure that you do not alter these prompts.

      • ∗ Loops, specifically for and while loops.

    • Do not mutate any passed parameters unless instructions dictate otherwise. You may mutate lists you have created however.

    • – While you may use global constants in your solutions, do not use global variables for anything other than testing.

QUESTION:

Write a function

string_clean(s)

which consumes a string s and returns a string. The returned string should be similar to the consumed string, but every time a digit appears in s, a number of characters corresponding to that digit (including the digit itself) should be removed from the returned string. For instance, string_clean("car4pent3ers") => "carts". This should be done left-to-right, and if removing one digit’s substring removes another digit, then that second digit shouldn’t be considered. For instance, string_clean("29Hello!")=> "Hello!". The string must not have any digits that would require removing a substring past the end of the string. This function should run in at worst O(n) time.

Note (and hint!): The join method of strings is O(n), where n is the length of the list, assuming each element of the list is of length O(1).

Samples:

string_clean("") => ""
string_clean("I love CS116!*!*!?") => "I love CS?" string_clean("6Hello") => ""
string_clean("I have 0 apples and 39 pears") =>

"I have 0 apples and pears"

Solutions

Expert Solution

Below are the screenshots of code & output:

The string_clean function has been implemented, while adhering to all the restrictions mentioned. Two pointer algorithm is used to know valid words in the given string. These words are extracted using string slicing and appended to list. Finally join method is employed to return the result string.

Below is the python code for the same:

#method string clean,uses sliding window to tokenize string

#Time complexity O(n)

def string_clean(s):

i,j=0,0#stores start and ending index of window

tokens=[]#stores tokens generated

#generating tokens - O(n)

while i<len(s):#while string isn't traversed

#string function isdigit to check if character is digit

if s[i].isdigit():

if int(s[i])==0:#if digit is 0,simply advance

i=i+1

else:

#else store the previous window

tokens.append(s[j:i])

i=j=i+int(s[i])#advance to next window

else:#if character is not digit

i=i+1# simply advance

tokens.append(s[j:])#storing last token

#using join to join the tokens - O(n)

return "".join(tokens)

#testing

print("string_clean(\"\")=>\""+string_clean("")+"\"")

print("string_clean(\"I love CS116!*!*!?\")=>\""+string_clean("I love CS116!*!*!?")+"\"")

print("string_clean(\"6Hello\")=>\""+string_clean("6Hello")+"\"")

print("string_clean(\"I have 0 apples and 39 pears\")=>\""+string_clean("I have 0 apples and 39 pears")+"\"")

print("string_clean(\"car4pent3ers\")=>\""+string_clean("car4pent3ers")+"\"")

print("string_clean(\"29Hello!\")=>\""+string_clean("29Hello!")+"\"")

Below is the python code:

 #method string clean,uses sliding window to tokenize string #Time complexity O(n) def string_clean(s): i,j=0,0#stores start and ending index of window tokens=[]#stores tokens generated #generating tokens - O(n) while i<len(s):#while string isn't traversed #string function isdigit to check if character is digit if s[i].isdigit(): if int(s[i])==0:#if digit is 0,simply advance     i=i+1 else:     #else store the previous window         tokens.append(s[j:i])   i=j=i+int(s[i])#advance to next window else:#if character is not digit  i=i+1# simply advance tokens.append(s[j:])#storing last token #using join to join the tokens - O(n) return "".join(tokens) #testing print("string_clean(\"\")=>\""+string_clean("")+"\"") print("string_clean(\"I love CS116!*!*!?\")=>\""+string_clean("I love CS116!*!*!?")+"\"") print("string_clean(\"6Hello\")=>\""+string_clean("6Hello")+"\"") print("string_clean(\"I have 0 apples and 39 pears\")=>\""+string_clean("I have 0 apples and 39 pears")+"\"") print("string_clean(\"car4pent3ers\")=>\""+string_clean("car4pent3ers")+"\"") print("string_clean(\"29Hello!\")=>\""+string_clean("29Hello!")+"\"")

Related Solutions

Please Read Carefully Before start answering this question. Please follow the instructions. This Question is from...
Please Read Carefully Before start answering this question. Please follow the instructions. This Question is from 'BSBFIM501 Manage budgets and financial plans' course. There are no parts missing for this Question; guaranteed!. This is the original Screenshot direct from the question. Therefore, there are nothing any further information can be provided. Thanks for your understanding and Cooperation. Please answer the following questions from the topics discussed for Prepare, implement, monitor and modify contingency plans: 1.a. Explain the process of preparing...
Stimulation (Please read the simulation before answering the questions . Please do not scan your answer,...
Stimulation (Please read the simulation before answering the questions . Please do not scan your answer, type please) Hey Ben. You’re getting an admission in the next 15 minutes coming from the outpatient clinic. BEN: Okay, what can you tell me about this client? JAN: Well, Susan Choi is 33 years old. (PATIENT) She’s been followed for depression over the past six months and is being admitted for acute mania. She is on administrative leave from her employment as a...
Simulation (Please read the scenario before answering the question. Also type your answer thanks) This is...
Simulation (Please read the scenario before answering the question. Also type your answer thanks) This is Becky, the nurse in the emergency Department. I am caring for Robert jones a 60-year-old African- American male. We admitted him at at 4:30   this morning. He reported increased shortness of breath and weakness.    His vitals were: blood pressure 80 over 62, R 30 pulse 164 and in a-fib. We gave him a 1000 milliliter bolus of sodium chloride to bring his blood pressure....
Please read through the entire question before answering. I'm asking for assistance on how to calculate...
Please read through the entire question before answering. I'm asking for assistance on how to calculate LOSS, not gain. Thank you! The major stock market indexes had strong results in 2014. The mean one-year return for stocks in the S&P 500, a group of 500 very large companies was +11.4%. The mean one year return for the NASDAQ, a group of 3200 small and medium-sized companies was +13.4%. Historically, the one-year returns are approximately normal, the standard deviation in the...
My topic is the Automobile Industry Please read it carefully before answering Thankyou Continuing with the...
My topic is the Automobile Industry Please read it carefully before answering Thankyou Continuing with the business you have chosen, write an analysis of your business in three parts: i) Management & Leadership, ii) Organizational Structure, and iii) Operations Management, based on the material you have collected for the three topics. Each analysis should also refer back to the material you have learned in the course, and be between 250 and 500 words per topic, although you can go a...
Read case and get all the information before answering these questions. Please answer these questions specifically...
Read case and get all the information before answering these questions. Please answer these questions specifically what they are asking for with details 1. What specific type of wholesaler is Joe? 2. Evaluate Joe's marketing strategy for his current lumber business. Be and be sure to mention the specific components. 3. Contrast the components of the marketing strategy for the Arbor Products with Joe's current Hanratty lumber business. 4. What should Joe do now? Which option should he take? Be...
Who gains and who loses from import restrictions? In answering, you should consider both consumers and...
Who gains and who loses from import restrictions? In answering, you should consider both consumers and producers in both the country that imposes the restrictions and in the other countries affected by them. Also, be sure to take into account the effects of import restrictions on export industries.
Please read the following scenario and respond to the question below in the form of essay...
Please read the following scenario and respond to the question below in the form of essay Claudia, a​ CMA, is working with Mr. Harrington in the examination room. Mr. Harrington is 73 years old and does not have any living immediate family members. His closest relative is a cousin who lives more than five hours away. Within the medical​practice, Mr. Harrington has the reputation of being grouchy at times and has been known to lose his temper easily. Claudia is...
Financial Reporting II Please read carefully before answering - Choose at least two concepts you have...
Financial Reporting II Please read carefully before answering - Choose at least two concepts you have learned in this course and explain how you may use them in your present or future accounting position. Make sure you provide details on how each concept will help you support the financial goals of the company you currently work for or will work for in the future.
please read carefully before answering. Thank you. Choose at least two concepts in financial reporting (Intermediate...
please read carefully before answering. Thank you. Choose at least two concepts in financial reporting (Intermediate Accounting: Reporting and Analysis) you have learned and explain how you may use them in your present or future accounting position. Make sure you provide details to include how each concept will help you support the financial goals of the company you currently work for or will work for in the future. 
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT