it-Python-courses-python-string--Python-courses-python-exercises

Exercise 84 *

Write a Python program as function that takes as parameter a string s and which returns the list of all repeated character in the string s. Example: if s = "python language", the fuction returns the list :

['n', 'a', 'g']

Solution

# create a function to test if given character is repeated within a given string
def isRepeated(s,c):
counter = 0
for x in s:
if x == c:
counter = counter + 1
if counter >= 2:
return True
else:
return False
# function which determines the list of all repeated characters
def listRepeated(s):
repeated = []
for x in s:
if isRepeated(s,x) and x not in repeated:
repeated.append(x)

return repeated

# Example
s = "python language"
print("The list of repeated character is : " , listRepeated(s))
# The output is:
# The list of repeated character is : ['n', 'a', 'g']

Younes Derfoufi
my-courses.net

Leave a Reply