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

What did World Com do to try to keep its stock price from falling?

Answers

The company had good enough internal controls to prevent Scott D.

What’s the relationship among speed frequency and the number of poles in a three phase induction motor

Answers

Answer:

The number of poles in the windings defines the motor's ideal speed. A motor with a higher number of poles will have a slower rated speed but a higher rated torque.

Explanation:

The relationship among speed, frequency, and the number of poles in a three-phase induction motor is governed by what is known as the synchronous speed equation.

The synchronous speed of an induction motor is the speed at which the rotating magnetic field generated by the stator windings of the motor rotates.

The synchronous speed (Ns) of a three-phase induction motor is given by the following equation:

Ns = (120 × f) / P

where:

Ns is the synchronous speed in revolutions per minute (RPM).

f is the supply frequency in hertz (Hz).

P is the number of poles.

From the equation, it can be observed that the synchronous speed is directly proportional to the frequency and inversely proportional to the number of poles.

This means that if the frequency increases, the synchronous speed also increases, assuming the number of poles remains constant.

Conversely, if the frequency decreases, the synchronous speed decreases.

The actual speed of an induction motor is known as the rotor speed or slip speed, which is always slightly lower than the synchronous speed. The difference between the synchronous speed and the actual speed is referred to as slip and is necessary for the motor to induce a voltage in the rotor and generate torque.

It's important to note that the synchronous speed equation assumes an ideal motor with no load. In practice, the actual speed of the motor depends on various factors, including the load torque, rotor resistance, and motor design.

Learn more about synchronous speed equation click;

https://brainly.com/question/33166801

#SPJ2

Which of the four factors of production are hit the hardest when high unemployment occurs ?

Answers

Answer:

Economic growth,cyclical and structural factors, demographics, education and training

Explanation:

.........

a web server is a computer that manages files for multiple user on a net work. true or false​

Answers

True. I’m pretty sure

Discuss your role as an IT professional in terms of your responsibility to clients, co-workers and society.

Answers

An IT professional is expected to deliver correct installations and programming that are safe from security breaches to clients. To co-workers, teamwork, respect, and brainstorming are needed to work together and achieve results. To society, an IT professional is expected to deliver architectures that do not compromise security and privacy.

An information technology professional could be focused on the hardware or software of systems. It is vital that IT professionals deliver services that are foolproof and not susceptible to attacks.

When working with colleagues, they must cooperate in order to deliver the most efficient services.

Learn more about IT professionals here:

https://brainly.com/question/14314381

Which system provides an easier way for people to communicate with a computer than a graphical user interface (GUI)

Answers

Answer: natural Language Processing

Explanation:

Natural Language Processing: It is a sub field of linguistics which is concerned with the interactions between Human and computer especially how to program computers to process and to understand large amounts of natural language data.

The term for an operator that may not evaluate one of its subexpressions is

Answers

Answer:

short-circuit

Explanation:

Convert the binary number 100101 to decimal. Show your solution

Answers

100101 is 37 in decimal form

The landing page of a web site has just been edited. Some users are complaining they do not see the updated content being displayed. What could be the possible reason(s)? (Select TWO responses)

Answers

In Software Engineering, when dealing with UI, there are a lot of attribute particular to text view that if not properly formatted may affect the users experience.

Two possible things that comes to my mind as a software developer are

The text colour may have be altered such that it matches that of the background so that it cannot be seen anymoreThe text View visibility may have been set to "INVISIBLE " or "GONE"

A little more checkup and tweaking or a search from online repository can go a long way to help the situation and the right user experience will be delivered.

Learn more about web design here:

https://brainly.com/question/25941596

If you are trying to create a game that involves a mystery, what colors would work best to support the mood?
dark colors
bright colors
neutral colors
greyscale colors

i gave up in life

Answers

Answer:

the answer is dark colors

Answer:

Dark colors

Explanation:

Dark colors are very ominous and support a mood of mystery

Does technology always follow the science, yes or no and explain the reason your choice

