computer languages i

24
Computer Languages I Dr. Ahmed Afifi Lecture-3: Data structure cont.

Upload: khangminh22

Post on 23-Nov-2023

0 views

Category:

Documents


0 download

TRANSCRIPT

Computer Languages I

Dr. Ahmed Afifi

Lecture-3: Data structure cont.

Tuples

- Seemingly similar to lists.

myTuple = (1, 2, 3)print myTuple[1]# 2print myTuple[1:3]# (2, 3)

Tuples are immutable

- Unlike lists, we cannot change elements.

>>> myTuple = ([1, 2], [2, 3])>>> myTuple[0] = [3,4]

Traceback (most recent call last):File "<stdin>", line 1, in <module>

TypeError: ’ tuple’ object does notsupport item assignment

>>> myTuple[0][1] = 3>>> myTuple([1, 3], [2, 3])

Packaging and unpacking

t = 1, 2, 3x, y, z = tprint t # (1, 2, 3)print y # 2

Functions with multiple return values

def simple_function():return 0, 1, 2

print simple_function()# (0, 1, 2)

Dictionaries

>>> d = {}>>> d[1] = "one">>> d[2] = "two">>> d{1: ’ one’ , 2: ’ two’ }>>> e = {1: ’ one’ , ’ hello’ : True}>>> e{1: ’ one’ , ’ hello’ : True}

- A dictionary is a collection of key-value pairs.

- An example: the keys are all words in the English language, and their

corresponding values are the meanings.

- Dictionaries are defined as:

Note how we can add more key-value pairs at any time. Also, only condition on

keys is that they are immutable.

Dictionaries

>>> d = {1: ’ one’ , 2: ’ two’ }>>> d[1] = ’ three’>>> d{1: ’ three’ , 2: ’ two’ }

- No duplicate keys, old value gets overwritten instead!

- We can access values by keys,

>>> d = {1: ’ one’ , 2: ’ two’ }>>> print d[1]

- Furthermore, we can check whether a key is in the dictionary by,

>>> <key> in <dict>

Dictionaries

>>> d = {1: ’ one’ , 2: ’ two’ , 3: ’ three’ }>>> for key, value in d.items():... print key, value...1 one2 two3 three

- Print all key-value pairs of a dictionary

Sets

>>> basket = [’ apple’ , ’ orange’ , ’ apple’ ,’ pear’ , ’ orange’ , ’ banana’ ]>>> fruit = set(basket) # create a set>>> fruitset([’ orange’ , ’ pear’ , ’ apple’ , ’ banana’ ])>>> ’ orange’ in fruit # fast membership testingTrue>>> ’ crabgrass’ in fruitFalse

- Sets are an unordered collection of unique elements

Set comprehensions

>>> a = {x for x in ’ abracadabra’ if x not in ’ abc’ }>>> aset([’ r’ , ’ d’ ])

Strings

- Strings hold a sequence of characters.

- Strings are immutable.

- We can slice strings just like lists and tuples.

- Between quotes or triple quotes.

- We can turn anything in Python into a string using str, This includes

dictionaries, lists, tuples, etc.

String formatting

- Special characters: \n, \t, \b, etc

- Add variables: %s, %f, %e, %g, %d, or use format.

>>>fl = 0.23>>>wo = ’ Hello’>>>inte = 12>>>print "s: {} \t f: {:0.1f} \n i: {}". format(wo, fl, inte)# s: Hello f: 0.2# i: 12

String: Split

- To split a string, for example, into separate words, we can use split().

>>>text = ’ Hello, world!\n How are you?’text.split()# [’ Hello,’, ’ world!’, ’ How’, ’ are’, ’ you?’]

- What if we have a comma separated file with numbers separated by

commas?

>>>numbers = ’ 1, 3, 2, 5’>>>numbers.split()# [’1,’, ’3,’, ’2,’, ’5’]>>>numbers.split(’ , ’ )# [’1’, ’3’, ’2’, ’5’][ int(i) for i in numbers.split(’ , ’ )]# [1, 3, 2, 5]

String: join

- We can use join to create a string from a list.

>>>words = [’ hello’ , ’ world’ ]‘’.join(words)#‘helloworld’‘ ’.join(words)#‘hello world’‘,’.join(words)# ‘hello, world’

Formatted Output

- Formatting the old way:

>>> print “ some string %d other string %f” %(value1, value2)

# Ex>>> print “Art: %d, price per Unit %8.2f” %(453, 59.058)# Art: 453, price per unit 59.06

