Docsity

Riassunti di Computer Programming, Sintesi del corso di Programmazione Orientata agli Oggetti

Toggle sidebar
bg1
Sommario
CAPITOLO 1 - COMPUTER ............................................................................................................................ 3
COMPUTER SCIENCE AND 3 PHASES ..................................................................................................................... 3
CPU ............................................................................................................................................................. 4
RAM ............................................................................................................................................................ 4
SECONDARY MEMORY ................................................................................................................................ 4
SYNTAX AND SEMANTICS ............................................................................................................................ 4
FUNCTION ................................................................................................................................................... 4
PROGRAMMING ENVIRONMENT ................................................................................................................ 4
ANOTHER DEFINITION OF LOOP .................................................................................................................. 5
CHAOTIC FUNCTIONS .................................................................................................................................. 5
MAIN ........................................................................................................................................................... 5
SOFTWARE VS HARDWARE + PROGRAMMING ............................................................................................ 5
PROGRAM VS ALGORITHM .......................................................................................................................... 5
NATURAL LANGUAGE VS PROGRAMMING LANGUAGE ............................................................................... 5
HIGH LEVEL VS MACHINE LANGUAGE .......................................................................................................... 5
INTERPRETER VS COMPILER ........................................................................................................................ 6
USING FLOAT TO A CHAOTIC FUNCTION ...................................................................................................... 6
COMPUTER PROGRAM ................................................................................................................................ 7
SOFTWARE DEVELOPMENT PROCESS .......................................................................................................... 7
EXPRESSIONS .............................................................................................................................................. 7
CAPITOLO 2 – DEF LOOP ................................................................................................................................... 7
DECISIONS ............................................................................................................................................... 8
NESTING:.................................................................................................................................................. 8
DEFINITE LOOP= .................................................................................................................................... 8
FOR LOOP= .............................................................................................................................................. 8
COUNTED LOOP= ................................................................................................................................... 8
INDEFINITE LOOP= ............................................................................................................................... 8
WHILE LOOP (PRE TEST LOOP)= ............................................................................................................. 9
SENTINEL LOOP ..................................................................................................................................... 9
BREAK(): .................................................................................................................................................... 9
TYPE(): ....................................................................................................................................................... 9
# FUTURE VALUE OF AMOUNT INVESTED YEARLY ................................................................................. 9
# SUM OF NUMBERS ENTERED BY THE USER. .....................................................................................10
# SQUARE ROOT USING NEWTON'S METHOD. ......................................................................................10
GRAPHICS.................................................................................................................................................11
GUI .............................................................................................................................................................11
PIXEL VS BITS ..............................................................................................................................................12
WIN.SETCOORDS(O, 0, 10, 10) PER CAMBIARE LE COORDINATE -> MUTATOR .......................................................12
# THIS PROGRAM PRINTS THE SQUARES OF INTEGERS FROM .........................................................................12
# THIS PROGRAM CONVERTS A TIME PERIOD EXPRESSED IN SECONDS ..........................................................13
# A PROGRAM DEMONSTRATING THE USE OF CONDITIONS IN IF STATEMENT ................................................14
# THIS FUNCTION TAKES AN ARGUMENT N > 1 AND RETURNS TRUE IF N IS PRIME, OTHERWISE IT
RETURNS FALSE ..........................................................................................................................................14
# THIS PROGRAM TAKES USER'S INPUT N>1 AND OUTPUTS THE NUMBER ................................................15
# OF PRIME NUMBERS LESS THAN OR EQUAL TO N ....................................................................................15
FLOAT() ........................................................................................................................................................15
INT() ............................................................................................................................................................16
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a

Anteprima parziale del testo

Scarica Riassunti di Computer Programming e più Sintesi del corso in PDF di Programmazione Orientata agli Oggetti solo su Docsity!

