You are on page 1of 2

CPGE : Reda Slaoui Année scolaire : 2023/2024

Python : Correction TP Les chaînes de


caractères 1

Exercice 1 :

1 #Q u e s t i o n 1
2 def a p p a r i t i o n ( chaine , c ) :
3 s=0
4 f o r ch i n c h a i n e :
5 i f ch==c :
6 s+=1
7 return s
8
9 #Q u e s t i o n 2
10 def doubler ( chaine ) :
11 V=" aAiIeEoOuUyY "
12 s=" "
13 f o r ch i n c h a i n e :
14 i f ch i n V:
15 s+=ch ∗2
16 else :
17 s+=ch
18 return s

Exercice 2 :

1 #I t e r a t i v e
2 d e f hamming ( ch1 , ch2 ) :
3 s=0
4 f o r i i n r a n g e ( l e n ( ch1 ) ) :
5 i f ch1 [ i ] ! = ch2 [ i ] :
6 s+=1
7 return s
8
9 #R e c u r s i v e
10 d e f hamming ( ch1 , ch2 ) :
11 i f l e n ( ch1 ) ==0:
12 return 0
13 e l i f ch1 [ 0 ] ! = ch2 [ 0 ] :
14 r e t u r n 1+hamming ( ch1 [ 1 : ] , ch2 [ 1 : ] )
15 else :
16 r e t u r n hamming ( ch1 [ 1 : ] , ch2 [ 1 : ] )

1
Exercice 3 :

1 #I t e r a t i v e
2 def palindrome ( chaine ) :
3 f o r i in range ( len ( chaine ) ) :
4 i f c h a i n e [ i ] ! = c h a i n e [− i − 1 ] :
5 return False
6 r e t u r n True
7 #R e c u r s i v e
8 def palindrome ( chaine ) :
9 i f l e n ( c h a i n e ) <=1:
10 r e t u r n True
11 e l i f chaine [0]!= chaine [ −1]:
12 return False
13 else :
14 return palindrome ( chaine [ 1 : − 1 ] )

Exercice 4 :

1 d e f r e c h e r c h e ( mot , t e x t e ) :
2 f o r i i n r a n g e ( l e n ( t e x t e )−l e n ( mot ) +1) :
3 s=0
4 f o r j i n r a n g e ( l e n ( mot ) ) :
5 i f mot [ j ]== t e x t e [ i+j ] :
6 s+=1
7 i f l e n ( mot )==s :
8 r e t u r n True
9 return False

You might also like