introduction to programming i - hacettepe Üniversitesibbm101/fall17/lectures/...about bbm 101...
TRANSCRIPT
Lecture#01– CourseIntroduction,WhatisComputation
Erkut Erdem,AykutErdem&AydınKaya//Fall2017 1
BBM101IntroductiontoProgrammingI
DrawingofAnalyticalEngine.Image: UniversityofCambridge
LectureOverview• Courseintroduction
• Whatiscomputation
2
Disclaimer:Muchofthematerialandslidesforthislecturewereborrowedfrom— RuthAnderson,MichaelErnstandBillHowe’sCSE140class
CourseStaff
• Instructors: AykutErdem,Erkut Erdem,AydınKaya
• TeachingAssistants:
– Necva Bölücü– SelmaDilek
– Selim Yılmaz
– Cemil Zalluoğlu 4
DonothesitatetoaskTAsforhelp!
AboutBBM101• Thiscourseteachescoreprogrammingconceptswithanemphasisondatamanipulationtasks fromscience,engineering,andbusiness
• Goal bytheendofthesemester:Givenadatasource andaproblemdescription,youcanindependentlywriteacomplete,usefulprogramtosolvetheproblem
5
• BBM103IntroductiontoProgrammingLaboratoryI− Studentswillgainskillstoapplytheconceptstorealworldproblems
LearningObjectives
• Computationalproblem-solving–Writingaprogramwillbecomeyour“go-to”solutionfordataanalysistasks.
• BasicPythonandCproficiency– Includingexperiencewithrelevantlibrariesfordatamanipulation,scientificcomputing,andvisualization.
6
WhatThisCourseisnot• A“skillscourse”inPython/C– …thoughyou’llbecomeproficientinthebasicsofthePython/Cprogramminglanguage
– …andyouwillgainexperiencewithsomeimportantPython/Clibraries
• A“project”course– theassignmentsare“real,”butareintendedtoteachspecificprogrammingconcepts
• A“softwareengineering”course– Programmingisthestartingpointofcomputerscienceandsoftwareengineering
7
Imagecredit:Google+user
Communication
• Website: http://web.cs.hacettepe.edu.tr/~bbm101/
• Seethewebsiteforalladministrativedetails
• Readthehandoutsandrequiredtexts,before thelecture
• Takenotes!
• FollowthecourseinPiazzahttps://piazza.com/hacettepe.edu.tr/fall2017/bbm101
8
TextBooks• ThePythonTutorial,availablefromthePythonwebsite.
– ThisisgoodforexplainingthenutsandboltsofhowPythonworks.
• IntroductiontoComputationandProgrammingUsingPython,SecondEdition,JohnV.Guttag,MITPress,August2016
• ThinkPython,2ndedition– Freelyavailableonlinein HTML and PDF.– Alsoavailableforpurchaseasaprintedbook,butdon'tbuythe
firstedition.– Thisbookintroducesmoreconceptualmaterial,motivating
computationalthinking.
• Thereisan interactiveversionof“HowtoThinkLikeaComputerScientist” (thefirsteditionof“ThinkPython”),whichletsyoutypeandrunPythoncodedirectlywhilereadingthebook.
• TheCProgrammingLanguage,2ndEdition,BrianKernighanandDennisRitchie,PrenticeHall,1988
9
GradingPolicy
• GradingforBBM101willbebasedon– twomidtermexam(25+30=55%)
– afinalexam(40%)
– classparticipation(5%)
• InBBM103,thegradingwillbebasedon– fiveassignments(75%)
– asetofquizzes(25%)(Yourlowest2quizgradeswillbedropped.)
10
AcademicIntegrity• Honestworkisrequiredofascientistorengineer.
• Collaborationpolicyonthecourseweb.Readit!– Discussionispermitted.– Carryingmaterialsfromdiscussionisnotpermitted.
– Everythingyouturninmustbeyourownwork.• Citeyoursources,explainanyunconventionalaction.
– Youmaynotviewothers’work.
– Ifyouhaveaquestion,ask.
• Wetrustyoucompletely.
• Butwehavenosympathyfortrustviolations– norshouldyou!
11
HowtoSucceed• Noprerequisites
• Non-predictorsforsuccess:– Pastprogrammingexperience– Enthusiasmforgamesorcomputers
• Programminganddataanalysisarechallenging
• Everyoneofyoucansucceed– Thereisnosuchthingasa“bornprogrammer”
– Workhard– Followdirections– Bemethodical– Think beforeyouact– Tryonyourown,thenaskforhelp– Startearly
12
PythonVersion
• WhateverIDEyouchoosetoworkwith,alwayssticktoPythonversion3.5.2
• Always usethisversiontocodeyourassignments.
14
“It’sagreattimetobeadatageek.”-- RogerBarga,MicrosoftResearch
18
“Thegreatestmindsofmygenerationaretryingtofigureouthowtomakepeopleclickonads”
-- JeffHammerbacher,co-founder,Cloudera
19
AllofScienceisReducingtoComputationalDataManipulationOldmodel:�Querytheworld� (Dataacquisitioncoupledtoaspecifichypothesis)Newmodel:�Downloadtheworld� (Dataacquisitionsupportsmanyhypotheses)– Astronomy:High-resolution,high-frequencyskysurveys(SDSS,LSST,PanSTARRS)– Biology:labautomation,high-throughputsequencing,– Oceanography:high-resolutionmodels,cheapsensors,satellites
40TB/2nights
~1TB/day100sofdevices
Example:AssessingTreatmentEfficacy
Zipcodeofclinic
Zipcodeofpatient
numberoffollowupswithin16weeksaftertreatmentenrollment.
Question:Doesthedistancebetweenthepatient’shomeandclinicinfluencethenumberoffollowups,andthereforetreatmentefficacy?
20
PythonProgramtoAssessTreatmentEfficacy# This program reads an Excel spreadsheet whose penultimate# and antepenultimate columns are zip codes.# It adds a new last column for the distance between those zip# codes, and outputs in CSV (comma-separated values) format.# Call the program with two numeric values: the first and last# row to include. # The output contains the column headers and those rows.
# Libraries to useimport randomimport sysimport xlrd # library for working with Excel spreadsheetsimport timefrom gdapi import GoogleDirections
# No key needed if few queriesgd = GoogleDirections('dummy-Google-key')
wb = xlrd.open_workbook('mhip_zip_eScience_121611a.xls')sheet = wb.sheet_by_index(0)
# User input: first row to process, first row not to processfirst_row = max(int(sys.argv[1]), 2)row_limit = min(int(sys.argv[2]+1), sheet.nrows)
def comma_separated(lst):return ",".join([str(s) for s in lst])
headers = sheet.row_values(0) + ["distance"]print comma_separated(headers)
for rownum in range(first_row,row_limit):row = sheet.row_values(rownum)(zip1, zip2) = row[-3:-1]if zip1 and zip2:
# Clean the datazip1 = str(int(zip1))zip2 = str(int(zip2))row[-3:-1] = [zip1, zip2]# Compute the distance via Google Mapstry:
distance = gd.query(zip1,zip2).distanceexcept:
print >> sys.stderr, "Error computing distance:", zip1, zip2
distance = ""# Print the row with the distanceprint comma_separated(row + [distance])# Avoid too many Google queries in rapid successiontime.sleep(random.random()+0.5)
23linesofexecutablecode!
21
Computingjobsarethe#1sourceofnewwagesintheUnitedStates
500,000currentopenings:Thesejobsareinevery industryandevery state,andthey’reprojectedtogrowattwicetherate
ofallotherjobs.
Slidecredit:code.org
Somestatistics(fromU.S.)
TheSTEM*problemisincomputerscience:
Sources:BureauofLaborStatistics,NationalCenterforEducationStatistics
71%ofall newjobsin
STEMareincomputing
8%ofSTEMgraduates
areincomputerscience
*STEM=Science,Technology,Engineering,andMathSlidecredit:code.org
Somestatistics(fromU.S.)
Computerscienceisjustaboutlearningtechnology
Computerscienceisaboutlogic,problemsolving,andcreativity
Somemaythink:
Slidecredit:code.org
WhatisKnowledge?• Declarativeknowledge
– Axioms(definitions)
– Statementsoffact
“yisthesquarerootofxifandonlyify*y=x”doesnothelptofindthesquareroot!
WhatisKnowledge?(cont’d.)• Declarativeknowledge
– Axioms(definitions)
– Statementsoffact
• Imperativeknowledge
– Howtodosomething
– Asequenceofspecificinstructions(whatcomputationisabout)
“yisthesquarerootofxifandonlyify*y=x” doesnothelptofindthesquareroot!
BabylonianmethodGetxasaninput1. Beginwithanarbitrarypositivenumbery02. Ifyn2 ≈x,stop
Elseletyn+1=(yn +x/yn)/2
3. Repeatstep(2)
(aninitialguess)(foundthesolution- yn)
(usethearithmeticmeantoapproximatethegeometricmean)
WhatisKnowledge?(cont’d.)• Anotherexample– Estimatinggreatestcommondivisor(gcd)
Declarativedefinition“disthegcd ofaandbifandonlyifdisthelargestpossibleintegersatisfyinga=d*xandb=d*ywithxandybeingtwopositiveintegers”
Imperativedefinition:Euclid’sformulaGet2positiveintegersaandb,a>=basinput1. Divideabyb,calltheremainderR
2. IfR=0,stopElseleta=bandb=R
3. Repeatstep2
(foundthesolution- b)
UseEuclid’sformulatocomputegcd(48,18).
WhatisaComputer?• Adevicethatexecutesasequenceofcomputationsandinstructions.
• Moderncomputersareelectronicanddigital.
• Doespencilandpapercountasacomputer?
Slidecredit:B.Huang
Programs• Thesesequencesofinstructionsandcomputationsiscalledaprogram.
• Wewillbedesigningprogramsinthiscourse.
• Theseprogramswillbebasedonalgorithms.– Algorithm - astep-by-stepproblem-solvingprocedure.
Slidecredit:B.Huang
WheredidtheTerm‘Computer’Originate?• ThedefinitionfromTheOxfordDictionary:
“Computer(noun).Apersonwhomakescalculations,especiallywithacalculatingmachine.”
CourtesyoftheLibraryofCongress
FixedProgramComputers• Developedtosolveaspecificproblem(set).
• Veryoldroots,oldperspectives,…– Abacus
– Antikythera Mechanism
– Pascaline
– LeibnizWheel
– Jacquard’sLoom
– BabbageDifferenceEngine
– TheHollerithElectricTabulatingSystem
– Atanasoff-BerryComputer(ABC)
– TuringBombe
– etc.
Antikythera Mechanism(100BC)• Firstanalogcomputer
• Anancientmechanicalcomputerdesignedtocalculateastronomicalpositions
©Rien vandeWeygaert
©Antikythera MechanismResearchProject
Pascaline (1642)• Blaise Pascal,1642
• Amechanicalcalculatorforperformingtwoarithmeticoperations:additionandsubtraction
©MarkRichards
©Britannica
LeibnizWheel(1694)• GottfriedWilhelmvonLeibniz,1694
• Amechanicalcalculatorforperformingallfourarithmeticoperations:addition,subtraction,multiplicationanddivision
CourtesyoftheDeutsches Museum,München
Jacquard’sLoom(1801)• Developedin1801byJoseph-MarieJacquard.
• Theloomwascontrolledbyaloopofpunchedcards.
• Holesinthepunchedcardsdeterminedhowtheknittingproceeded,yieldingverycomplexweavesatamuchfasterrate
AJacquardLoomworkshop- Germany,1858.Adoptedfrom:T.Cortina
BabbageDifferenceEngine(1832)
• CharlesBabbage,1832
• Amechanicalcalculatordesignedtotabulatepolynomialfunctions(canbeusedforsolvingpolynomialequations,curvefitting,etc.)
• A workingdifferenceenginewasbuiltin1991tocelebratethe200thanniversaryofBabbage'sbirth(LondonScienceMuseum).
• Itcouldhold8numbersof31decimaldigitseachandcouldthustabulate7thdegreepolynomialstothatprecision.
©MarkRichards
TheHollerithElectricTabulatingSystem• 1880Census. Took1,500people7yearstomanuallyprocessdata.
• HermanHollerith. Developedcountingandsortingmachinetoautomate.– Usepunchcardstorecorddata(e.g.,gender,age).
– Machinesortsonecolumnatatime(intooneof12bins).
– Typicalquestion:howmanywomenofage20to30?
• 1890Census.Finishedmonthsearlyandunderbudget!
punchcard(12holespercolumn)Hollerithtabulatingmachineandsorter
Adoptedfrom:Sedgewick andWayne
ModernPunchCards• Punchcards.[1900sto1950s]
– Alsousefulforaccounting,inventory,andbusinessprocesses.
– Primarymediumfordataentry,storage,andprocessing.
• Hollerith'scompanylatermergedwith3otherstoformComputingTabulatingRecordingCorporation(CTRC);thecompanywasrenamedin1924.
Adoptedfrom:Sedgewick andWayne
ModernPunchCards• Punchcards.[1900sto1950s]
– Alsousefulforaccounting,inventory,andbusinessprocesses.
– Primarymediumfordataentry,storage,andprocessing.
• Hollerith'scompanylatermergedwith3otherstoformComputingTabulatingRecordingCorporation(CTRC);thecompanywasrenamedin1924.
Adoptedfrom:Sedgewick andWayne
IBM80SeriesCardSorter,1949(650cardsperminute)
Atanasoff-BerryComputer(ABC)(1939)
• JohnVincentAtanasoff andCliffordBerry,1939-1942
• Oneofthefirstelectronicdigitalcomputingdevices
• Designedtosolveasystemoflinearequations
TuringBombe(1941)• AlanTuring,1939
• DevelopedtocrackGermanEnigmacodesduringWWII.
Enigmamachineinuse
AlanTuring• 1912-1954
• Consideredthe“father”ofmoderncomputerscience.
• Presentedformalismsforthenotionsofcomputationandcomputabilityinthe1930’s.
• WorkedatBletchleyParkinGreatBritainduringWWIItodevelopCollossus tohelpbreaktheGermanEnigmaCode.
• Developedthenotionin1950ofatestformachineintelligencenowcalledtheTuringTest.
• TheTuringAward,thehighestawardincomputing,isnamedinhonorofAlanTuring.
Slidecredit:G.Kesden
StoredProgramComputers• Problemsolving
• Whatifinputisamachine(description)itself?
• UniversalTuringmachines– Anabstractgeneralpurposecomputer
MachineInput Output
UniversalTuringMachines• Tape
– Storesinput,output,andintermediateresults.
– Onearbitrarilylongstrip,dividedintocells.
– Finitealphabetofsymbols.
• Tapehead– Pointstoonecelloftape.
– Readsasymbolfromactivecell.
– Writesasymboltoactivecell.
– Movesonecellatatime.
• Isthereamorepowerfulmodelofcomputation?No!
tapehead
tape
tape # 1 1 0 0 + 1 0 1 1 # ……
tape head
Adoptedfrom:Sedgewick andWayneMostimportantscientificresultof20thcentury?
QuestionsAboutComputation• Whatisageneral-purposecomputer?
• Aretherelimitsonthepowerofdigitalcomputers?
• Aretherelimitsonthepowerofmachineswecanbuild?
David Hilbert Kurt Gödel Alan Turing Alonzo Church John von Neumann
Adoptedfrom:Sedgewick andWayne
Church-TuringThesis(1936)
• Remark. "Thesis"andnotamathematicaltheorembecauseit'sastatementaboutthephysicalworldandnotsubjecttoproof.
• Usesimulationtoprovemodelsequivalent.– AndroidsimulatoroniPhone.
– iPhonesimulatoronAndroid.
• Implications.
– Noneedtoseekmorepowerfulmachinesorlanguages.
– Enablesrigorousstudyofcomputation(inthisuniverse).
• Bottomline. Turingmachineisasimpleanduniversalmodelofcomputation.
Turingmachinescancomputeanyfunctionthatcanbecomputed
byaphysicallyharnessable processofthenaturalworld.
Adoptedfrom:Sedgewick andWayne
Church-TuringThesis:Evidence• 8decadeswithoutacounterexample.
• Many,manymodelsofcomputationthatturnedouttobeequivalent.
Adoptedfrom:Sedgewick andWayne
modelofcomputation description
enhancedTuringmachines multipleheads,multipletapes,2Dtape,nondeterminism
untyped lambdacalculus methodtodefineandmanipulatefunctions
recursivefunctions functionsdealingwithcomputationonintegers
unrestrictedgrammars iterativestringreplacementrulesusedbylinguists
extendedL-systems parallelstringreplacementrulesthatmodelplantgrowth
programminglanguages Java,C,C++,Perl,Python,PHP,Lisp,PostScript,Excel
randomaccessmachines registersplusmainmemory,e.g.,TOY,Pentium
cellularautomata cellswhichchangestatebasedonlocalinteractions
quantumcomputer computeusingsuperpositionofquantumstates
DNAcomputer computeusingbiologicaloperationsonDNA
Babbage’sAnalyticalEngine(1834,1836)
• Designedaround1834to1836– wastobeauniversalmachinecapableofanymathematicalcomputation
– embodiesmanyelementsoftoday’sdigitalcomputer
– acontrolunitwithmoveablesprocketsonacylinderthatcouldbemodified
– separatedthearithmeticoperations(donebythemill)fromthestorageofnumbers(keptinthestore)• storehad1000registersof50digitseach
– Babbageincorporatedusingpunchedcardsforinput• ideacamefromJacquardloom
• NeverbuiltbyBabbageduetolackoffundsandhiseventualdeathin1871
Adoptedfrom:T.Cortina
AdaLovelace• 1815-1852
• DaughterofpoetLordByron
• TranslatedLuigiMenabrea’s articleonBabbage’sAnalyticalEnginetoEnglish– Quadrupleditslengthbyaddinglengthynotesanddetailed
mathematicalexplanations
• Referredtoastheworld’sfirstprogrammer– Describedhowthemachinemightbeconfigured(programmed)to
solveavarietyofproblems.
Slidecredit:G.Kesden
TheZuse Z3Computer(1941)• Konrad Zuse,1941
• TheoriginalZ3wasdestroyedinabombingraidofBerlinin1943.
• Zuse latersupervisedareconstructionoftheZ3inthe1960s(currentlyondisplayattheDeutsches MuseuminMunich)
ENIAC(Mauchly andEckert,USA,1946)
• Thefirstlarge-scalegeneral-purposeelectroniccomputerwithoutanymechanicalparts.
• DesignedtocalculateartilleryfiringtablesfortheUnitedStatesArmy'sBallisticResearchLaboratory
EDVAC(vonNeuman,USA,1951)• UnliketheENIAC,itusesbinaryratherthandecimalnumberingsystem
• Instructionswerestoredinmemorysequentiallywiththeirdata
• Instructionswereexecutedsequentiallyexceptwhereaconditionalinstructionwouldcauseajumptoaninstructionsomeplaceotherthanthenextinstruction
AdoptedfromG.Kesden
Summary
• Whatiscomputation?
–Whatisknowledge?
–Whatisacomputer?
–Whatisaprogram?
– Historyofcomputing