Sommario

  • CAPITOLO 1 - COMPUTER
  • COMPUTER SCIENCE AND 3 PHASES.....................................................................................................................
  • CPU
  • RAM
  • SECONDARY MEMORY
  • SYNTAX AND SEMANTICS
  • FUNCTION
  • PROGRAMMING ENVIRONMENT
  • ANOTHER DEFINITION OF LOOP
  • CHAOTIC FUNCTIONS
  • MAIN
  • SOFTWARE VS HARDWARE + PROGRAMMING
  • PROGRAM VS ALGORITHM..........................................................................................................................
  • NATURAL LANGUAGE VS PROGRAMMING LANGUAGE
  • HIGH LEVEL VS MACHINE LANGUAGE
  • INTERPRETER VS COMPILER
  • USING FLOAT TO A CHAOTIC FUNCTION
  • COMPUTER PROGRAM
  • SOFTWARE DEVELOPMENT PROCESS
  • EXPRESSIONS
  • CAPITOLO 2 – DEF LOOP
  • DECISIONS
  • NESTING:..................................................................................................................................................
  • DEFINITE LOOP=....................................................................................................................................
  • FOR LOOP=
  • COUNTED LOOP=
  • INDEFINITE LOOP=
  • WHILE LOOP (PRE TEST LOOP)=
  • SENTINEL LOOP
  • BREAK():
  • TYPE():
  • FUTURE VALUE OF AMOUNT INVESTED YEARLY

  • SUM OF NUMBERS ENTERED BY THE USER.

  • SQUARE ROOT USING NEWTON'S METHOD.

  • GRAPHICS.................................................................................................................................................
  • GUI
  • PIXEL VS BITS
  • WIN.SETCOORDS(O, 0, 10, 10) PER CAMBIARE LE COORDINATE - > MUTATOR
  • THIS PROGRAM PRINTS THE SQUARES OF INTEGERS FROM

  • THIS PROGRAM CONVERTS A TIME PERIOD EXPRESSED IN SECONDS

  • A PROGRAM DEMONSTRATING THE USE OF CONDITIONS IN IF STATEMENT

  • RETURNS FALSE # THIS FUNCTION TAKES AN ARGUMENT N > 1 AND RETURNS TRUE IF N IS PRIME, OTHERWISE IT
  • THIS PROGRAM TAKES USER'S INPUT N>1 AND OUTPUTS THE NUMBER

  • OF PRIME NUMBERS LESS THAN OR EQUAL TO N

  • FLOAT()
  • INT()
  • STR()
  • EVAL()..........................................................................................................................................................
  • PARAMETERS – FORMAL AND ACTUAL VS VARIABLED
  • UNICODE (ORD, CHR)
  • STRING METHOD
  • SEQUENCE
  • THIS FUNCTION CHECKS WHETHER THE STRING GIVEN AS PARAMETER

  • IS A PALINDROME WORD OR NOT, REGARDLESS OF LETTER CASES

  • UNIMODAL(SEQ) FUNCTION CHECKS WHETHER THE NON-EMPTY NUMBER LIST SEQ IS UNIMODAL OR NOT

  • BITONIC(SEQ) CHECKS WHETHER THE GIVEN NUMBER LIST SEQ IS BITONIC OR NOT

  • WRITE A PROGRAM THAT CALCULATES WHETHER A YEAR IS A LEAP YEAR USING SOME ELIF

  • TUPLE:
  • DICTIONARIES
  • DICTIONARY METHODS
  • ARRAYS
  • BOOLEAN MATRIX AND/OR

CPU

  • True. CPU is the brain of the computer and stands for central processing unit. It is able to carry out all the basic operations and instructions of a program on data. Ex: sending data to the Main Memory. Data and Program (instructions) are stored in RAM in encoded form. The CPU executes the instructions repeating the “Fetch-Decode-Execute Cycle” : Retrieve a piece of (Instruction, Data) from RAM, Decode it to see what operation and operands it represents, carry out the appropriate action activating the necessary (CPU) inner circuitry ...lather, rinse, repeat! RAM
  • False. RAM (random access memory) is the main memory of a computer and the CPU can only access the info stored in the main memory. It is fast but volatile: when the power is off, everything, all the contents are lost.
  • True. All the information that your computer is currently working on is stored in the main memory SECONDARY MEMORY Cheap, more permanent storage, large capacity: magnetic, flash optical) but slow. SYNTAX AND SEMANTICS
  • False. Sintax is the form of the language and semantic it’s its meaning. FUNCTION
  • True. A function is a sequence of commands (called statements) for the Python interpreter to execute. PROGRAMMING ENVIRONMENT
  • False. A programming environment is not a place where programmers work. It is a software designed to help programmers write programs
  • True.

ANOTHER DEFINITION OF LOOP

  • False. A loop is useful in order to execute a command for a given number of times. So it tells python to repeat certain instructions over and over CHAOTIC FUNCTIONS
  • False. Chaotic functions can be computed but the results may be not very useful MAIN
  • The statements of a program are often placed in a function called main SOFTWARE VS HARDWARE + PROGRAMMING
  • The software is given by the programs that run the hardware, that is the physical machine. More over, the process of creating a software is called programming PROGRAM VS ALGORITHM
  • Both are a sequence of commands called statements for the python interpreter to execute to solve a problem. Specifically, a program is a specific implementation of an algorithm that can be executed by a computer NATURAL LANGUAGE VS PROGRAMMING LANGUAGE
  • The natural language is very ambiguous and imprecise to describe algorithms, in fact programs are expressed in a programming language, which is very precise and unambiguous. The first one is used by humans to communicate, while the second one is used for writing instructions for computers. HIGH LEVEL VS MACHINE LANGUAGE
  • High level language is designed to be used and understood by humans, but it must be translated into machine language (binary digits; not ascii [128 character, from 0 to 127] in main memory)

COMPUTER PROGRAM

 A detailed, step-by-step set of instructions telling a computer what to do. If we change the program, the computer performs a different set of actions or a different task. The machine stays the same, but the program changes! SOFTWARE DEVELOPMENT PROCESS

  1. Analyze the problem : figure out exactly the problem to be solved.
  2. Determine specifications: describe exactly what the program will do
  3. Create a design: formulate the structure, how the program gets worked out, developing algorithms, software architecture
  4. Implement the design: translate the design in a computer language, starting the code writing
  5. Test/ Debugging: finding bugs, errors
  6. Maintain the program: considering needs of users EXPRESSIONS Expression: a fragment of code whose evaluation produces new data value
  • literal: fragment of code representing some specific constant data
  • string: text/phrase/sentence as reference to by programmers
  • string literal: fixed text enclosed in single or double quotes New expressions can be obtained combining simpler expressions using math operators: +, - , *, /, ** Capitolo 2 – Def loop
  1. def main(): print("This program calculates the future value of a 10 - year investment.")
  2. principal = eval(input("Enter the initial principal: "))
  1. apr = eval(input("Enter the annual interest rate: ")) for i in range(10): principal = principal * (1 + apr) print ("The value in 10 years is:", principal) main() DECISIONS ONE WAY DECISION: if TWO WAY DECISION: if else MULTIWAY DECISION: if elif else NESTING: writing a decision structure (respectively loop, or function definition) into the body of another decision structure (resp. loop, or function) DEFINITE LOOP= is a loop that execute a known number of times. FOR LOOP= for defines a loop that iterates through a sequence of values. A Python for loop implements a definite loop. COUNTED LOOP= is a specific kind of definite loop that is designed to iterate a certain number of times. We have: for in range() INDEFINITE LOOP= it keeps iterating if certain conditions are met

def main(): n = eval(input("Please enter a whole number: ")) fact = 1 for factor in range(n,1,-1): fact = fact * factor print("The factorial of", n, "is", fact) main()

Sum of numbers entered by the user.

def main(): print("This program allows you to total up some numbers") print() n = int(input("How many numbers do you have? ")) total = 0 for i in range(n): num = float(input("Enter a number: ")) total = total + num print() print("The sum of the numbers is:", total) main()

Square root using Newton's method.

import math def main(): print("This program calculates square root using Newton's method.") print() x = float(input("Enter number to find the root of: ")) n = int(input("How many iterations should I use? "))

guess = x / 2. for i in range(n): guess = (guess + x/guess)/2. print() print("Approximate square root:", guess) print("Difference from math.sqrt:", math.sqrt(x) - guess) main() GRAPHICS >>> ### Open a graphics window >>> win = GraphWin('Shapes') >>> ### Draw a red circle centered at point >>> ### (100, 100) with radius 30 >>> center = Point(100, 100) >>> circ = Circle(center, 30) >>> circ.setFill('red') >>> circ.draw(win) >>> ### Put a textual label in the center of the circle >>> label = Text(center, "Red Circle") >>> label.draw(win) >>> ### Draw a square using a Rectangle object >>> rect = Rectangle(Point(30, 30), Point(70, 70)) >>> rect.draw(win) >>> ### Draw a line segment using a Line object >>> line = Line(Point(20, 30), Point(180, 165)) >>> line.draw(win) >>> ### Draw an oval using the Oval object >>> oval = Oval(Point(20, 150), Point(180, 199)) >>> oval.draw(win) GUI Most applications you’re familiar with have Graphical User Interfaces (GUI) that provide windows, icons, buttons and menus.

