Exercise 69
Write a Python program which takes a string 's' as input and which returns True if the string is duplicated and False otherwise. Example: if s = "HelloHello", the function must returns True.
Solution
# function thet takes a string s as input and returns True if s is a duplicated string
def is_duplicated_string(s):
n = len(s)
"""
first we checks if the length of the string s is even or odd.
If it's odd, it cannot be a duplicated string, so the function returns False.
"""
if n % 2 != 0:
return False
else:
# splits the string into two halves, first_half and second_half, and checks if they are equal.
half = n // 2
first_half = s[:half]
second_half = s[half:]
return first_half == second_half
# Now we can use this algorithm:
s1 = "HelloHello"
is_duplicated = is_duplicated_string(s1)
print(is_duplicated) # Output: True
s2 = "HelloWorld"
is_duplicated = is_duplicated_string(s2)
print(is_duplicated) # Output: False
Younes Derfoufi
my-courses.net
[…] Exercise 69 || Solution […]