%[flags][width][.precision]type

- The general form of formatting is:

Formatted Output

- Formatting the old way:

Conversion Meaningd Signed integer decimal.

i Signed integer decimal.

o Unsigned octal.

u Unsigned decimal.

x Unsigned hexadecimal (lowercase).

X Unsigned hexadecimal (uppercase).

e Floating point exponential format (lowercase).

E Floating point exponential format (uppercase).

f Floating point decimal format.

F Floating point decimal format.

g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.

G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.

c Single character (accepts integer or single character string).

r String (converts any python object using repr()).

s String (converts any python object using str()).

% No argument is converted, results in a "%" character in the result.

Formatted Output- Formatting the old way:

>>> print "%10.3e"% (356.08977)3.561e+02>>> print "%10.3E"% (356.08977)3.561E+02>>> print "%10o"% (25)

31>>> print "%10.3o"% (25)

031>>> print "%10.5o"% (25)

00031>>> print "%5x"% (47)

2f>>> print "%5.4x"% (47)002f>>> print "%5.4X"% (47)002F>>> print("Only one percentage sign: %% " % ())

Formatted Output- Formatting the old way:

>>> print "%#5X"% (47) 0X2F>>> print "%5X"% (47) 2F>>> print "%#5.4X"% (47) 0X002F>>> print "%#5o"% (25) 0o31>>> print "%+d"% (42) +42>>> print "% d"% (42) 42>>> print "%+2d"% (42) +42>>> print "% 2d"% (42) 42>>> print "%2d"% (42) 42

Flag Meaning

# Used with o, x or X specifiers the value is preceded with 0, 0o, 0O, 0x or 0X respectively.

0 The conversion result will be zero padded for numeric values.

- The converted value is left adjusted

If no sign (minus sign e.g.) is going to be written, a blank space is inserted before the value.

+ A sign character ("+" or "-") will precede the conversion (overrides a "space" flag).

Formatted Output- Formatting, the Pythonic way:

Using keyword parameters

Formatted Output- Formatting, the Pythonic way:

>>> "First argument: {0}, second one: {1}".format(47,11) 'First argument: 47, second one: 11'>>> "Second argument: {1}, first one: {0}".format(47,11) 'Second argument: 11, first one: 47'>>> "Second argument: {1:3d}, first one: {0:7.2f}".format(47.42,11) 'Second argument: 11, first one: 47.42'>>> "First argument: {}, second one: {}".format(47,11) 'First argument: 47, second one: 11'>>> # arguments can be used more than once:... >>> "various precions: {0:6.2f} or {0:6.3f}".format(1.4148) 'various precions: 1.41 or 1.415'>>>

Formatted Output- Formatting, the Pythonic way:

>>> "{0:<20s} {1:6.2f}".format(‘Art & Math:', 6.99)'Art & Math: 6.99'>>> "{0:>20s} {1:6.2f}".format('Art & Math:', 6.99)' Art & Math: 6.99'>>> "{0:>20s} {1:6.2f}".format('Art & bio:', 7.99)' Art & bio: 7.99'>>> "{0:<20s} {1:6.2f}".format('Art & bio:', 7.99)'Art & bio: 7.99'>>> "{0:<20} {1:6.2f}".format('Art & bio:', 7.99)'Art & bio: 7.99'>>> "{0:>20} {1:6.2f}".format('Art & bio:', 7.99)' Art & bio: 7.99'>>>

It's possible to left or right justify data with the format method. To this end, we can

precede the formatting with a "<" (left justify) or ">" (right justify).

File I/O- How to read from and write to disk?

o We can instantiate a file object using open or file

f = open(filename, option)

filename: path and filenameoption:

'r' read file'w' write to file'a' append to file

We need to close a file after we are done: f.close()

File I/O- Using with open as f

o Very useful way to open, read/write and close file:

>>> with open(<filename>, ‘r’) as f:print f.read()

- .read() : reads the entire file.

- .readline(): reads a single line per call

- .readlines(): returns a list with lines (splits at new line)

o Another fast option to read a file:

>>> with open(<filename>, ‘r’) as f:for line in f:

print line

File I/O- Writing to file

O Using write()

>>> with open(<filename>, ‘w’) as f:f.write(<something>)

# write elements of list to filewith open(filename, ‘w’) as f:

for x in xs:f.write(‘{}\n’.format(x))

# write elements of dictionary to filewith open(filename, ‘w’) as f:

for k, v in d.iteritems():f.write(‘{}: {}\n’.format(k, v))