PROBLEM STATEMENT:
Given a string, return the count of the number of times that a substring length 2
appears in the string and also as the last 2 chars of the string, so “hixxxhi” yields 1
(we won’t count the end substring).
last2(‘hixxhi’) -> 1
last2(‘xaxxaxaxx’) -> 1
last2(‘axxxaaxx’) -> 2
SOLUTION:
def last2(str):
# Check whether the string is too short to have a 2-character ending
if len(str) < 2:
return 0
# Get the last 2 characters of the string
lt = str[-2:]
count = 0
# Loops through the string except for the last 2 characters
for i in range(len(str) - 2):
curr_pair = str[i:i+2]
if curr_pair == lt:
count += 1
return count
# --- User Input Section ---
print("----------This program counts how many times the last two characters of your input
string appear earlier in the string.----------")
st = input("Enter a string (at least 2 characters long): ")
result = last2(st)
print(f"The last two characters '{st[-2:]}' appear {result} time(s) earlier in the string.")
SCREENSHOT OF OUTPUT:
PROBLEM STATEMENT:
Given a string and a non-negative int n, we’ll say that the front of the string is the first
3 chars, or whatever is there, if the string is less than length 3. Return n copies of the
front.
front_times(‘Chocolate’, 2) -> ‘ChoCho’
front_times(‘Chocolate’, 3) -> ‘ChoChoCho’
front_times(‘Abc’, 3) -> ‘AbcAbcAbc’
SOLUTION:
def front_times(s, n):
# Get the front of the string (first 3 characters or less)
fr = s[:3]
return fr * n
# Taking user input
print("----------This program will repeat the first 3 letters (or less) of a word as many times as
you choose.----------\n")
st = input("Please enter a word or string: ")
while True:
try:
num = int(input("Now enter a non-negative number (how many times to repeat the
front): "))
if num < 0:
print("Please enter a non-negative number only.")
continue
break
except ValueError:
print("That doesn't look like a number. Please try again.")
# Generating result
result = front_times(st, num)
# Displaying result
print(f"\nResult: The front part repeated {num} times is:\n{result}")
SCREENSHOT OF OUTPUT: