Starting from:

$25

CSE101 - Introduction to Programming 2 - Solved

 PROBLEMS
   Q Forprogram offers the user a choice to select one operation at a time. The operations are listed below:1. 2.1.thisWordDrequired.problem,isp andlay Wspeci icordsIfyouthe!! havewordWordtoexistswriteCounint:atheTheprogramtextuserile,thatisprintpromptedperformsits counttosomeandinputoperationsif notthe thenwordonprintwhosea text‘Wordcountile.doesTheis

not exist’.Displa(Notey Uniquethat aWwordords: isForanythissequencechoice, ofyoucharacters/digits/alphabetsjust print all the unique wordsenclosedpresentbetweenin thea

           3.4. text.Dcorresponding word counts. (space)eispplacelay aWllordWord: YouCounpromptts: ForHtheinthist: userUoption,se ato dicinputtyouionahavertwoy!)towords,printsayall theWord1uniqueandwordsWord2.andAlltheirthe

           5. Roccurrences of Word1 in the text ile are replaced by Word2.uit: The program ends.

Q

The program is menu-driven (see igure below). 

 

For option 2, print all the unique words present in the text separated by a semicolon (;)

 

Forreplaced by Word2 in the ile.choice 4, the user is required to enter 2 words, Word1 and Word2. All occurrences of Word1 are

 

●     The input text file will be provided.

●     Consider the following example regarding Option 2 and 3:

Let’s say that the text file has the following contents: “the the is a break the if if” Then the unique words in the text file are [“the”, “is”, “a”, “break”, “if”] (and not [“is”, “a”,

“break”]).

So the output for Option 2 will be: the ; is ; a ; break ; if For Option 3 the output becomes:

the : 3 is : 1 a: 1

break : 1

if : 2

●     For Option 4, you have to rewrite the contents in the input file itself by replacing Word1 with Word2. (No new file should be created). The options can be chosen in any order and hence the results should be in accordance with the updates made by the user.

●      In the final submission make sure that the input file is unaltered. Q2. Transformations!!

Intransformationwecreate3canD graphicsamake3D shapea simpleoperationssoftwarefromonegivenlikeonthatBlender,verticesthem.worksMakingandMaya,on theissoftwareableetc.,console.toweperformarelikeYourablesotask3istransformationtobeyondiscreateto writetheobjectsascopeprogramoperationsandof thisperformthatcoursewhichis ablesomebutareto

Scaling, Translation, and Rotation.

Creating the 3D shapeThethe ithprogramvertex of the 3D Shape.takes as input three lists x, y, and z each of length n where ( x[i], y[i], z[i] ) represent

 

For the above cuboidx = [0, 0, 0, 0, 4, 4, 4, 4]y = [0, 0, 3, 3, 3, 0, 0, 3]z = [0, 2, 2, 0, 0, 0, 2, 2]

TrAnythe transformed point (x’, y’, z’).ansftransformationormation T represented by a matrix (list of lists) can be applied on a point (x, y, z) to get A generic T can be represented as -

T =          

So, applying T on point (x,y,z) is done using -

 

Thereown T matrix representation.are 3 types of transformations as mentioned earlier and each type of transformation has it’s 1. ScalingFor scaling, to scale the point by sx , sy and sz ; T here is -

                   T =         

2.             TranslatingFor translating a point by tx, ty, and tz ; T here, is -

                   T =        

3.             RotationTherepresented by rotaterotation can happenaxes (along𝝓) where 𝝓 is the angle3 axes viz., x, y andby which you wish to rotate the point.z so each of these have different T matrix

 

 IThe irst line will containNext line will input the space-separated listNext line will input the space-separated listNext line will input the space-separated listNext line will input the number of transformation queries to apply which isNextnputq: lines will input a queryn which is the numberxyz of vertices the 3D shape hasq

Each query looks like -

For scaling, the query looks likeSwhere, sx sy sSzrepresents scaling and sx, sy and sz represent the amount of scale in each axes

For translating, the query looks likeTwhere, tx ty tTz represents translation and tx, ty and tz represent the amount of translation in each axes

For rotating, the query looks likeRwhere,which to rotate. Similarly, for y-axis we write x 𝝓 R represents rotation and x representsR y the𝝓 and for z axis we writeaxis of rotation and 𝝓R zrepresents𝝓        the angle by

OPrint the inal transformed 3 lists x, y and zutput:

 Also, store these lists in a text ile in the same format as input and output. Q3. Conversion of numbers !!.

