Docsity
Docsity

Prepara tus exámenes
Prepara tus exámenes

Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity


Consigue puntos base para descargar
Consigue puntos base para descargar

Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium


Orientación Universidad
Orientación Universidad


examen 2 lab, Exámenes de Fundamentos de la Informática

Asignatura: Fonaments d'informática, Profesor: germinal camps, Carrera: Enginyeria Informàtica, Universidad: UAB

Tipo: Exámenes

2015/2016

Subido el 01/12/2016

aolk
aolk 🇪🇸

5

(1)

1 documento

1 / 2

Toggle sidebar

Esta página no es visible en la vista previa

¡No te pierdas las partes importantes!

bg1
Sequences indexing
Base Types
Python 3 Basic Reference Card
©2012 - Laurent Pointal
Licence Creative Commons Attribution 2
Official Python docu mentation on
http://docs.python. org/py3k
0783 -192int
9.23 -1.7e-60.0float
True Falsebool
"One\nTwo" 'I\'m'str
"""X\tY\tZ
1\t2\t3"""
10-6
tab char
new line
multiline
Container Types
list [1,5,9] ["x",11,8.9] ["mot"] []
tuple (1,5,9) 11,"y",7.4 ("mot",) ()
dict
{1:"one",3:"three",2:"two",3.14:"π"}
{"key":"value"}
set
{}
{1,9,3,0}
◾ ordered sequence, fast index access, repeatable values
set()
◾ no a priori order, unique key, fast key access%; keys%= base types or tuples
{"key1","key2"}
unmodifiable
Variables assignment
x = 1.2+8+sin(0)
y,z,r = 9.2,-7.6,"bad"
value or calculation expression
variable name (identifier)
azAZ_ followed by azAZ_09
◽ diacritics allowed but should be avoided
◽ language keywords forbidden
◽ min/MAJ case discrimination
expression with just comas
unmodifiable,
ordered sequence of chars
dictionnary
integer, float, boolean, string
container with several
values (here a tuple)
variables
names
Identifiers
a toto x7 y_max BigOne
8y and
x+=3x-=2
increment
decrement
Conversions
for lists, tuples, char strings, …
int("15")
float("-11.24e8")
bool
str(78.3)repr("Text")
can specify integer number base in 2nd parameter
int(15.56)truncate decimal part (round(15.56) for rounded integer)
and for litteral representation
type(expression)
use comparators (with ==, !=, <, >, …), logial boolean result
see verso for string formating allowing finer control
":".join(['toto','12','pswd'])'toto:12:pswd'
joining string sequence of strings
"words with spaces".split() ['words','with','spaces']
"1,4,8,2".split(",")['1','4','8','2']
splitting string
dict([(3,"three"),(1,"one")]){1:'one',3:'three'}
list("abc")['a','b','c']
use each element
from sequence
set(["one","two"]){'one','two'}
use each element
from sequence
lst=[11, 67, "abc", 3.14, 42, 1968] lst[1]67
lst[-2]42
0 1 2 3 54
-6 -5 -
4
-3 -1-2
individual access to items via [index]
positive index
negative index
0 1 2 3 54 6
-6 -5 -4 -3 -1-2
negative slice
positive slice
access to sub-sequences via [start slice:end slice:step]
len(lst)6
lst[1:3]→[67,"abc"]
lst[::2]→[11,"abc",42]
lst[-3:-1]→[3.14,42]
lst[:3]→[11,67,"abc"]
lst[:-1]→[11,67,"abc",3.14,42]
lst[4:]→[42,1968]
lst[1:-1]→[67,"abc",3.14,42]
lst[:]→[11,67,"abc",3.14,42,1968]
missing slice indication → from start / up to end
Conditional Statement
if x==42:
# block if logical expression x==42 is true
print("real truth")
elif x>0:
# block else if logical expression x>0 is true
print("be positive")
elif bFinished:
# block else if boolean variable bFinished is true
print("how, finished")
else:
# block else for other cases
print("when it's not")
Boolean Logic Statements Blocks
parent statement:
statements block 1…
parent statement:
statements block 2…
next statement after block 1
indentation%!
Comparators: < > <= >= == !=
=
a and b
a or b
not a
logical and
logical or
logical not
one or other or both
twice simultaneously
if logical expression:
statements block
statements block executed
only if a condition is true
True
False
true constant value
false constant value
can go with several else if, else if... and only one final else,
example%:
lst[-1]1968
lst[0]11
last one
first one
x=None «%undefined%» constant value
Maths
Operators: + - * / // % **
× ÷
integer ÷ ÷ remain
abfrom math import sin,pi
' escaped
abs(-3.2)→3.2
round(3.57,1)→3.6
floating point numbers… approximated value!
sin(pi/4)→0.707…
cos(2*pi/3)→-0.4999…
sqrt(81)→9.0
log(e**2)→2.0
angles in radians
acos(0.5)→1.0471…
etc. (cf doc)
(1+5.3)*212.6
for variables, funct ions,
modules, classes names
Mémento v1.0.5a
pf2

