Building a String Library

Sometimes when programming you need to introduce a new data type and develop a library of functions for manipulating instances of that data type. Often this is done as methods on a new class but not always.

In this assignment, you'll be defining a collection of functions on strings, most of which already exist as methods on the str class. However, you should pretend that they don't already exist and define them as functions. Of course, you can't just use the existing methods. This will give you a bunch of practice on manipulating strings and also on defining functions.

In this assignment, you'll be defining a collection of functions on strings. You should define each of these as a new function with a function header as below. The description of each is in the comment supplied. Recall that strings are immutable, so you will have to return a new copy of the string for those that call for you to return a string. If you are returning the same string as the input, just return it; there is no need to make a new copy, and it wouldn't anyway.

The only string functions/methods to use:

ord, chr
indexing and slicing
append (i.e., ``+'')
len, in, not in
equality comparison (== or !=))
Looping over strings (while or for loops) and selection (if statements) are allowed. BUT You cannot convert the strings to other types such as lists.

Define each of the following functions, with semantics as indicated by the comment. In each of the following ch is a single character, str, str1, str2 are strings, and i is a non-negative integer. You do not have to validate the inputs, except as indicated; you can assume these types.

At least one question asks you to return two values. That really means returning a tuple (pair) of values. You do that as follows:

return value1, value2
This actually returns the pair (value1, value2). The caller can then assign the members of the pair to two variables:

x, y = pairReturningFunction() # assumes function returns a pair
z, w = (value1, value2) # assigning a tuple to 2 variables
If you like, you can use earlier functions in later ones, or define helper functions, though it shouldn't really be necessary. Note that some of these are trivial to write, while others are a bit harder. I have done the first one for you.

def myAppend( str, ch ):
# Return a new string that is like str but with
# character ch added at the end
return str + ch

def myCount( str, ch ):
# Return the number of times character ch appears
# in str.

def myExtend( str1, str2 ):
# Return a new string that contains the elements of
# str1 followed by the elements of str2, in the same
# order they appear in str2.

def myMin( str ):
# Return the character in str with the lowest ASCII code.
# If str is empty, print "Empty string: no min value"
# and return None.

def myInsert( str, i, ch ):
# Return a new string like str except that ch has been
# inserted at the ith position. I.e., the string is now
# one character longer than before. Print "Invalid index" if
# i is greater than the length of str and return None.

def myPop( str, i ):
# Return two results:
# 1. a new string that is like str but with the ith
# element removed;
# 2. the value that was removed.
# Print "Invalid index" if i is greater than or
# equal to len(str), and return str unchanged and None

def myFind( str, ch ):
# Return the index of the first (leftmost) occurrence of
# ch in str, if any. Return -1 if ch does not occur in str.

def myRFind( str, ch ):
# Return the index of the last (rightmost) occurrence of
# ch in str, if any. Return -1 if ch does not occur in str.

def myRemove( str, ch ):
# Return a new string with the first occurrence of ch
# removed. If there is none, return str.

def myRemoveAll( str, ch ):
# Return a new string with all occurrences of ch.
# removed. If there are none, return str.

def myReverse( str ):
# Return a new string like str but with the characters
# in the reverse order.
Expected output:

>>> from MyStringFunctions import *
>>> s1 = "abcd"
>>> s2 = "efgh"
>>> myAppend( s1, "e" )
'abcde'
>>> myCount( s1, "e")
0
>>> myCount( s1, "a")
1
>>> myCount( "abcabc", "a")
2
>>> myExtend( s1, s2 )
'abcdefgh'
>>> myMin( "" )
Empty string: no min value # Note the None doesn't print
>>> myMin( "zqralm" )
'a'
>>> myMin( "Hello World!" )
' '
>>> myInsert( "abc", 0, "d")
'dabc'
>>> myInsert( "abc", 2, "d")
'abdc'
>>> myInsert( "abc", 4, "d")
Invalid index # Note the None doesn't print
>>> myPop( "abcd", 1 )
('acd', 'b')
>>> myPop( "abcd", 0 )
('bcd', 'a')
>>> myPop( "abcd", 5)
Invalid index
('abcd', None)
>>> myFind( "abcdabcd", "a")
0
>>> myFind( "abcdabcd", "c")
2
>>> myFind( "abcdabcd", "f")
-1
>>> myRFind("abcdabcd", "d")
7
>>> myRFind("abcdabcd", "e")
-1
>>> myRemove( "abcdabcd", "a")
'bcdabcd'
>>> myRemove( "abcdabcd", "x")
'abcdabcd'
>>> myRemove( "abcdabcd", "d")
'abcabcd'
>>> myRemoveAll("abcabcabca", "a")
'bcbcbc'
>>> myReverse( "abcd" )
'dcba'
>>> myReverse( "" )
''