Asuserecentlyotherthecommunicatewenumbersothertoplanets.allanother.foundknow,hand,withprogramwitheachForthatweForcreaturesradixexample,theseofcreaturescanthisthefordo10creaturestask,followingthenumbers, andCreaturesoflivingfollowingNASAthethefromthereoperations,computerrepresentationhiredZoralivingaoperations.maydifferentyou.planetonuseusesAsyoutheadifferentusesworld,numbersinmustprogrammerHuru-HuruFortheoctaleachasksodifferentradixwewithaprocess,representation.numberneedplanetattoradixradix.NASA,representtoyouusestwo,representedconvertOnyoumusthexadecimaletc.PlanetareaScientistsnumbernumbersScientistsmakeaskedEarth,inappropriatestringtoonradix.fromwantathumanscreateseveralNASAasoneOnantoa radixmenu-drivenFor functions.

inputnumber with the speci ied radix.and give the result in the other radix. You must handle it wisely if the user does not enter a

1)  Convert decimal to binary and vice-versa

2)  Convert decimal to hexadecimal and vice-versa3) Convert decimal to octal and vice-versa.

4)  Convert binary to hexadecimal and vice-versa.

5)  Convert binary to octal and vice-versa.

6)  Convert hexadecimal to octal and vice-versa.

7)  Convert number with radix A to radix B. Here A,B <= 36. In this case, you must take A,B as input.Type 1-6 are basic and you already know examples.

Example of Type 7) :

(GF12)18 = (98192)10                  (here, A = 18 , B = 10)

 (CA91)13 = (5C83)17      (here, A = 13, B = 17) Q4. Final Report!!

Theconductsimulate a JEE-type environment.Nationalthe JEETestingpaperAgencybut beforewill notthat,be abletheytowantholdtothistestyear’syouJEEif youpaper.canSo,writetheya haveprogramaskedthatyoucanto

The question paper has a total of 20 MCQ-type questions.

There“Admin”.are two folders representing the two high-level parties of the system which are “Student” and

In“StudentName_StudentNo.txt”.student’s submission to the questions.the                                      “Student”                             folder Eachtherestudentwill     hasbe theirtext ownilestextwithile. Eachthe textnamingile representsconventionthe

An example text ile for the Student Name - John with Student Number - 1357 is

 

Where, “-” represents that the student didn’t attempt that question There will be a “RegisteredStudents.txt” in the “Admin” folder. Example of a RegisteredStudents.txt -

 

Where, each line represents <StudentName> <StudentNo>

Inpaper.report a “FinalReport.txt” which has the name, number, and score of each student.the “Admin”Using thisfolderanswertherekey,is alsoyou anneed“AnswerKey.txt”to evaluate theilesubmissionswhich is theofanswereach student.key to theAnd,questioninally

Example of AnswerKey.txt -

 

Example of FinalReport.txt -

 

Where, each line represents <StudentName> <StudentNo> <StudentScore>

The scores are evaluated as follows -●

         ●● If the student’s answer matches the answer in the answer key they are awarded +4 marksIfthey are awarded -1 marksIf the student didn’t answer the question they are awarded 0 marks.the student answered the question and it does not match the answer in the answer key

YourFinalReport.txttask is to write a code that evaluates each student’s submission and inally create a

 Q5. Music Theory!

  MostcalledTypically,of“Nwetheoteyouhave”music. A note is a fundamental unit of musicmust12culturesnotes.have 7heardacrossof themthattheareglobemusicthe haveregularconsiststhethat is used to create melodies and riffs.notesmostof sevenandfundamental5notesof the(orextrasimilarity.thenotes“SapThistwhichSurassimilarityare”). Butcalledinis reality,

 Inkeys,sharp or lats(you don’t need to worry about the theory behind it).contain 12 notes!!)simplerand thisterms,patternIf youishaverepeatedever seen(alsoacalledpiano,anit consistsoctave, orof ”asaptblockak”ofin7 Hindi,white keysalthoughand 5itblackdoes

   The notes are typically denoted asThe C’ is the same note C, but in a hC Cigh#er oct D D#ave E F F(i.e# , G Gits # A A#frequen Bcy C is double ’                                                                                                      than the previous C !)

  Let’s de ine some terms and jargons!!:-●●● AD, leaving C# in between.) Remember these are not the random rules that I’ve made!!AD# will be called a Half Step).whalfKehyolestep,isThestethekeypdenoted,groupdenotedis generallyofasnotesasH, Wisdenoted,theisfollowingthejumpjumpbyfromsomewhatfromtheisprotocolsoneonecallednotenotetheto(toyesROOTthethewe3immediaterdhavenotenote. protocolsFor(i.e,nextexample,a jump(i.e,infromfrommusicA keyDC astotoof

well!).A‘C’Shas the root node as C.cale is

