Python Programming Exercises Guide
Python Programming Exercises Guide
WriteaprograminPythonthataskstheusertoentertheirnameanddisplaysit.
yournamewithawelcomemessage!
Solution
name=input("Typeyourname:")
print("Welcome: ", name)
Exercise2| Sumoftwonumbers
WriteaprograminPythonthataskstheusertoentertwonumbersaandbanddisplaysthem.
theirsum:a+b
Solution
#-*-coding:utf-8-*-
asktheusertoenterthevaluesofaandb
a=input("Enter the value of number a: ")
b=input("Enter the value of the number b: ")
Convertstringstointegers
a=int(a)
b=int(b)
s = a + b
print("The sum of a and b is a + b = ", s)
Exercise3| Maximumoftwonumbers
WriteaprograminPythonthataskstheusertoentertwonumbersaandbanddisplaysthem.
theirmaximum.
Solution
#-*-coding:utf-8-*-
readthevaluesofaandb
a = int(input("Enter the value of number a: "))
b = int(input("Enter the value of number b: "))
Performacomparisontesttofindthelargest
if(a>b):
The maximum of a and b is: a =
else:
The maximum of a and b is: b =
Exercise4| Displayingthefirst100numbersinPython
WriteaprograminPythonthatdisplaysthefirst100integers.
Solution
#-*-coding:utf-8-*-
iteratethroughthefirst100numbersusingtheforloop
foriinrange(0,101):
print(i)
afterexecution,theprogramdisplaysthefirst100numbers:
0
1
2
.
.
.
100
"""
Exercise5| TesttheparityofanumberinPython
WriteaprograminPythonthataskstheusertoentertheirintegerand...
displaywhetherthisnumberisevenorodd
Solution
#-*-coding:utf-8-*-
Readthevalueofn
n = input("Type value of the integer n : ")
Convertntoaninteger
n=int(n)
Testifnisevenornot
if(n%2==0):
The number '
else:
The number '
Exercise6| Displaymajororminoraccordingtoageinpython
WriteaprograminPythonthataskstheusertoentertheirageanddisplaysit.
message«vousêtesMajeur!»sil’âgetapéestsupérieurouégaleà18etlemessage«vousêtes
minor!"iftheenteredageislessthan18.
Solution
#-*-coding:utf-8-*-
Asktheusertoentertheirage
age=int(input("Enteryourage:"))
if(age>18):
You are an adult!
else:
You are a minor!
Exercise7| Maximumofthreenumbersinpython
WriteaprograminPythonthataskstheusertoenter3numbersx,y,andzanddisplaysthem.
theirmaximum.
Solution
#-*-coding:utf-8-*-
Asktheusertoenter3numbersa,b,c
a=int(input("Type a value of the number a "))
b = int(input("Type a value of the number b "))
c=int(input("Type a value of the number c "))
defineandinitializethemaximumtozero
max=0
if(a > b):
max=a
else:
max=b
if(max<c):
max=c
else:
max=max
The maximum of the three numbers is: max(a,b,c) =
Exercise8| CalculatingthesumofthefirstnumbersinPython
WriteaprograminPythonthataskstheusertoenteranintegernanddisplaysit.
thevalueofthesum1+2+…+n=
Solution
#-*-coding:utf-8-*-
Asktheusertoenterthevalueoftheintegern
n=int(input("Type a value of the integer n "))
defineandinitializeanauxiliaryvariablej
j=0
foriinrange(1,n+1):
j = j + i
The sum 1 + 2 + 3 + ...+
Exercise9| FactorialofanintegerinPython
WriteaprograminPythonthataskstheusertoinputanintegernanddisplaysn
!
Solution
#-*-coding:utf-8-*-
Asktheusertoenterthevalueoftheintegern
n=int(input("Type a value of the integer n "))
#defineandinitializeanauxiliaryvariablej
j=0
foriinrange(1,n+1):
j = j * i
Factorial of n is : n ! = : j
Exercise10| PerimeterandareaofacircleinPython
WriteaprograminPythonthataskstheusertoentertheradiusofacircleandreturnsit.
theareaandtheperimeter.
Solution
#-*-coding:utf-8-*-
importthenumberpifromthemathlibrary
frommathimportpi
readthevalueofradiusr
r = int(input("Enter the value of the radius r: "))
calculationofthecircumferenceofthecircle
P=2πr
calculationoftheareaofthecircle
S = (π²) * (r²)
print("The perimeter of the circle with radius r =", r, "is P =", P)
The surface area of the circle with radius r =
Exercise11| DeterminethedivisorsofanintegerinPython
WriteaprograminPythonthataskstheusertoinputanintegernanddisplaysit.
allthedivisorsofthisnumber.
Solution
#-*-coding:utf-8-*-
n=int(input("Enter the value of the integer n "))
iteratethroughallintegerslessthanorequalton
foriinrange(1,n+1):
testifiisadivisorofn
if(n%i==0):
print("The number ", i, " is a divisor of ", n)
Exercise12| MultiplicationtableinPython
1)–Write a program in Python that asks the user to enter an integer n and to
displaythemultiplicationtableofthisnumber.
2)–Improvetheprogramsothatitdisplaysthemultiplicationtablesofallnumbers
between1and9.
Solution
Multiplicationtableofanintegerenteredonthekeyboard
#-*-coding:utf-8-*-
Readthevalueoftheintegern
n=int(input("Enter the value of n "))
The multiplication table of :
foriinrange(1,10):
print(i, " x", n, " = ", i * n)
Pythoncodethatprovidesthemultiplicationtablesforallnumbers1,2,3,…,9
#-*-coding:utf-8-*-
fornuminrange(1,10):
#insertseparator
print("--------------------------------------")
print("the multiplication table of : ",n," is :")
foriinrange(1,10):
print(i, " x ", n, " = ", i * n)
Whatisdisplayedatexecution:
————————————–
themultiplicationtableof:1is:
1 x 1 = 1
2 x 1 = 2
3 x 1 = 3
4 x 1 = 4
5 x 1 = 5
6 x 1 = 6
7 x 1 = 7
8 x 1 = 8
9 x 1 = 9
————————————–
themultiplicationtableof:2is:
1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
4 x 2 = 8
5x2=10
6x2=12
7x2=14
8x2=16
9x2=18
————————————–
themultiplicationtableof:3is:
1 x 3 = 3
2 x 3 = 6
3 x 3 = 9
4x3=12
5x3=15
6x3=18
7x3=21
8x3=24
9x3=27
————————————–
themultiplicationtableof:4is:
1 x 4 = 4
2 x 4 = 8
3x4=12
4x4=16
5x4=20
6x4=24
7x4=28
8x4=32
9x4=36
————————————–
themultiplicationtableof:5is:
1 x 5 = 5
2x5=10
3x5=15
4x5=20
5x5=25
6x5=30
7x5=35
8x5=40
9x5=45
————————————–
themultiplicationtableof:6is:
1 x 6 = 6
2x6=12
3x6=18
4x6=24
5x6=30
6x6=36
7x6=42
8x6=48
9x6=54
————————————–
themultiplicationtableof:7is:
1 x 7 = 7
2x7=14
3x7=21
4x7=28
5x7=35
6x7=42
7x7=49
8x7=56
9x7=63
————————————–
themultiplicationtableof:8is:
1 x 8 = 8
2x8=16
3x8=24
4x8=32
5x8=40
6x8=48
7x8=56
8x8=64
9x8=72
————————————–
themultiplicationtableof:9is:
1 x 9 = 9
2x9=18
3x9=27
4x9=36
5x9=45
6x9=54
7x9=63
8x9=72
9x9=81
Exercise13| QuotientandremainderoftheEuclideandivisionofabybinPython
WriteaprograminPythonthataskstheusertoentertwointegersaandb
andtodisplaythequotientandtheremainderoftheEuclideandivisionofabyb.
Solution
#-*-coding:utf-8-*-
Readthevaluesofaandb
a=int(input("Enter the value of the integer a: "))
b = int(input("Enter the value of integer b: "))
q equals a divided by b
r = a % b
The quotient of the Euclidean division of a by b is: q =
The remainder of the Euclidean division of a by b is: r =
Exercise14| PerfectsquareinPython
WriteaprograminPythonthataskstheusertoenteranintegernandto
displaywhetherthisnumberisaperfectsquareornot.
Solution
#-*-coding:utf-8-*-
Readthevalueoftheintegern
n=int(input("Type the value of n: "))
Weuseacounterj
j=0
foriinrange(0,n):
if(i**2==n):
j = j + 1
if(j>0):
The integer
else:
print("the integer ", n, " is not a perfect square")
Exercise15| TestifanumberisprimeornotinPython
WriteaprograminPythonthataskstheusertoenteranintegernandtoit
displaywhetherthisnumberisprimeornot.
Solution
#-*-coding:utf-8-*-
Readthevalueoftheintegern
n=int(input("Enter the value of n: "))
Weuseacounterthatcountsthenumberofdivisorsofn.
j=0
foriinrange(1,n+1):
if(n%i==0):
j=j+1
Wetestifthenumberofdivisorsofnis=2toconcludethatnis
first
if(j==2):
The number
else:
The number
Exercise16| TraversethecharactersofastringinPython
WriteaprograminPythonthatallowsyoutoiteratethroughanddisplaythecharactersofavariable.
[Link],fors="Python",theprogramdisplaysthecharacters:
P
y
t
h
o
n
Solution
1stmethod
#-*-coding:utf-8-*-
Asktheusertoenterastring.
s=input("Enter a string s:")
getthelengthofs
n=len(s)
foriinrange(0,n):
print(s[i])
2ndmethod
Asktheusertoenterastrings
s=input("Enter a string s:")
forxins
print(x)
Exercise17| NumberofoccurrencesofacharacterinastringinPython
WriteaprograminPythontodisplayforagivenstring,thenumber
[Link]="
[Link]»theprogrammustdisplay:
Thecharacter:"P"appears1timeinthestrings
Thecharacter:'y'appears1timeinthestrings.
Thecharacter:'t'appears1timeinthestrings
Thecharacter:'h'appears1timeinthestrings
Thecharacter:'o'appears2timesinthestrings
Thecharacter:"n"appears1timeinthestrings
Thecharacter:'.appears1timeinthestrings
Thecharacter:"r"appears1timeinthestrings
Thecharacter:'g'appears1timeinthestrings
Solution
#-*-coding:utf-8-*-
Python is a programming language
groupthecharactersofsinasettoavoidrepetitions
unique=set({})
forxins
ifxnotinunique:
[Link](x)
The number of occurrences of the character:
is:
"""
Whatdisplaysafterexecution:
Thenumberofoccurrencesofthecharacter:Pinthestringsis:1
Thenumberofoccurrencesofthecharacter:yinthestringsis:1
Thenumberofoccurrencesofthecharacter:tinthestringsis:3
Thenumberofoccurrencesofthecharacter:hinthestringsis:1
Thenumberofoccurrencesofthecharacter:ointhestringsis:3
Thenumberofoccurrencesofthecharacter:ninthestringsis:4
Thenumberofoccurrencesofthecharacter: inthestringsis:5
Thenumberofoccurrencesofthecharacter:einthestringsis:3
Thenumberofoccurrencesofthecharacter:sinthestringsis:1
Thenumberofoccurrencesofthecharacter:uinthestringsis:1
Thenumberofoccurrencesofthecharacter:linthestringsis:1
Thenumberofoccurrencesofthecharacter:ainthestringsis:4
Thenumberofoccurrencesofthecharacter:ginthestringsis:3
Thenumberofoccurrencesofthecharacter:dinthestringsis:1
Thenumberofoccurrencesofthecharacter:pinthestringsis:1
Thenumberofoccurrencesofthecharacter:rinthestringsis:2
Thenumberofoccurrencesofthecharacter:minthestringsis:2
Thenumberofoccurrencesofthecharacter:iinthestringsis:1
"""
Exercise18| PositionofacharacterinastringinPython
WriteaPythonprogramthataskstheusertoenterastringsandtoit
returnamessageindicatingwhetherthestringcontainstheletter'a'whileindicatingitsposition
[Link],iftheusertypesthestrings='language',theprogramreturns:Theletter'a'is
trouveàlaposition:1Lalettre‘a’setrouveàlaposition:4
Solution
#-*-coding:utf-8-*-
Asktheusertotypeinthevalueofs
s=input("Enter the value of s: ")
Getthelengthofthestrings
n=len(s)
Scanthestringswhilesearchingforthecharacter'a'
foriinrange(0,n):
Testiftheencounteredcharacterisequalto'a'
if(s[i]=='a'):
The character 'a' is located at position:
thechains)
Exercise19| ListtheelementsofalistinPython
WriteaprograminPythonthatallowslistingthestringsthatmakeupthelistl=["laptop",
“iphone”,“tablet”]toutenindiquantlalongueurdechaquechaine.
Solution
["laptop","iphone","tablet","printer","Ipad"]
iteratethroughtheelementsofthelistl
forxinl
print(x, ' is in list l, its length is: ', len(x))
Exercise20| Exchangethefirstcharacterandthelastcharacterofastring
WriteaprograminPythonthatswapsthefirstandlastcharacterofastring.
givenchain.
Solution
#-*-coding:utf-8-*-
defineanexampleofchains
[Link]
getthelengthofthestrings
n=len(s)
getthefirstcharacterofthestrings
first=s[0]
last=s[n-1]
extractthesubstringobtainedfromsbyignoringthefirstandthe
lastcharacter
s1=s[1:n-1]
buildanewstringbychangingthefirstandthelastcharacter
s2=last+s1+first
print(s2)
Exercise21|NumberofvowelsinastringinPython
WriteaprograminPythonthatcountsthenumberofvowelsinastring.
[Link]='anticonstitutionellement'theprogrammustreturnthemessage
Thechainunconstitutionallyhas10vowels.
Solution
definethevowelsinaset
vowels={'a','e','y','u','i','o'}
defineastring
unconstitutionally
getthelengthofthestrings
n=len(s)
initializethenumberofvowelsto0
number_vowels=0
traversethecharactersofthestrings
foriinrange(0,n):
if(s[i]in vowels):
number_vowels=number_vowels+1
print("The number of vowels in the string 's' is: ", number_vowels)
Exercise22| FirstwordofatextinPython
WriteaprograminPython,[Link]
Thetext:t='Pythonisawonderfulprogramminglanguage',theprogrammust
sendbackPython
Solution
#-*-coding:utf-8-*-
programthatdeterminesthefirstwordofastringinPython
defineastrings
Learn Python at [Link]
initializethefirstwordtoanemptystring
premierMot=""
initializethecounter
i=0
findthefirstspaceinthestring
while(s[i]!=""):
premierMot=premierMot+s[i]
i=i+1
The first word of the string s is:
Exercise23|DeterminetheextensionofafileinPython
WriteaprograminPythonthataskstheusertoenterthenameofafileandtoit
[Link],[Link],theprogramwilreturnthe
[Link].
Solution
#-*-coding:utf-8-*-
Asktheusertoenterafilename
file=input("Enterthenameofthefilewithitsextension:")
convertfiletolist
L = [Link](".")
fileExtension="."+L[-1]
print("The file extension is: ", extensionFichier)
Exercise24| PalindromeinPython
Apalindromeisawordwhoseorderoflettersremainsthesamewhenreadfromlefttorightorfromrighttoleft.
[Link]:'laval','radar','sos'...[Link]
asktheusertoenterawordandreturnwhetheritisapalindromeornot?
Solution
#-*-coding:utf-8-*-
Asktheusertoenteraword
word=input("Enteraword:")
reversetheword
inverse=word[::-1]
if(mot==inverse):
The word:
else:
The word:
Exercise25| ReverseastringinPython
[Link]
Iftheuserentersthewordpython,theprogramwilreturnnohtyp.
Solution
Firstmethod
#-*-coding:UTF-8-*-
Readthestringvariables
s=input("Type a string s: ")
getthereverseofthestrings
s1=s[::-1]
Secondmethod
#-*-coding:UTF-8-*-
Readthestringvariables
s = input("Enter a string s: ")
initializetheinversetoanemptystring
inv=""
constructionoftheinverseinarecursiveway
forxins:
inv=x+inv
print("The inverse of the string: '", s, "' is: ", inv)
Exercise26| Searchforwordsthatstartwiththeletterainatext
Writeaprogramthataskstheusertoenteratextandreturnsallthewords.
startingwiththelettera.
Solution
1stmethod
#-*-coding:UTF-8-*-
Read the string s
s=input("Type a character string s: ")
convertthestringsintoalist
s=[Link]()
lookforalltheelementsinthelistthatstartwiththeletter'a'
forxins:
if(x[0]=='a'):
The word:
2ndmethod
#-*-coding:UTF-8-*-
Read the chain s
s=input("Enter a string s: ")
convertthestringsintoalist
s=[Link]()
getthelengthofthelists
n=len(s)
searchfortheitemsinthelistthatstartwiththeletter'a'
foriinrange(0,n):
if(s[i][0]=='a'):
print("The word: '", s[i], "' starts with the letter 'a'")
"""
Meandyouarebeginners.
Youwillreceivethemessage:
Theword:'and'beginswiththeletter'a'
Theword:'are'beginswiththeletter'a'
"""
Exercise27|Functionthatcalculatesthesumandtheproductoftheelementsofalist
WriteaprograminPythonintheformofafunctionthatcalculatesthesumoftheelementsofalist.
[Link].
Solution
#-*-coding:UTF-8-*-
Functionthatcalculatestheproductoftheelementsofalist
defmult(l):
m=1
Creationoftheproductbygoingthroughtheelementsofthelist
forxinl:
m = m * x
returnm
print(mult([2,5,3]))
Functionthatcalculatesthesumoftheelementsofalist
defsum(l):
s=0
Creatingthesumbygoingthroughtheelementsofthelist
forxinl:
s = s + x
returns
print(sum([2,5,3]))
Exercise28| TestifalistorastringisemptyinPython
[Link].
characters.
Solution
Firstmethod
#-*-coding:UTF-8-*-
CheckifalistLisempty
#definealistL
L=list()
tryifthelistLisempty
ifL==[]:
ThelistLisempty
else:
ThelistLisnotempty
Testifastringisempty
defineastrings
s=""
Checkifastringsisempty
ifs=="":
Thestringsisempty
else:
Thelistisnotempty
2ndmethod
CheckifalistLeisempty
definealistL
L=list()
1)-TestifthelistLisemptyusingthefunctionlen()
iflen(L)==0:
ThelistLisempty
else:
ThelistLisnotempty
Testifastringisempty
defineastrings
s=""
Testifthestringsisemptyusingthelen()function
iflen(s)==0:
Thestringsisempty
else:
ThelistLisnotempty
Exercise29| RemoveduplicateelementsfromalistinPython
WriteaPythonprogramthatremovesduplicateelementsfromalist.
Solution
1stmethod
#-*-coding:UTF-8-*-
definesafunctionthatremovesduplicatesfromthelist
defremoveDuplicate(l):
defineandinitializethelistwithoutduplicateelements
unique=[]
Constructionofthelistwithoutduplicateelements
forxinl:
ifxnotinunique
[Link](x)
returnunique
Example
[2,7,13,2,17,13,2,7,13]
print(removeDuplicate(l))
2ndmethod
#-*-coding:utf-8-*-
definethefunctionthatremovesduplicateelementsfromalist
defremoveDuplicate(l):
convertthelistintoaset
SET=set(l)
reconvertthewholeintoalist
L=list(SET)
returnL
Example
[2,7,7,13,2,17,25,17,13,15,15,2,7,13]
print(removeDuplicate(l))
Exercice30|RecherchelesélémentscommunsàdeuxlistesenPython
WriteafunctioninPythonthatallowsustocomparetwolistsandindicatewhetherthesetwolists
haveacommonvalueornot.
Solution
#-*-coding:UTF-8-*-
defelementsCommon(l1,l2):
compteur=0
forxinl1:
ifxinl2:
counter=counter+1
ifcounter!=0:
returnTrue
else:
returnFalse
l1=[2,35,5,6,21]
l2=[2,13,5,7,19]
print(commonElements(l1, l2))
WhatdisplaysTrue
Exercice31|Extrairelalistedesentierspairsetlalistedesentiersimpairsd’uneliste
WriteaPythonprogramthatextractsthelistofevenintegersandthelistofoddintegers
ofalistofnumbers.
Solution
#-*-coding:UTF-8-*-
defextract(l):
pair=[]
impair=[]
forxinl:
if(x%2==0):
[Link](x)
else:
[Link](x)
The list of even integers is:
The list of odd integers is:
Testthealgorithm
l=[23,4,56,7,8,9,0,18,7,6,55,43,2]
print(extract(l))
"""
Whatdisplaysafterexecution:
Thelistofevenintegersis:[4,56,8,0,18,6,2]
Thelistofoddintegersis:[23,7,9,7,55,43]
"""
Exercise32| DeterminingallthelistsbypermutingalistinPython
WriteaPythonprogramthatreturnsallthelistsobtainedbypermutingtheelementsofalist.
data.
Solution
#-*-coding:UTF-8-*-
"""
importingtheitertoolsmodule:
Thismoduleimplementsmanyiteratorblocksinspiredbytheconstructions
APL,Haskell,andSML.
"""
importitertools
Usageexample
l=[1,2,3,4]
permutations=[Link](l)
L=list(permutations)
Thelistsobtainedbyswappingthetermsoflistl:L
Exercise33| Traversingastringwithastepof2inPython
WriteaprograminPythonthataskstheusertoenterastringofcharactersand
[Link]="Python",theprogram
returns'Pto'.
Solution
Firstmethod
#-*-coding:utf-8-*-
Read the string s
s=input("Enter the string s:")
s1=""
i=0
while(i<len(s)-1):
s1=s1+s[i]
i=i+2
print(s1)
2ndmethod
#-*-coding:utf-8-*-
"""
Read the string s
s=input("Enter the string s:")}
traversalofthestringswithstep=2
print(s[0:len(s):2])
Exercice34|Extrairelesnotessupérieuràlamoyenned’unelistedenotes
Etantdonnéelalistedesnotesdesélèves:notes=[12,04,14,11,18,13,07,10,05,09,15,
WriteaPythonprogramthatallowsyoutoextractfromthislistandcreateanotherlistthat
containsonlythegradesaboveaverage(grades>=10)
Solution
#-*-coding:utf-8-*-
notes=[12,4,14,11,18,13,7,10,5,9,15,8,14,16]
definethelistthatwillcontainthegradesaboveaverage
moyenne=[]
forxinnotes:
addonlythegrades>=10totheaveragelist
if(x>=10):
[Link](x)
Thelistcontainingonlythegradeshigherthantheaverage
average
Exercise35| ConvertaURLintoahypertextlink
WriteaPythonprogramthatconvertsaURLenteredfromthekeyboardintoalink.
Solution
#-*-coding:utf-8-*-
ReadURLaddress
url=input("Saisiruneurl:")
#Lireletextedulienhypertexte
text_lien=input("saisirletextedulien")
converttheurltexttoalink
url="<ahref='"+url+"'>"+text_lien+"</a>"
print(url)
#-*-coding:utf-8-*-
Example textwithsome spaces multiple"
Transformthetextintoalist
L = [Link]()
initializethetextwithoutspacestoanemptytext
texteSansEspace=""
Reconstructthetextbygoingthroughtheelementsofthelist.
forxinL:
texteSansEspace=texteSansEspace+x+""
print(textWithoutSpace)
Exercise37| CommonwordswithtwotextsinPython
WriteaPythonprogramthatgroupsinalistthecommonwordsfromtwostringss1.
ands2.
Solution
#-*-coding:utf-8-*-
defcommonWords(s1,s2):
L1=[Link]()
L2=[Link]()
communs=[]
forxinL1:
if(xinL2):
[Link](x)
returncommuns
Example
Pythonisahigh-levelprogramminglanguage
Pythonisaninterpretedlanguage
The list of common words between s1 and s2 is :
Whatitdisplaysatruntime:
Thelistofcommonwordsins1ands2is:['Python','is','a','language']
Exercise38| LongestwordinastringinPython
WriteaPythonprogramthatsearchesforthelongestwordinastring.
Solution
#-*-coding:utf-8-*-
defmotMax(s):
L=[Link]()
mot=""
forxinL:
if(len(x) > len(word)):
word=x
returnmot
Example
Python is an object-oriented programming language
print("The longest word in the string is: ", motMax(s))
Whatisdisplayedatruntime:
Thelongestwordinthestringis:programming
Exercise39| NumberofwordsinastringinPython
[Link]
thatthetextiswellformed(aspaceaftereachpunctuationandnospacebeforethepunctuation).
Solution
#-*-coding:utf-8-*-
Python is a programming language. Python is object-oriented.
Transformationofthestringsintoalist
L=[Link]()
RetrievingthenumberofelementsinthelistL
numberOfWords=len(L)
print("The number of words in the string s is : ", nombreMots)
Exercise40|Exchangethe1erandthelastcharacterofatextinPython
[Link]="Pyhon
isaprogramminglanguage",theprogramreturnsthestrings2="programmingisa
[Link]-formed(onespaceaftereachpunctuationand
nospacebeforepunctuation).
Solution
#-*-coding:utf-8-*-
Python is a programming language
TransformationofthestringsintoalistL
L=[Link]()
RetrievingthenumberofelementsinthelistL
n=len(L)
retrievingthefirstandlastelement
premier=L[0]
dernier=L[n-1]
WeremovethefirstandthelastelementofthelistL.
[Link](n-1)
[Link](0)
WereconvertthelistLintoastring
s1="".join(L)
swapthefirstandthelastelementinthestrings
last + s1 + first
print(s)
Exercise41| Numberofelementsinalistthataredivisiblebyagiveninteger
CreateaPythonfunctioncallednombreDivisiblesthatappliestoalistofnumbersand
anintegern,whichreturnsthenumberofelementsinthelistthataredivisiblebyn.
Solution
#-*-coding:UTF-8-*-
defnameDivisibles(l,n):
i=0
forkinl:
if(k%n==0):
i=i+1
returns
l=[12,4,7,9,11]
n=3
The number of elements in l that are divisible by
nombreDivisibles(l,n)
Exercise42| NumberofoccurrencesofagivenelementinPython
CreateafunctioninPythoncallednombreOccurences()thatappliestoalistLandanelementxas
parametersandwhichreturnsthenumberoftimestheelementxappearsinthelistLwithoutusingthe
count()function.
Solution
defnameOccurrences(L,x):
occ=0
forelementinL:
ifelement==x:
occ+=1
returnocc
L=[3,11,3,8,3,23,3,7,11,3]
print("The number of occurrences of 3 in the list is: ", nombreOccurences(L, 3))
Exercise43| InsertstarsbetweencharactersofastringinPython
CreateaPythonfunctionnamedInsertEtoile()thatplaces"stars"betweeneachcharacterofa
[Link]='Python',InsertEtoile(s)givesP*t*h*o*n
Solution
#coding:utf-8
definsertStar(s):
creationofanemptystringthatwillcontain
thecharactersofthestringsareseparatedbystars
"""
s2=""
#insert*betweenthecharactersofthestrings
forxins
s2=s2+x+"*"
returns2
Example:
Python
print(insertStar(s))
Exercise44| TransformthewordsofalisttouppercaseinPython
CreateaPythonfunctionnamedtoutEnMajuscule()thattransformsalistofstringsinto
anotherlistmadeupofuppercasestrings.
ExampleifL=["Python","is","a","programming","language"]
ThefunctionmustreturnthelistL2=["PYTHON","IS","A","LANGUAGE",
PROGRAMMATION
Solution
#coding:utf-8
defmaj(L):
Creationofanemptylisttoholdthewordsinuppercase
listMaj=[]
RetrievethewordsfromLandinserttheminuppercaseintothelist.
listMaj
forwordinL:
[Link]([Link]())
returnlistMaj
Testtheprogram
["Python","is","a","programming","language"]
print(maj(L))
Exercice45| NombredemajusculesetdeminusculesdansunechaineenPython
WriteafunctioninPythonthattakesastringasanargumentandreturnsthenumber
oflowercaseanduppercaseleterscontainedinthestrings.
Solution
#coding:utf-8
defnameMajMin(s):
Weinitializethenumberofuppercaseandlowercaseletterstozero.
nombreMaj=0
nombreMin=0
Wegothroughtheletersofstestingifthecharacterisuppercaseorlowercase.
forlettreins
if([Link]()):
nombreMaj=nombreMaj+1
[Link]():
nombreMin=nombreMin+1
return(upperCaseCount,lowerCaseCount)
Wearetestingthealgorithm
Python
print(nameUpperLower(s))
The number of uppercase letters is:
print("The number of lowercase letters is: ", nombreMajMin(s)[1])
Exercise46| ConversionofbinarytodecimalinalistinPython
WriteafunctioninPythonthatprovidesthelistofdigitsofanumberwritteninbase.
10withoutconvertingthenumbertoastringandwithoutusinganypredefinedfunctions.
Solution
Exercise47| listofcommonwordsintwotextsinPython
WriteanalgorithminPythonthatreturnsalistofwordscommonto
deuxtextes.ExemplesiT1=“Pythonestunlangagedeprogrammation”etT2=“Pythonestorientéobjet”
theprogrammustreturnthelistofcommonwordsL=['Python','is'].
Solution
#coding:utf-8
commonWords(T1,T2):
Converttextsintolists
L1=[Link]()
L2=[Link]()
initializationofthelistofcommonwordstoempty
communs=[]
WegothroughtheelementsofthelistL1andtesttheirmembershipto
L2
formotinL1:
ifmotinL2:
[Link](word)
returncommuns
Wearetestingthealgorithm
T1="Pythonestunlangagedeprogrammation"
Pythonisobject-oriented
print(commonWords(T1, T2))
["Python","is"]