Answers

Answer 1
Code:

def myAppend( str, ch ):
# Return a new string that is like str but with
# character ch added at the end
return str + ch

def myCount( str, ch ):
# Return the number of times character ch appears
# in str.

# initiaalizing count with 0
count = 0

# iterating over every characters present in str
for character in str:
# incrementing count by 1 if character == ch
if character == ch:
count += 1

# returning count
return count


def myExtend( str1, str2 ):
# Return a new string that contains the elements of
# str1 followed by the elements of str2, in the same
# order they appear in str2.

# concatenating both strings and returning its result
return str1 + str2

def myMin( str ):
# Return the character in str with the lowest ASCII code.

# If str is empty, print "Empty string: no min value"
# and return None.
if str == "":
print("Empty string: no min value")
return None

# storing first character from str in char
char = str[0]

# iterating over every characters present in str
for character in str:
# if current character is lower than char then
# assigning char with current character
if character < char:
char = character
# returning char
return char


def myInsert( str, i, ch ):
# Return a new string like str except that ch has been
# inserted at the ith position. I.e., the string is now
# one character longer than before.

# Print "Invalid index" if
# i is greater than the length of str and return None.

if i > len(str):
print("Invalid index")
return None

# str[:i] gives substring starting from 0 and upto ith position
# str[i:] gives substring starting from i and till last position
# returning the concatenated result of all three
return str[:i]+ch+str[i:]

def myPop( str, i ):
# Return two results:
# 1. a new string that is like str but with the ith
# element removed;
# 2. the value that was removed.
# Print "Invalid index" if i is greater than or
# equal to len(str), and return str unchanged and None
if i >= len(str):
print("Invalid index")
return str, None

# finding new string without ith character
new_str = str[:i] + str[i+1:]

# returning new_str and popped character
return new_str, str[i]

def myFind( str, ch ):
# Return the index of the first (leftmost) occurrence of
# ch in str, if any. Return -1 if ch does not occur in str.

# finding length of the string
length = len(str)

# iterating over every characters present in str
for i in range(length):
# returning position i at which character was found
if str[i]==ch:
return i
# returning -1 otherwise
return -1


def myRFind( str, ch ):
# Return the index of the last (rightmost) occurrence of
# ch in str, if any. Return -1 if ch does not occur in str.

# finding length of the string
length = len(str)

# iterating over every characters present in str from right side
for i in range(length-1, 0, -1):
# returning position i at which character was found
if str[i]==ch:
return i
# returning -1 otherwise
return -1

def myRemove( str, ch ):
# Return a new string with the first occurrence of ch
# removed. If there is none, return str.

# returning str if ch is not present in str
if ch not in str:
return str

# finding position of first occurence of ch in str
pos = 0

for char in str:
# stopping loop if both character matches
if char == ch:
break
# incrementing pos by 1
pos += 1

# returning strig excluding first occurence of ch
return str[:pos] + str[pos+1:]

def myRemoveAll( str, ch ):
# Return a new string with all occurrences of ch.
# removed. If there are none, return str.

# creating an empty string
string = ""

# iterating over each and every character of str
for char in str:
# if char is not matching with ch then adding it to string
if char!=ch:
string += char
# returning string
return string

def myReverse( str ):
# Return a new string like str but with the characters
# in the reverse order.

return str[::-1]

Related Questions

why GUI operating system is more popular than CUI operating system these days? discuss
please give me long answer​

Answers

Answer:

Explanation:GUI operating system is more popular than CUI operating system these days because they support extra devices and multimedia system and also network and internet which CUI doesnot support. In CUI operating system we have to type commands to perform any task in the computer but in GUI operating system we can give vommands to the computer by clicking on icons, menus and buttons which is easier to us.

Hope It helps................

Explain why you do not need expensive equipment to take pictures or record video?

Answers

Explanation:

Expensive equipment is not necessary because from a technical perspective as long as the device has a lens and a mic it should be able to take photos and videos.

Answer: No, you don't not need an expensive camera . It may have better quality or worst quality . A phone car record and take pictures. Using a Light Stand Can give you a better lighting and better angle so you don't have to hold it or put it on your table, lap, or desk.

Explanation: A lot of people think you need to own a good camera to take a good photograph. A more expensive camera can help, but certainly is not essential. To answer the question though, it is 'no' – the equipment really doesn't make any difference to the end result, but does affect the process of getting there.