Vista previa parcial del texto

¡Descarga examen 2 lab y más Exámenes en PDF de Fundamentos de la Informática solo en Docsity!

Sequences indexing Base Types

Python 3 Basic Reference Card

©2012 - Laurent Pointal Licence Creative Commons Attribution 2 Official Python documentation on http://docs.python.org/py3k int 783 0 - float 9.23 0.0 -1.7e- bool True False str "One\nTwo" 'I'm' """X\tY\tZ 1\t2\t3""" 10 - tab char new line multiline Container Types list [1,5,9] ["x",11,8.9] ["mot"] [] tuple (1,5,9) 11,"y",7.4 ("mot",) () dict {1:"one",3:"three",2:"two",3.14:"π"} {"key":"value"} set

◾ ordered sequence, fast index access, repeatable values set() ◾ no a priori order, unique key, fast key access ; keys = base types or tuples {"key1","key2"} unmodifiable Variables assignment x = 1.2+ 8 +sin( 0 ) y,z,r = 9.2,-7.6,"bad" value or calculation expression variable name (identifier) a‥zA‥Z_ followed by a‥zA‥Z_0‥ 9 ◽ diacritics allowed but should be avoided ◽ language keywords forbidden ◽ min/MAJ case discrimination expression with just comas unmodifiable, ordered sequence of chars dictionnary integer, float, boolean, string container with several values (here a tuple) variables names Identifiers ☺ a toto x7 y_max BigOne ☹ 8y and x+= 3 x-= 2 increment decrement Conversions for lists, tuples, char strings, … int("15") float("-11.24e8") bool str(78.3) repr("Text") can specify integer number base in 2nd^ parameter int(15.56) truncate decimal part (round(15.56) for rounded integer) and for litteral representation type( expression ) use comparators (with ==, !=, <, >, …), logial boolean result see verso for string formating allowing finer control ":".join(['toto','12','pswd']) 'toto:12:pswd' joining string sequence of strings "words with spaces".split() ['words','with','spaces'] "1,4,8,2".split(",") ['1','4','8','2'] splitting string dict([(3,"three"),(1,"one")]) {1:'one',3:'three'} list("abc") use each element ['a','b','c'] from sequence set(["one","two"]) {'one','two'} use each element from sequence lst=[11, 67, "abc", 3.14, 42, 1968] (^) lst[ 1 ] 67 lst[-2] 42 0 1 2 3 4 5 -6 -5 - 4 -3 -2 - positive index individual access to items via [ index ] negative index 0 1 2 3 4 5 6 negative slice -6 -5 -4 -3 -2 - positive slice access to sub-sequences via [ start slice : end slice : step ] len(lst) 6 lst[ 1 : 3 ]→[67,"abc"] lst[:: 2 ]→[11,"abc",42] lst[-3:-1]→[3.14,42] lst[: 3 ]→[11,67,"abc"] lst[:-1]→[11,67,"abc",3.14,42] lst[ 4 :]→[42,1968] lst[ 1 :-1]→[67,"abc",3.14,42] lst[:]→[11,67,"abc",3.14,42,1968] missing slice indication → from start / up to end Conditional Statement if x== 42 : # block if logical expression x==42 is true print("real truth") elif x> 0 : # block else if logical expression x>0 is true print("be positive") elif bFinished: # block else if boolean variable bFinished is true print("how, finished") else: # block else for other cases print("when it's not") Boolean Logic (^) Statements Blocks parent statement : statements block 1…parent statement : statements block 2…next statement after block 1 indentation! Comparators: < > <= >= == != ≤ ≥ = ≠ a and b a or b not a logical and logical or logical not one or other or both twice simultaneously if logical expression : statements block statements block executed only if a condition is true True False true constant value false constant value can go with several else if, else if... and only one final else, example : lst[-1] 1968 lst[ 0 ] 11 last one first one x=None « undefined » constant value Maths Operators: + - * / // % ** × ÷ integer ÷ ÷ remain ab from math import sin,pi… ' escaped abs(-3.2)→3. round(3.57, 1 )→3. ☝ floating point numbers… approximated value! sin(pi/ 4 )→0.707… cos( 2 pi/ 3 )→-0.4999… sqrt( 81 )→9.0 √ log(e* 2 )→2. angles in radians acos(0.5)→1.0471… etc. (cf doc)

