Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Extended Introduction to Computer Science CS1001.py Lecture 4: Functions & Side Effects ; Integer Representations: Unary, Binary, and Other Bases Instructors: Daniel Deutch, Amiram Yehudai Teaching Assistants: Amir Rubinstein, Michal Kleinbort School of Computer Science Tel-Aviv University, Fall Semester, 2014/15 http://tau-cs1001-py.wikidot.com Reminder: What we did in Lecture 3 (Highlights) I Additional operations on lists and strings, e.g. slicing. I Functions I Equality and Identity I Mutable vs. immutable classes I Effects of Assignments I Python’s Memory Model I Un-assignment: Deletion 2 / 31 Lecture 4: Planned Goals and Topics 1. More on functions I I I Tuples and lists. Multiple values returned by functions. Side effects of function execution. 2. Integer representation (if time allows) I I Natural numbers: Unary vs. binary representation. Natural numbers: Representation in different bases (binary, decimal, octal, hexadecimal, 31, etc.). 3 / 31 Tuples vs. Lists >>> a =(2 ,3 ,4) >>> b =[2 ,3 ,4] >>> type ( a ) < class ’ tuple ’ > >>> type ( b ) < class ’ list ’ > >>> a [1] , b [1] (3 , 3) >>> [ a [ i ]== b [ i ] for i in range (3)] [ True , True , True ] Tuples are much like lists, but syntactically they are enclosed in regular brackets, while lists are enclosed in square brackets. >>> a == b False >>> b [0]=0 # mutating the list >>> a [0]=0 # trying to mutate the tuple Traceback ( most recent call last ): File " < pyshell #30 > " , line 1 , in < module > a [0]=0 TypeError : ’ tuple ’ object does not support item assignment Tuples are much like lists, only they are immutable. 4 / 31 Back to Functions: Return Values A function can return more than a single value. For example >>> def mydivmod (a , b ): ’’’ integer quotient and remainder of a divided by b ’’’ return ( a // b , a % b ) When executing this function, we get back two (integer) values, “packed” in a tuple. >>> mydivmod (21 ,5) (4 , 1) >>> mydivmod (21 ,5)[0] 4 >>> type ( mydivmod (21 ,5)) < class ’ tuple ’ > Incidentally, the returned values can simultaneously assigned: >>> >>> 14 >>> 2 >>> 100 d , r = mydivmod (100 ,7) d r 7*14+2 5 / 31 Python’s Mechanism for Passing Functions’ Parameters Consider the following function, operating on two arguments: def linear combination(x,y): y=2*y return x+y The formal parameters x and y are local, and their “life time” is just during the execution of the function. They disappear when the function is returned. 6 / 31 Back to Functions: Mechanism for Passing Parameters def linear combination(x,y): y=2*y return (x+y) Now let us execute it in the following manner >>> >>> 11 >>> 3 >>> 4 a,b=3,4 # simultaneous assignment linear combination(a,b) # this is the correct value a b # b has NOT changed The assignment y=2*y makes the formal argument y reference another object with a different value inside the body of linear combination(x,y). This change is kept local, inside the body of the function. The change is not visible by the calling environment. 7 / 31 Passing Arguments in Functions’ Call Different programming languages have different mechanisms for passing arguments when a function is called (executed). In Python, the address of the actual parameters is passed to the corresponding formal parameters in the function. An assignment to the formal parameter within the function body creates a new object, and causes the formal parameter to address it. This change is not visible to the original caller’s environment. 8 / 31 Python Functions: Mutable Objects as Formal Variables def modify_list ( lst , i , val ): ’’’ assign val to lst [ i ] does not return any meaningful value ’’’ if len ( lst ) > i : lst [ i ]= val return None >>> >>> >>> [0 , lst =[0 ,1 ,2 ,3 ,4] modify_list ( lst ,3 ,1000) lst 1 , 2 , 1000 , 4] If the function execution mutates one of its parameters, its address in the function does not change. It remains the same address as in the calling environment. So such mutation does affect the original caller’s environment. This phenomena is known as a side effect. Any changes to the calling environment, which are different than those caused through returned functions’ values, are called side effects. 9 / 31 Mutable Objects as Formal Parameters: A 2nd Example Consider the following function, operating on one argument: def increment(lst): for i in range(len(lst)): lst[i] = lst[i] +1 # no value returned Now let us execute it in the following manner >>> >>> >>> [1, list1=[0,1,2,3] increment(list1) list1 2, 3, 4] # list1 has changed! In this case too, the formal argument (and local variable) lst was mutated inside the body of increment(lst). This mutation is visible back in the calling environment. Such change occurs only for mutable objects. 10 / 31 Effect of Mutations vs. Assignment inside Function Body Consider the following function, operating on one argument: def nullify(lst): lst=[ ] # no value returned Now let us execute it in the following manner >>> >>> >>> [0, list1=[0,1,2,3] nullify(list1) list1 1, 2, 3] # list1 has NOT changed! Any change (like an assignment) to the formal argument, lst, that changes the (identity of) the referenced object are not visible in the calling environment, despite the fact that it is a mutable object. 11 / 31 Effect of Mutations vs. Assignment inside Function Body 2 It is possible to detect such changes using id. def nullify(lst): print(hex(id(lst))) lst=[ ] print(hex(id(lst))) # no value returned Now let us execute it in the following manner >>> list1=[0,1,2,3] >>> print(hex(id(lst))) 0x1f608f0 >>> nullify(list1) 0x1f608f0 0x11f4918 # id of local var lst has changed >>> list1 [0, 1, 2, 3] # (external) list1 has NOT changed! >>> print(hex(id(lst))) 0x1f608f0 Any change (like an assignment) to the formal argument, lst, that changes the (identity of) the referenced object are not visible in the calling environment, despite the fact that it is a mutable object. 12 / 31 Functions: Local vs. Global Variables Consider the following functions, operating on one argument: def summation local(n): partial sum = sum(range(1,n+1)) # no value returned Now let us execute it in the following manner >>> partial sum=0 >>> summation local(5) >>> partial sum 0 # partial sum has NOT changed In this example, partial sum is local to the function body, and changes are not visible to the original caller of the function. 13 / 31 Functions: Local vs. Global Variables Consider the following function, operating on one argument: def su m m a t i o n _ g l o b a l ( n ): global partial_sum partial_sum = sum ( range (1 , n +1)) # no value returned In this example, the declaration global partial sum makes this variable global. In particular, changes to it do propagate to the original caller of the function. Typically, global variables are discouraged, unless you have a very good reason to use them. 14 / 31 Functions: Local vs. Global Variables Lets run both versions (“local” and “global”): >>> partial sum Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> partial sum NameError: name ’partial sum’ is not defined >>> summation local(5) >>> partial sum Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> partial sum NameError: name ’partial sum’ is not defined >>> summation global(5) >>> partial sum 15 The declaration global partial sum makes this variable global. In particular, changes to it do propagate to the original caller of the function (including defining it). This may be useful, but may also be weird and confusing. 15 / 31 Functions: Information Flow and Side Effects To conclude, we saw three ways of passing information from a function back to its original caller: 1. Using return value(s). This typically is the safest and easiest to understand mechanism. 2. Mutating a mutable formal parameter. This often is harder to understand and debug, and more error prone, but sometime almost inevitable. Use wisely and document. 3. Via changes to variables that are explicitly declared global. Much harder to understand and debug, and more error prone. Try to avoid. Printing a value is not the same as returning it, and should be used only for communication with the human user 16 / 31 2. Integer representation 17 / 31 Natural Numbers “God created the natural numbers; all the rest is the work of man” (Leopold Kronecker, 1823 –1891). In this course, we will look at some issues related to natural numbers. We will be careful to pay attention to the computational overhead of carrying the various operations. Today: I Integers: Unary vs. binary representation. I Integers in Python. I Representation in different bases (binary, decimal, octal, hexadecimal, 31, etc.). In the (near) future: I Addition, multiplication and division. I Exponentiation and modular exponentiation. I Euclid’s greatest common divisor (gcd) algorithm. I Probabilistic primality testing. I Diffie-Helman secret sharing protocol. I The RSA public key cryptosystem. 18 / 31 Deep Inside the Computer Circuitry Most of the logic and memory hardware inside the computer are electronic devices containing a huge number of transistors (the transistor was invented in 1947, Bell Labs, NJ). At any given point in time, the voltage in each of these tiny devices (1 nanometer = 10−9 meter) is either +5v or 0v. Transistors operate as switches, and are combined to complex and functional circuitry. An extremely useful abstraction is to ignore the underlying electric details, and view the voltage levels as bits (binary digits): 0v is viewed as 0, +5v is viewed as 1. 19 / 31 From Bits to Numbers An extremely useful abstraction is to ignore the underlying electric details, and view the voltage levels as bits (binary digits): 0v is viewed as 0, +5v is viewed as 1. The next conceptual step is arranging these bits so they can represent numbers. Then, we will strive to arrange the numbers so they can represent characters, text, pictures, audio, video, etc. etc. We will begin at the beginning: From bits to numbers. 20 / 31 Unary vs. Binary Representation of Numbers Consider the natural number nineteen. In unary, it is represented as 1111111111111111111. In binary, it is represented as 10011. To translate a binary number to (regular) decimal number, multiply the rightmost bit by 20 = 1, the second rightmost by 21 , etc. and sum up the results. So 10011 is 1 · 20 + 1 · 21 + 0 · 22 + 0 · 23 + 1 · 24 which is 19 in decimal ). The lengths of the two representations are substantially different. The unary representation is exponentially longer than the binary representation. To see this, consider the natural number 2n . In unary it is represented by 2n ones. In binary, it is represented by a single one, followed by n zeroes. 21 / 31 Translation Translating a binary number to decimal is easy and by definition. In fact, the definition in the previous slide almost dictates an algorithm for translation. Can you come up with an algorithm for translating decimal to binary? 22 / 31 Unary, Binary and Other Representations Other representations are obviously also in use. In particular the ternary (base 3), hexadecimal (hex, 0x, base 16) and of course decimal (base 10) are well known. The lengths of representations in different bases differ. However, the lengths in bases b and c are related linearly. For example, a number represented with d digits (in decimal) will take at most dd log2 10e bits (in binary). As alluded to earlier, natural numbers in the computer are represented in binary, for a variety of reasons having to do with the physical world, electric circuits, capacities, currents, etc.. 23 / 31 Representation of natural numbers in an arbitrary base A natural number N can be represented in a base b, as a polynomial of degree k, provided that N is between bk and bk+1 . The polynomial coefficients are natural numbers smaller than b. The coefficients of the polynomial are the k + 1 digits of N in its b-ary representation. N = ak ∗ bk + ak−1 ∗ bk−1 + ..... + a1 ∗ b + a0 where bk ≤ N bk+1 , and for each i , 0 ≤ ai b Nin base b = (ak ak−1 .....a1 a0 ) 24 / 31 Different Bases Representations in Python Python has built in functions for converting a number from decimal (base 10) to binary, octal (base 8), and hexadecimal (base 16). >>> bin(1000) ‘0b1111101000’ >>> oct(1000) ‘0o1750’ >>> hex(1000) ‘0x3e8’ The returned values are strings, whose prefixes 0b,0o,0x indicate the bases 2, 8, 16, respectively. >>> type(bin(1000)) <class ’str’> 25 / 31 Converting to Decimal in Python Python has a built-in function, int, for converting a number from base b representation to decimal representation. The input is a string, which is a representation of a number in base b (for the power of two bases, 0b, 0o, 0x prefixes are optional), and the base, b itself . >>> int("0110",2) 6 >>> int("0b0110",2) 6 >>> int("f",16) 15 >>> int("fff",16) 4095 >>> int("fff",17) 4605 >>> int("ben",24) 6695 >>> int("ben",23) # "a" is 10,...,"m" is 22, so no "n" in base 23 Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> int("ben",23) ValueError: invalid literal for int() with base 23:’ben’ 26 / 31 Natural Numbers and Computer Words Modern computers are arranged by words, groups of fixed number of bits that correspond to size of registers, units of memory, etc. Word size is uniform across a computer, and depends both on the hardware (processors, memory, etc.) and on the operating system. Typical word sizes are 8, 16 (Intel original 8086), 32 (popular), or 64 bits (fairly popular since 2010 as well). In many programming languages, integers are represented by either a single computer word, or by two computer words. In Java, for example, these are termed int and long, correspondingly. Things are quite different in Python, as we will soon see. 27 / 31 Natural Numbers and Integers in Python A 32 bits word can represent any integer, k, in the range −231 ≤ k ≤ 231 − 1. To handle larger numbers, these 32 bits words should be manipulated correspondingly (represent signed sums of successive powers of 232 ). This is either done explicitly by the user/programmer, or provided directly by the programming language. Python takes care of large integers internally, even if they are way over the word size. >>> 3**97-2**121+17 19088056320749371083854654541807988572109959828 28 / 31 Natural Numbers and Integers in Python, cont. Still, when manipulating large integers, one should think of the computational resources involved: 10 I Space: There is no difficulty to represent 22 − 17, or, in Python 2**(2**10)-17 (as the result takes four lines on my 100 Python Shell window, I skip it). But don’t try 22 − 17 (why?)! I Time: How many basic operations (or, clock cycles) are needed? I Time will grow as n, the number of bits in the numbers we operate on, grow. How time grows as a function of n is important since this will make the difference between fast and slow tasks, and even between feasible and infeasible tasks. I We will define these notions precisely in the future, but you should start paying attention today. 29 / 31 Positive and Negative Integers in the Computer (for reference only) On any modern computer hardware, running any operating system, natural numbers are represented in binary. An interesting issue is how integers (esp. negative integers) are represented so that elementary operations like increment/decrement, addition, subtraction, and negation are efficient. The two common ways are 1. One’s complement, where, e.g. -1 is represented by 11111110, and there are two representations for zero: +0 is represented by 00000000, and -0 is represented by 11111111. 2. Two’s complement, where, e.g. -1 is represented by 11111111, -2 by 11111110, and there is only one 0, represented by 00000000. Two’s complement is implemented more often. 30 / 31 Two’s Complement (for reference only) For the sake of completeness, we’ll explain how negative integers are represented in the two’s complement representation. To begin with, non negative integers have 0 as their leading (leftmost) bit, while negative integers have 1 as their leading (leftmost) bit. Suppose we have a k bits, non negative integer, M . To represent −M , we compute 2k − M , and drop the leading (leftmost) bit. For the sake of simplicity, suppose we deal with an 8 bits number: 100000000 00000001 --------11111111 M =1 −1 100000000 00001110 --------11110010 M = 14 −14 A desirable property of two’s complement is that we add two numbers “as usual”, regardless of whether they are positive or negative. 31 / 31