Byeeeeeee Remember to stan BTS , Wear Your Mask, And Drink Water

Q) Look at the code and determine the output

y=-10
while(y<10):
print('$', end="") y += 5

(a) $$$$$$$$$$
(b) $$$$
(c) $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
(d) Nothing will be printed

Answers

Answer:

B.

Explanation:

software that converts program written in other language into machine language​

Answers

Software Development Tools

Compiler which is a part of software development tools,converts High level programming language into binary code.(machine language)

Computer viruses and coding books

Answers

Is there a picture to go along with this? I don’t see one and an willing to help!

Tumblr, Jaiku is an example of _____________ website.
a) Microblogging
b) Blogging
c) Social Networking
d) None of the Above​

Answers

Answer:

Microblogging

One of the best-known channels in the microblogging world. Twitter is a quick and convenient way to share short posts, GIFs, article links, videos and more. Pinterest: Companies on Pinterest link to products, articles and other useful information for audiences .

Explanation:

Hope this helps you !!

Q) Look at the code sequence and select the correct output

str="Python using Colab"
for i in str:
if(i.isupper()==True):
print(i.lower(), end="")
if(i.islower()==True):
print(i.lower(), end="")

(a) pYTHONUSINGcOLAB
(b) PYTHONUSINGCOLAB
(c) Error
(d) pythonusingcolab​

Answers

Answer:

D.

Explanation:

10011÷11 binary division​

Answers

Answer:

110.01001

Explanation:

it's a repeating decimal

what is a computer software

Answers

Software is the digital operations performed by a computer’s hardware.

Answer:

Software is a collection of instructions that tell a computer how to work. This is in contrast to hardware, from which the system is built and actually performs the work.

Explanation:

Please mark as brainliest

what is the keyboard shortcut to display formulas on the worksheet

Answers

the keyboard shortcut is c=8

I ate five M&Ms: red, green, green, red and yellow. Only these three colors are possible. I assume that p(yellow)=3p(green)
What is the estimated probability of green color?

Answers

Answer:

Below is code written in a free CAS (WxMaxima):

The above code creates the probability of 19 or more brown in the sample of 48 for population sizes from 5*19 to 10000 in steps of 5.

Here’s a plot of that data:

The horizontal blue line is the probability for an infinite population size (or, choosing each of the 48 M&Ms with replacement, which I infer is not what you meant). It is calculated using the binomial cdf:

The red curve approaches the blue line asymptotically as the population gets larger.

At population 10000, the red curve is

.

Why is information so important in our lives

Answers

Information is very important because it helps us as a society make decisions. Decisions are impossible without information, and we are constantly seeking information in everything we do. Information is important in decreasing our sense of doubt and uncertainty as well.
Information is important in everyone's lives because without information, we would not be able to develop our knowledge on the world. Retaining information starts when you're a baby up until you die and this is through sensory - being able to touch, hear, see and taste.

Additionally, what's the importance of technology in our life? Technology can make any family or business feel safer. There are many security devices and software available to secure your financial data, protect your home when you are away and much more. Technology is important because it makes you feel more secure with every area in life for both personal and business reasons.

Where did the first human cities show up?
South Africa
Mesopotamia
Peru
Denmark

Answers

The first human cities in the history of the world showed up at; B: Mesopotamia

Throughout the history of the world, cities have always been attractive to more and more people because they useful as centers of learning including culture, and great economic opportunities.

However, this explosion of migration to the cities has lead to some very large cities that are home to as much as 15 million or more which could lead to overpopulation and potentially health hazards.

Now, the first cities in the world from history are said to have appeared thousands of years around 7500 BC ago in Mesopotamia which had very fertile lands. The cities formed here include those in euphrates and even along the Nile River in Egypt.

Read more about Mesopotamia at; https://brainly.com/question/22701821

Role and responsibility of an IT professional

Answers

create the computer, network, and communication systems that an organization needs

I need help with This excel chart. I don't know how to divide all the rows and columns.

In column F, enter formulas that use a function to calculate % Caught with Table (fish caught with Table hook divided by the total number of fish caught).
Format the % Caught with Table values as a percent with one decimal place.

Answers

Answer:

sorry I don't know how to do this.Very very sorry.

Write a program that allows the user to enter three separate strings: a city name, a state name, and a ZIP code.

Answers

Answer:

In Python:

city = input("Enter a city: ")

state = input("Enter a state: ")

zip_code = input("Enter a zip code: ")