for variables, functions, modules, classes… names Mémento v1.0.5a

"model {} {} {}".format(x,y,r) "{ selection : formating! conversion }" Selection parameter (apparition order by default): 2 → argument index 2 (the 3rd) y → argument named y "…".format(x=3,y=2,z=12) 0.name → attribute name of argument index 0 0[name] → value for key name of argument index 0 0[2] → value for index 2 of argument index 0 Formating parameter: ◽ filling : 1 char (followed by alignment!) ◽ alignment : < left, > right, ^ center, = on sign ◽ sign : + for >0 and <0, - only for <0, espace for > ◽ #: alternative representation ◽ minwidth : number, 0 at start for filling with 0 ◽. precision : decimal count for a float, max width ◽ type : integers: b binary, c char, d decimal (default), o octal, x ou X hexadecimal… float: e or E exponential, f or F fixed point, g ou G appropriate (default), % pourcent Conversion parameter: s → display string via str() r → representation string via repr() str Display / Input print("v=", 3 ,"cm :",x,",",y+ 4 ) print options: ◽ sep=" " (items separator, default space) ◽ end="\n" (end of print, default new line) ◽ file=f (print to file, default standard output) items to display: littéral values, variables, expressions loop on dict/set = loop on sequence of keys statements block executed as long Conditional loop statement as condition is true while logical expression : statements block s = 0 i = 1 while i <= 100 : # statement executed as long as i ≤ 100 s = s + i** 2 i = i + 1 print("sum:",s) initialisations before the loop condition with at least one variable value (here i)

s = ∑

i = 1 i = 100 i 2 ☝ make condition variable change statements block executed for each Iterative loop statement item of a sequence of values for variable in sequence : statements block s = "Some text" cpt = 0 for c in s: if c == "e": cpt = cpt + 1 print("found",cpt,"'e'") Go over sequence's values Count number of e in the string Go over sequence's index ◽ modify item at index ◽ access items around index (before/after) lst = [11,18,9,12,23,4,17] lost = [] for idx in range(len(lst)): val = lst[idx] if val > 15 : lost.append(val) lst[idx] = 15 print("modif:",lst,"-lost:",lost) Limit values greater than 15, memorisation of lost values. ☝ care to inifinite loops! initialisations before the loop loop variable, value managed by instruction for statement use slices to go over a subset of the sequence computed result after the loop formating directives values to format Strings formating Generator of int sequences Files s = input("Instructions:") ☝ input always return a string , convert it to required type (cf boxed Conversions on recto). frequently used in for iterative loops range returns a « generator », convert it to list to see the values, example: print(list(range(4))) range( 5 ) 0 1 2 3 4 range( 3 , 8 ) 3 4 5 6 7 range( 2 , 12 , 3 ) 2 5 8 11 range( [start,]stop [,step] ) f = open("fic.txt","w",encoding="utf8") storage of data on disk, and read back opening mode ◽ 'r' read ◽ 'w' write ◽ 'a' append… encoding of chars for text files: uft8 ascii latin1 … name of file on disk (+path…) file variable for operations f.write("coucou") writingtext file → read /write only strings , convert from/to required type. reading s = f.read(4) for line in f : # line processing block cf functions in modules os and os.path if char count not specified, read whole file s = f.readline() read next line f.close() ☝ dont miss to close file after use very common: iterative loop reading lines of a text file Function definition def fctname(p_x,p_y,p_z): """documentation""" # statements block, res computation, etc. return res function name (identifier) result value of the call. if no computed result to return: return None ☝ parameters and all of this bloc only exist in the bloc and during the function call (« black box ») named parametrs Function call r = fctname( 3 ,i+ 2 , 2 *i) one argument per parameter retrieve returned result (if necessary) Operations on sequences empty string if end of file len(seq)→items count min(seq) max(seq) sum(seq) sorted(seq)→sorted copy reversed(seq)→reversed copy enumerate(seq)→sequence (index,value) for for loops lists special lst.append(item) lst.extend(seq) lst.index(val) lst.count(val) lst.pop(idx) lst.sort() lst.remove(val) lst.insert(idx,val) "{:e}".format(123.728212) →'1.237282e+02' "{:f}".format(123.728212) →'123.728212' "{:g}".format(123.728212) →'123.728' default 0 not included