main()

This program converts a time period expressed in seconds

into the format HOURS:MINUTES:SECONDS

def main():

get input from user

seconds = int(input("Enter the number of seconds: "))

calculate nr. of hours

hrs = seconds // (60*60)

calculate the remaining seconds

rem_sec = seconds % (60*60)

calculate nr. of minutes

min = rem_sec // 60

calculate the remaining seconds

sec = rem_sec % 60

output the result in the format HOURS:MINUTES:SECONDS

print(seconds, " seconds correspond to ", hrs, ":", min, ":", sec, sep='') main()

A program demonstrating the use of conditions in if statement

for checking user input

def main(): inputNumber = float(input("Enter the course grade: ")) grade = int(inputNumber) if grade > 30 or grade < 18 or grade != inputNumber: print("Error: grade must be an integer") print(" between 18 and 30") else: print("Grade", grade, "accepted.")

Other instructions ...

main()

This function takes an argument n > 1 and returns True if n is

prime, otherwise it returns False

Notice, this function is not safe with respect to wrong argument

values def primality_test(n): prime_flag = True # this "flag" marks whether the number n is prime or not

loop a variable d through [2, 3, ..., n-1]

for d in range(2,n):

check whether n is divisible by d

Int() = convert expr to a integer value; “” Se inserisco valori misti, trasforma da int a float Str() = return a string representation of expr Eval() = evaluate string as a expression PARAMETERS – FORMAL AND ACTUAL VS VARIABLED The main purpose is to provide information from the caller to the function. Parameters provide the changeable context of a function call. The scope of a variable refers to the places in a program where it can be accessed Four step process   The calling program (the caller) suspends its execution at the point of the call.   The formal parameters of the called function get assigned the values supplied by the actual parameters in the call.   The body of the function is executed.   Control moves back to the point of the caller just after where the function was called. Formal parameters are variables in the function definition. Actual parameters are the values given to those variables when control transfers to the function. Difference between ordinary variables and parameters Parameters are like ordinary function variables in that they are local to the function and serve as "named values." They are different because they are automatically

assigned an initial value when the function is called. Normal local variables have to be assigned a value within the function definition. Unicode (ord, chr) standard encoding/decoding:  The ord (for ordinal) function returns the numeric code of a single character  The chr function converts a numeric code to the corresponding character. STRING METHOD  s.capitalize() – Copy of s with only the first character capitalized  s.title() – Copy of s; first character of each word capitalized  s.center(width) – Center s in a text field of given width:  s.count(sub) – Count the number of occurrences of substring sub in s  s.find(sub) – Find the first position where sub occurs (starts) in s  returns - 1 if sub does not occur in s  s.join(list) – Concatenate list of strings into one large string using s as separator  s.ljust(width) – Like center, but s is left-justified  s.lower() – Copy of s in all lowercase letters  s.lstrip() – Copy of s with leading whitespace(s) removed  s.replace(oldsub, newsub) – Replace occurrences of oldsub in s with newsub  s.rfind(sub) – Like find, but returns the right-most position

rev_word = reverse_word(word) return rev_word == word

unimodal(seq) function checks whether the non-empty number list seq is

unimodal or not def is_nondec(seq):

This function checks whether the given number list is monotonic non-decreasing

l = len(seq) if l <= 1: return True else: nondec_flag = True

scan the sequence to search for possible pair such seq[i] > seq[i+1]

for i in range(0,l-1): if seq[i] > seq[i+1]: nondec_flag = False return nondec_flag def is_noninc(seq):

This function checks whether the given number list is monotonic non-increasing

l = len(seq) if l <= 1: return True

else: noninc_flag = True

scan the sequence to search for possible pair such seq[i] < seq[i+1]

for i in range(0,l-1): if seq[i] < seq[i+1]: noninc_flag = False return noninc_flag def unimodal(seq): found_unimodal = False

loop pos through the positions of the sequence

for pos in range(0,len(seq)):

check whether the subsequence from the beginning to position pos-1 is non-

decreasing seq1 = seq[:pos] seq1_nondec = is_nondec(seq1)

check whether the subsequence from pos to the end is non-increasing

seq2 = seq[pos:] seq2_noninc = is_noninc(seq2) if seq1_nondec and seq2_noninc: found_unimodal = True return found_unimodal # Notice: thanks to for-loop above, this returns True iff the two checks of at least one iteration are successful