How have you seen technology transform in your own life? What was the oldest computer or device you remember using? How does this compare to the machines you use today? What was your favorite piece of tech that is no longer popular or in common use? What are some modern benefits you're grateful for? Share your own "history of computing" with your fellow learners!

Answers

I am greatly opportuned to live in a time an era where technology is prevalent and constantly evolving, I have also experience technological changes in my life in the areas of learning because  I browse about questions a lot.

What was the oldest computer or device you remember using?

I can remember using a Nokia 3310 but now I use an iPhone 11 pro max

How does this compare to the machines you use today?

The difference in the Nokia 3310 mobile and my current iPhone 11 pro max goes a long way to describe the evolutionary changes in technology, my iPhone 11 pro max is a smart phone with a lot of feature not present in my old Nokia 3310.

What was your favorite piece of tech that is no longer popular or in common use?

My favourite piece of tech no longer in use today is the typewriter, I like it because of the sound from the key when I am typing, it is more like typing and have fun at the same time.

What are some modern benefits you're grateful for?

I am most grateful for the Internet because it is a repository for knowledge, I learn and collaborate everyday using the Internet.

Learn more how the history of computer:

https://brainly.com/question/485705

Which of these are examples of an access control system? Check all that apply.
OpenID
44:13
OAuth
TACACS+
RADIUS
Expand
10. Question

Answers

The examples of an access control system include the following:

C. OAuth

D. TACACS+

E. RADIUS

An access control system can be defined as a security technique that is typically designed and developed to determine whether or not an end user has the minimum requirement, permission and credentials to access (view), or use file and folder resources stored on a computer.

In Cybersecurity, an access control system is mainly used to verify the identity of an individual or electronic device on a computer network, especially through authentication and authorization protocols such as:

OAuth: Open Authorization.TACACS+: Terminal Access Controller Access Control Server.RADIUS: Remote Authentication Dial-In User Service.

Read more on access control here: https://brainly.com/question/3521353

Write an if/else statement that assigns 1 to the variable fever if the variable temperature is greater than 98.6; otherwise it assigns 0 to fever.

Answers

Answer:

temperature = int(float(input("Enter temperature: ")))

fever = 0

if temperature > 98.6:

   fever +=1

else:

   fever = 0

print(fever)

Explanation:

what are the parts system unit​

Answers

Explanation:

there are 6 main system unit components:

motherboard

processor

RAM

hard drive

video card

power supply.

explain the different types of programming languages​

Answers

Answer:

Language types. Machine and assembly languages. Algorithmic languages. FORTRAN. ALGOL. C. Business-oriented languages. COBOL. SQL. Education-oriented languages. BASIC. Pascal. Logo. Hypertalk. Object-oriented languages. C++ C# Ada. Java. Visual Basic. Python. ...

Elements of programming. Control structures. Data structures.

Explanation:

Pls Mark Brainliest

One of the main operations associated with the dictionary ADT is:
(a) given a key and value, remove the entry with given key and value from the dictionary
(b) given a value, remove the entry that contains the value
(c) remove the last item in the dictionary
(d) given a key, return the value of the dictionary entry with the given key

Answers

ITS B my friends and teacher helped

Is majority intent determined by how many times the same type of result is shown on the search engine result page?

Answers

According to the search engine algorithm, it is True that the majority intent is determined by how many times the same result is shown on the search engine result page.

What is Search Intent?

Search Intent is a term used to describe a user's reason when typing a question or words into a search engine.

Generally, if a user found that no search results match his wants, he would likely not click on any link before performing a similar query search. This would make search engines return with more links that have higher clicks.

Different types of Search IntentInformationalCommercialNavigationTransactional

Hence, in this case, it is concluded that the correct answer is True.

Learn more about Search Engine here: https://brainly.com/question/13709771

In addition to being fun, another reason that people have been creating games ever since they settled into communities is:
They keep us out of trouble.
They teach us to follow rules.
They teach cooperation.
They teach strategy and critical thinking.

if you want points just keep looking im asking questons liek crazy

Answers

Answer:

I am pretty sure it's D. to teach strategy and critical thinking.

Answer:

They teach strategy and critical thinking

Explanation:

35. Which of these devices can be accessed remotely across the internet? 1 O Solid State Drive O USB Memory Stick Cloud Storage Optical Media This is a required question​

Answers

Answer: I believe it's cloud storage.

Explanation:

The cloud is basically an area of all the data you've acquired. And you can only access it on the internet. It's not a physical object. So The Cloud is your answer! :>

(Please mark this as brainliest)

How can you implement a framework?

Answers

Answer:

that's the answer