Answers

Answer:

NO

Explanation:

because Technology does not always follow science but it may actually lead science in some instances. An example is weather forecasting.Mark me brainliest plz

Shell Scripting:

In the following statement, X is the initial value:

for (( X = N; X <= Y; X++ ))
True or False

Answers

True because if x sucks x then Y will spill juice cream team juice what how ….its true.

Shell scripts are most useful for repetitive tasks that would take a long time to accomplish if entered one line at a time. A few examples of uses for shell scripts are as follows: automating the process of code compilation. Programming or setting up a programming environment. Thus, it is true.

What role of Shell Scripting in programming?

You can access the Unix system through a Shell. It leverages the input you provide to execute programs. Once a program has finished running, its output is shown. In the shell environment, we may run our commands, applications, and shell scripts.

Programmers do not need to switch to a completely other syntax because the command and syntax are precisely the same as those placed directly on the command line.

Therefore, it is true that Shell scripts may be created considerably more quickly. Rapid start interactive bug-fixing.

Learn more about Shell Scripting here:

https://brainly.com/question/29625476

#SPJ2

Question #2
Dropdown
Complete the sentence.
A_____
number is composed of only zeros and ones.

Answers

What are the answer choices? If none then i say "A prime

number is composed of only zeros and ones."

Answer: Binary

Explanation: Binary numbers use the base-2 numeral system (binary). This system uses only two symbols: "0" (zero) and "1".

Which of the following is not an Error Style for data validation?

Answers

Based on the Microsoft Excel data validation, the option that is not an Error Style for data validation is the choice that does not show an error alert.

Given that there is no option available, the best way to answer this question is to show the types of Error Styles for data validation available.

Different types of Error Style for data validationStop style: this will bring the option of "Retry, " "Cancel, " and "Help."

Warning style: this will show "Continue," with options of "Yes," "No," "Cancel," and "Help."

Information Style: this will ask you to input the whole number with the option of "Ok," "Cancel," and "Help."

Hence, in this case, it is concluded that the Error Style for data validation is Stop, Warning, and Information Style.

Learn more about Error Style for data validation here: https://brainly.com/question/18497347

Define technical writing. The proposal introduces the ……. (5 Mark)

a) Results b) Objectives c) Researcher d) None of the previous

Answers

Answer:

B.objective

#carryonlearning

How does critical thinking relates to peer assessment?

Answers

Answer:

Peer review is a critical component of the life of the mind and an effective teaching strategy for nurturing students' critical thinking skills. ... peer review of writing is most effective when students have an opportunity to revise their writings prior to submitting a grade. Is it true that peer assessment helps students develop their critical thinking skills?

The students' perceptions of the peer evaluation activity were later elicited in interviews and a short written survey. The findings of the study indicate that peer evaluation activities did help in developing critical thinking skills, thus improving their academic writing performance.

Explanation:

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 !!

Explain the 3 types of control transfer structures in programming using flowchart symbols

Answers

Answer:

Process Flowchart.

Data Flowchart.

Business Process Modeling Diagram.

how does the internet bring people farther apart
use a paragraph to answer the question​

Answers

Answer:

First of all you may not be able to see your friend in person and it gets very sad. Sometimes you call them but they don't answer you because they don't have enough time to talk or they have something else to do. They won't always want to be on the internet you know, they want to go outside and get a life and not be like the FRE-KIN T-I-K T-O-K-E-R-S WHO ARE CHILDREN AND BEING VERY STU-PID AND ARE TOTAL IDIOTS AND SAY STUFF THAT MAKE NO SENSE AND TRY TO GET ATTENTION. OH DON'T BRING TOWARDS THE GA-CHA IT SO TRASH. I still hate gacha :) and I am happy. Another thing is what some people post, you see you meet friends in real life and sometimes you get to know them but you don't know what they might be doing on the internet and another thing is that they post stuff that makes you feel uncomfortable and disgusted.