mentionedA

  → To create a major scale based upon a root note, we follow the rule:i.e.,another●if weand,Whaveto2. ME inor(aFor Sgroupcaleaexample,majorof notesscalea C scale).selectedwithRoot Wroot)A) to.W HscalefromnoteF (Wfromhasthe WC, W HwetwoE12), willthenfundamentalspopularjumpanothervariantsa wholeWnotestocalledGstep, thenwith(1W.WaM) totoajorrootAD,, SThenthennotecale

to

W to B, and inally to(fromformC’ D),(after half step from BThen half step (H

So the notes of the major scale in C (i.e, with root node C) are C, D, E, F, G, A, B, C’

→ To create a minor scale based upon a root note, we follow the rule:I.e, if we have to form a minor scale withRooroott W H Cnote’ W W HC, we Wwill W                                      follow the jumps (in W or H) and the

notes we will be getting are: C D D# F G G# A#

  ‘sBased upon this logic, You have to perform this task:-First,cale12Myouajnotesor.twillxt’inbeandseparatecreating‘scaleMlines.inaofunctionr.tSimilarly,xt’. ‘scaleMajor.txt’note‘scaleMinor.txt’Create(). Thiswill containwillfunctioncontainnotesshouldnotesof createtheofmajorminorseparatescale,scaleilesforfor eacheachcalledofof the 12 notes in separate lines. After having written this information, you must close the ile.the

  Youfunctionsnotes in the key of that root note.will beacceptcreatinga roottwonotefunctionsas a parametercalled major(upperNotescase).(rooThent) andtheseminorwillNotesreturn(roothet).correspondingBoth of these

Youseparate lines.will be accepting the user’s input for the root note and the type of scale (“Major” or “Minor”) in

  BasedmajorNotes()respectivelyupon thedependingandtypeminorNotes()of uponscale, theyoumusttypewill bebeofcallingrescaleadinmgbeingatjohreNoilestaskedess(croaloetbyM)ajoortherm.txintuser,orNandotandescsa(rleoreturnMoti)n.or.Bothtxthet, space-separated notes present in that scale.

 

 

NOTEmust be followed as has been mentioned.- File handling is mandatory for this program. All the steps for reading and writing to the iles

 QGiven a 2d square matrix of size NxN, you are asked to traverse over matrix and print elementpresent in the matrix in the order it has been traversed. You must irst ask the user to give matrixinput then create a menu for speci ied types of traversal, then ask the user to choose one of themand print the required traversal. You must make your code generalize so that it works properly forany given N.6.

 2)3)4)5)6)1) Normal traversal( from left to right for each row)Alternating traversal ( irst left to right for the irst row, then right to left for the second row,then left to right for the third row, and so on.)Spiral traversal from outer to inwardsBoundary traversal.(First, traverse the upper boundary from left to right, then rightboundary from up to down, then bottom boundary from right to left and at last from leftboundary from down to up)Diagonal traversal from right to leftDiagonal traversal from left to right.

Sample case:

Consider matrix with N = 4:

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

Normal Traversal : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Alternating traversal : 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13

Spiral Traversal : 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

Boundary traversal : 1 2 3 4 8 12 16 15 14 13 9 5

Diagonal traversal from right to left : 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Diagonal traversal from left to right : 4 3 8 2 7 12 1 6 11 16 5 10 15 9 14 13

 BONUS PROBLEMS
   B1Sinceilethe concepts that you can apply. Ghandling,thisenerate youspeci ichaveandDr.been task,TJaloteest!workingyouwantsneedontototestthecreatewhetherfundamentals2 pythonyou areiles.as wellableIn as,tothecreatehaveirstlearnedilea programcallednewc‘asthatdataes.phandlesystructures’,you mostneedandofto