Explanation:

I hope it helps to you

Convert the binary number 100101 to decimal. Show your solution

Answers

100101 is 37 in decimal form

Game have been a part of human life only recently in human history—about 1100 AD.
True
False

Answers

Answer:

The answer is false it has not

Answer:

B: False

Explanation:

it's just false

Dean Smith is dissatisfied with the time it takes to get a new faculty ID made and believes more servers will speed up service and reduce costs thanks to shorter lines. Prof. Karen is tasked to study the situation. Prof. Karen observes an average of 20 customers/hr arriving and each technician (service window) serves 5 customer/hr, on average. Assume an M/M/s queue system. Prof. Karen calculates the operational cost of each server as $20/hr, and assumes a cost of waiting in the SYSTEM as $25/hr per customer. What is the optimal number of service windows to minimize total cost

Answers

The answer is :

X = 4

Explanation:

The optimal number of service windows to minimize total cost will be 5 service windows.

How to calculate the optimal value?

The optimal number of service windows to minimize total cost will be calculated thus:

Cost = 20x + 25(20 - 5x)

Cost = 20x + 500 - 125x

Cost = 500 - 105x

For the minimum cost,

500 - 105x = 0

105x = 500

x = 500/105

x = 4.76 = 5

Therefore, the optimal number of service windows to minimize total cost will be 5 service windows.

Learn more about cost on:

https://brainly.com/question/25109150

#SPJ2

PLEASE HELP I NEED TO CHECK MY ANSWER ASAPPP

8. Based on the following syntax, what is a likely output for this code snippet if "number" was 35.555

return count(amount_owed. 2)

O 35.555
O 35.55
O 36
O 40

Answers

Functions are code segments that are executed when called or invoked

The function definition is not given; so, the output of the program cannot be outrightly determined.

However, the following are the possible scenarios.

The program would return 35.55 if the 2 represents the digits after decimal.The program would return 36 if the 2 represents the significant digits.

It is unlikely for the program to return (a) 35.555 and (d) 40

Read more about functions at:

https://brainly.com/question/14284563

Other Questions
(PHOTOGRAPHY) When your camera and computer are talking to each other during the photo transfer process, a pop-up window should appear. What will this pop-up window explain?Group of answer choiceshow to transfer your photos from your computer to your friends computerhow to transfer your photos onto the internethow to transfer your photos from your computer to your camerahow to transfer your photos from your camera to your computerPLEASE HELP!!! I cannot go home now. I (shop) ................................... with my friends. How did Jesus' teachings differ from the Jewish leaders? ______= Speed / Wavelength A hole needs to be at least 40 feet below ground level. This means it needs to be more than 2 times its current depth.represented by the inequality 2d Which detail from the story best explains why Maria Elisa wants to give Mrs. Robertson aChia Pet?A. "But I've chosen something that is even better." (Paragraph 28)B. "I point to the picture in the flyer: a clay sheep covered in grassy hair."(Paragraph 32)C."We learned about germination last month."" (Paragraph 33)"I'll be the only one who is empty-handed!" (Paragraph 41)111D. Can someone help me out on this math problem? Help help help help help Helppppopleaseee???? HELPPPPPP (question in picture) I have to ask this question describe the ways in which George Washington inspired the Continental Army and served as an example for his soldiers to follow? how can I answer this in three ways How does social media affect the academic performance of children aged 10-17? Metals are malleable which means they can ______________ break easily conduct electricity be melted into a liquid form be hammered or pressed permanently out of shape without breaking or cracking Read the excerpt from Anne Frank: The Diary of a Young Girl:I have often been downcast, but never in despair; I regard our hiding as a dangerousadventure, romantic and interesting at the same time. In my diary I treat all theprivations as amusing. I have made up my mind now to lead a different life fromother girls and, later on, different from ordinary housewives. My start has been sovery full of interest, and that is the sole reason why I have to laugh at the humorousside of the most dangerous moments.Based on this passage, write a one paragraph description of Anne's viewpoint andtone, as well as the meaning of this text. Be sure to explain how specific languagewithin the text impacts reader understanding of her stance, attitude, and message. Which shows the weight of an atom?atomic massatomic numberchemical symbolnone of the above Which immigrant groups have had a large influence on music in the United States? Immigrants from Antarctica and Greenland Immigrants from Canada, Australia, and the Pacific Rim Immigrants from China and the Philippines Immigrants from Mexico, South America, and the Caribbean hydrofluoric acidWhats the formula can anyone slove this question pls 71.841 to the nearest tenth Can we trust our relatives ?