Briefly explain the Conleptual model 044
effective computer Based instruction
for adult outlining the three units
(output, process, input)

Answers

According to computer analysis, the concept of effective computer-based instruction for adults is the embedment of the fundamental parts of computer-based instruction to provide the expected stratagems for inquiry in CBI for adults.

The three (3) units output, process, and input

Output in CBI External supportCBI DesignInstructional Strategy design

Process in CBISelf DirectednessComputer Self EfficacyLearning Goal Level

Output in CBILearning OutcomeScreen DesignPractice Strategy

Hence, in this case, it is concluded that computer-based instructions can be effective for adult learning.

Learn more about Computer Based Instructions here: brainly.com/question/15697793

There are two kinds of emotions: positive and negative. True False

Answers

Answer:

False

Explanation:

There are many emotions the human brain can experience

False is the answer to the question

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)

P3. Produce a plan to use social media in a business to meet its business requirements.

Answers

The plan to use social media in a business include:

It is important to audit the current social presence.  The company should document who their Ideal customer is. A mission statement should be created. One should identify the key success metrics. An engaging content should be created.  The company should also invest in a social media management tool.

It should be noted that using social media in a business is an effective way to meet its business requirements and achieve organizational goals.

Learn more about social media on:

https://brainly.com/question/1163631

Briefly the conceptual model of effective computer based instruction for adults outlining three units (output, Process and input )

Answers

but I think it’s output

You are given an integer N where 0 <= N <= 100, followed by another line of input which has a word W with length L where 1 <= L <= 50. Your task is to print N lines with the word W. The lines of your output should not have any trailing or leading spaces.

Your output lines should not have any trailing or leading whitespaces

Input

3
Hello


Output

Hello
Hello
Hello

Answers

import math as m

def print_word(N, W, retries = 4):

for _ in retries:

if(N > 100 or N < 0 or len(W) > 50):

print("Number is out of range or word is too large. Try again.")

new_word = str(input("New word: "))

new_num = int(input("New number: "))

if(new_num >= 0 and new_num <= 100 and len(W) <= 50):

for row in new_num:

print(new_word)

return "Thank you for your time!"

if(N >= 0 and N <= 100 and len(W) <= 50):

for row in N:

print(W)

return "Thank you for your time!"

try:

N = m.floor(int(input("Enter a number from 0 to 100: " )))

W = str(input("Enter a word: "))

except ValueError:

print("Invalid Input!")

print(print_word(N,W))

Following are the python program to print the input string value:

Program:

N= int(input("Enter a value of integer N (0 <= N <= 100): "))#defining an integer variable N that inputs integer value from the user-end

W = input("Enter the word W (length of 1 <= L <= 50): ")#defining a string variable W that inputs the value fom the user-end

for n in range(N):#defining a for loop that uses the range method with integer variable and prints the string value

   print(W)#printing the string value

Program Explanation:

Defining the an integer variable "N" that inputs an integer value from the user-end.In the next step, another variable "W" is declared that inputs the string value from the user-end.After input all the value a for loop is declared that uses the range method with integer variable and prints the string value.  

Output:

Please find the attached file.

Fin out more information about the program here:

brainly.com/question/24604692

"1. What sorts of problems does this declaration imagine being solved through science and technology?"

Answers

‎‎‎This proclamation focuses on overcoming age, cognitive limitations, involuntary pain, and our physical confinement to the planet. They seek to help bodies live longer, human minds gain more knowledge, stop world hunger, thirst, violence, and other forms of violence, and assist humans in living on worlds other than Earth.

Which of the four factors of production are hit the hardest when high unemployment occurs ?


A. Land

B. Labor

C. Capitol

D. Management

Answers

Answer:

Land

Explanation:

people start to farm so that they earn money by selling those vegetables

Unemployment may result in increased payments from the state and federal governments for things like food stamps because unemployed persons tend to spend less and may accumulate more debt. Thus, option A is correct.

What hardest when high unemployment occurs?