create at least two mandatory functions-For

  result(s).IngInef●unnercatitoenD1a(t)a,(),youyouneedneedNto)for. For this particulartoForde ineinputs,accepteachinanyanotherNofthecomputationalnumbertheusertextinputs,task, you have either of these two options:inputofile.times.youRememberfortasktheneedTheseofnumberyourtoinputsthiscallchoice.outputoffuwouldinput-outputnctionItileshouldhave1must().toThereturnbecorrespondpairs,storedresultsometheyofin would like to generate(sayYoudifferentcan ask textmustthe useriles.be stored

function1()N

●    toYourespectively)thecaninputusebeingrandom()providedfunction(Hintto: yougeneratecan addrandomnumbersdata.to Afterthe inputthat,andalloutputthe stepsile remainnames, similar to the previous one.

  Infunctions.the second ile calledte‘ st.py’, you need to mandatorily use‘cases.py’. And two mandatory

Themust callThe function,resulttextfuncofttfile),ieuosnntic2nt(ig)ocorresponding(n), to perform the operation on2(must), mustreadbethetomatchedinputsthe correctfromto thethethe input read from text ile.input.outputtext ilesIf (allwhichgeneratedsuchagain,outputsbyghasenehavetoratbeeDbeenareadta()frommatched. Thentheit successfully, It should return “SUCCESS”, Otherwise, “FAILED”.output

  NOTEYou are also free to return any number or type of values from those functions. Every input passed tothe functions,NOTEimplement the same operation as function1 but, differently (for example, if function1 uses for loopfor iteration, function2() could use other iterative strategies).12:: you are free to customize all the functions,The function implementation in function1()function1()andfunction2()must havewith different names and number of parameters.is also left on your choice. function2() mustbeen read from text iles.

Also, two skeleton iles ‘cases.py’ and ‘test.py’, would be shared with the students, and they can editthem too.

NOTE:All the related and relevant iles have to be stored in a single folder named ““.py” ile speci ic to this question has to be present in this folder only, with the naming conventionmentioned earlier. A2_2021XXX_B1”. The

B2Doja.             Dog and DJ Snack are 2 very popular, rich singers with many grammys. Moreover they bothas they can for the fans to stay in the city of FanVille.win a grammy every year. They both love their fans and want to buy as many skyscrapers

Forgrammyreputation rises for DJ Snack when he buys a skyscraper.Sincereputationavailable.HenceeverythetoiskeepskyscraperButsingingtheas duetheynumberthingstoindustrycan.someoffair,ofheightSogrammystheyweirdtheyishbothcompetitive,DojabothlawsshedecideDogdecideinhasFanville,buys,attoDojatothebuyitbuytimegivesDogskyscrapersonlythesheandheroneskyscraperbuysaDJskyscraperfanonSnackthereputationalternateskyscraper.withcompetecantheyearsofbehmaximumboughtInto* withgrammy.agetsimilarDojainasheightamuchHereyear.way,Dog going irst.

the singers. As a programming student you decide to write a python program to ind this out.whenYou, asalla thefan skyscrapersof both DojaareDogsoldandout.DJ Snack,You alsowantwantto indto showout whothe skyscraperswill have moreownedfan reputationby each of

The initial number of Grammys with Doja Dog and DJ Snack are P, Q respectively.TheFanVille can be:0000000FanVille city is M units tall and has N skyscrapers. If M = 6 and N = 7, a possible layout for 0000100

whereheights of skyscrapers are 2, 3, 4, 1, 5, 3 and 3 respectively.11111111110111011011100101000 represents the sky and a column of 1s is a skyscraper. In the above example, the

Input:First line contains 2 integers P, QSecond line contains 2 integers M, NNext M lines contain 1 string each of length NOutput:First line: Total reputation of Doja DogSecond line: Total reputation of DJ SnackNextand skyscrapers owned by DJ Snack as S (see test case)M lines contain a inal layout of FanVille i.e. print each skyscraper owned by Doja Dog as D

Example Test Case:Input:1 1

6000000100011011111111111 4

Output:14 16

000000000SDDSSDDSDDSDDS0

Explanation:Year 1:Doja5 reputationDog initially has 1 grammy and buys skyscraper at index 2 which has height 5 to get 5*1 =

Year 2:Doja Dog and DJ Snack both win a grammyDJreputationSnack now has 2 grammys and buys skyscraper at index 3 which has height 4 to get 4*2 = 8

Year 3:Doja Dog and DJ Snack both win another grammyDojareputationDog now has 3 grammys and buys skyscraper at index 1 which has height 3 to get 3*3 = 9

Year 4:Doja Dog and DJ Snack both win another grammyDJreputationSnack now has 4 grammys and buys the last remaining skyscraper of height 2 to get 2*4 = 8 Total reputation for Doja Dog = 5+9 = 14Total reputation for DJ Snack = 8+8 = 16

Sinceskyscrapers to Ds.Similarly, we turn 1s at indexes 0 and 3 to Ss because they are owned by DJ Snack.000000000SDDSSDDSDDSDDS0 the skyscraper at indexes 1 and 2 are owned by Doja Dog, we turn the 1s in those

Assumptions and clari ications:Both Doja Dog and DJ Snack start with 0 fan reputation.Each skyscraper must have height atleast 1.P, Q > 0Ifthem.there are 2 skyscrapers with the same maximum height, then the singers can buy any one of

More products