High unemployment causes a decline in inflation. Voters and policymakers do not like dropping prices; they seek low unemployment and low inflation. They typically have to choose between the two and cannot usually have both.

Unemployed workers go through financial difficulties, which has an impact on their families, interpersonal relationships, and communities. If neglected, this can lead to a recession or even a depression as consumer spending, one of an economy's key sources of growth, falls.

Therefore, Land production is hit the hardest when high unemployment occurs.

Learn more about unemployment here:

https://brainly.com/question/18801727

#SPJ2

How often do you trade cowoncy? If so, for what and how much?​

Answers

There are different ways to trade cowoncy. There are some legitimate site to buy and sell it. In trade cowoncy, about 100000 Cowoncy is bought for $17.89USD.

Cowoncy is commonly described as the OwO bot's form of currency. It is known as a currency used worldwide in hunting.

Its role is mainly for for hunting and in the activation of one's huntbot and it is often used in other form of purchases such as cosmetics, etc.

Learn more about trade from

https://brainly.com/question/17727564

) Give the assembly language instruction sequence to enable external interrupt 0 (INT0) as an interrupt source and to make it falling-edge triggered. What signal (port and port pin) must be low to trigger a falling-edge trigger event for INT0

Answers

Your solution is attached with the picture below

different types of programming languages​

Answers

the main types are machine language, assembly language and high level language

Answer:

At the time of writing, some of the top programming languages include: 

C

Java 

Python

C++

C# 

Visual Basic 

JavaScript

PHP

SQL

Assembly language

R

Groovy 

Other Questions
Here is a balanced Hanger. Each triangle weighs 2.5 pounds, each circle weighs 3 pounds, and x represents the weight of each square. Select all equations that represent the hanger which statement correctly compares a function of lipids to a function of proteins in the body? subtract 19/12 - 3/4 claim one celebrity. nobody else can choose the celebrity you claim. What are three basic tasks of the federal bureaucracy I NEED HELP PLEASE! Thank you Which of the following is an economic change Americans faced after WW1?a)shortage of country-made goodsb)loss of landc)forced to pay reparitions Case: Brown v. Board of Education, Topeka -How might life be different for society today if the court had ruled the opposite way? Students should read all questions carefully and choose the appropriate answer,1. The greatest asset of any country is the:1 pointeconomic growthnatural resourcespeopletourist industry Which action most contributed to an international economic crisis during the early years of the Great Depression?. GIVING BRAINLIEST. please help. In documentary filmmaking, why is it typical for a filmmaker to write a script after the film is shot? a derpartment store sell 152 pair of jeans for 29 each. which is the best estimate of the total sales for the jeans Select all equations that represent this question:Priya is stacking building blocks to make a tower. She takes a break when the tower is 2 1/2 feet tall, which is 5/8 of the hight of the tower she wants ti build. How tall is the tower when finished? For a project in her Geometry class, Makayla uses a mirror on the ground to measure the height of her school building. She walks a distance of 13.75 meters from the school, then places a mirror on flat on the ground, marked with an X at the center. She then steps 1.2 meters to the other side of the mirror, until she can see the top of the school clearly marked in the X. Her partner measures the distance from her eyes to the ground to be 1.35 meters. How tall is the school? Round your answer to the nearest hundredth of a meter. Find sin(a-B), if cosa=1/3, cosB=1/4, a=(0;180), B(-90;0) A neuron that stimulates the gastrocnemius muscle receives signals from multiple areas of the brain. This is an example of Q2. Fill in the blank with correct words.A: Chemical B: Horizontal C: Shells D: Columns E: Group VII1) The vertical ___________are called groups and the_____________rows are called periods.2) Elements in the same groups have the same number of electrons in their outer_______________ for example, all the elements in ___________ have 7 electrons on their outer shells.3) Elements in the same group have similar ___________ and physical properties what is equivalent to 1 1/3 and 3/4 using 12 as the denominator tortoise shells and snail shells are similar in function to protect the organism from predators based on a comparison of the organisms in the images what can you conclude