Python Essentials: Part 1 - Module 3

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Bubble Sort

- algorithm that sorts a list by repeatedly comparing adjacent elements & swapping them to achieve our goal (or desired order) - each appropriate value will "bubble" towards its position in the list (float up from the bottom to the surface, just like bubbles in a glass of champagne)

Lists in lists: two-dimensional arrays -empty chessboard ex.

- assume that a predefined symbol named EMPTY designates an empty field on the chessboard Ex. create a list of lists representing the whole chessboard : board = [ ] for i in range(8): row = [EMPTY for i in range(8)] board.append(row) - inner part of the loop : creates a row consisting of eight elements (each of them equal to EMPTY) & appends it to the board list - outer repeats it 8 times - in total, the board list consists of 64 elements (all equal to EMPTY)

expo variable

- can be used as a control variable for a loop, - indicates the current value of the exponent power = 1 for *expo* in range(16) : print("2 to power of", expo, "is", power) power *= 2 - !expo! >>> x ^ !#! power is the answer to the exponentiation and also a variable being replaced to have a continued calculation fo every next variable value being fed in

2nd use of for-loop

- can hide all the actions connected to the list's indexing, and deliver all the list's elements handily the whole thing looks like : my_list = [10, 1, 8, 3, 5] total = 0 for i in my_list: total += i print(total) (^here, instead of using in range(len(my_list)) , we use in my_list; instead of total += my_list[i] , we use total += i) - i variable is assigned the values of all subsequent list elements (acts as a copy of the elements' values) - process occurs as many times as there are elements

*Making Use of Comparison Operator Results

- can store result in a variable to make use of it later - can use the answer you get to make a decision about the future of the program by using a special instruction* > more common & convenient option

Slice

- element of Python syntax that allows you to make a new copy of a list, or parts of a list [:] - copies the list's CONTENTS, not it's name

max()

- function returns the largest number ---- user inputs 3 numbers ----> ex. largest_number = max(number1, number2, number3) print("The largest number is:", largest_number)

not

- unary logical operator - it negates ; think of it as a deceiver! - turns truth into falsehood and falsehood into truth -very high priority - same as the unary

???*signed 2's complement*???

???*used w/ ~negation*???

Boolean

A binary variable, having two possible values called "true" and "false."

Algorithm

Is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output

Pseudocode

Kind of notation which is not an actual programming language (it can be neither compiled nor executed), but it is formalized, concise and readable

!=

Not Equal To Operator (inequality) compares two arguments & answers the question "are these values equal" ? - answers w/ 1 of 2 kinds of predefined literals/keywords - "True" or "False" BUT the answer is the opposite > if they're equal, the result is "False" > if they're unequal, the result is "True"

Unary Operator

One that takes a single operand/argument and performs an operation

Loop

Performing a certain part of the code more than once (passing through it as many times as needed)

sequence of instructions based on bit

if flag_register & the_mask: # My bit is set. else: # My bit is reset.

lists in lists

when a list's elements are just lists - best ex. of such arrays is a chessboard 8 rows (numbered 1-8) 8 columns (marked a-h)

xor operator property

x ^ 1 = ~x x ^ 0 = x

**3.7.1.4 python ess. part 1 - reference ex. for in-depth**

# design a list capable of storing all these results # thermometer records air temp (hourly) throughout the month # total of 24 × 31 = 744 values # which data type would be adequate? float # measures temp w/ accuracy of 0.1 ℃ # make an arbitrary decision... : # rows will record readings every hr (on the hr)- 24 elements # each row will be assigned to one day of the month - 31 rows # h - hour, d - day temps = [[0.0 for h in range(24)] for d in range(31)] # whole matrix is now filled with zeros # can assume it's automatically updated using special hardware agents # wait for the matrix to be filled with measurements

Bitwise Chart

(check desktop for full chart) but here is the simplification : & requires two 1's to provide 1 as result | requires at least one 1 to provide 1 as result ^ requires exactly one 1 to provide 1 as the result

Negative Indices & Assumptions w/ Slices

(remember -1 is the pos. of last element in the list, -2 is second to last, and so on...) - start - index of 1st element included in the slice > if it specifies an element lying further than that of the end pos. (from the pov of beginning of the list), then the slice will be [ ] > if omitted, assumption is that you want a slice beginning from pos. 0 - end - index of 1st element NOT included in the slice > if omitted, assumption is you want a slice ending @ list's last pos. --> len(my_list) NOTE: this is NOT (end-1) the assumption is the actual LAST element of the list

xor

- "exclusive or" operator (Xclusive) - ^ (denoted as caret symbol) - additional operator that does not have a non-bitwise log-op. equivalent

Lists

- "scalar" variables are able to store exactly 1 given value at a time (like "scalar" in mathematics) -we've been using these kinds of var.'s, but here each element in a list are scalar -you can start a list's life by creating it w/ empty [ ] - lists are in the format : ex. numbers = [10, 5, 7, 2, 1] - "numbers" is a list consisting of 5 values, all #s - creates a list of length = to 5 (5 elements inside of it) - elements can be of many different types & are always numbered starting from 0

in / not-in operators

- (in) checks if a given element is currently stored somewhere inside the list - & returns True in this case (False is returned if not) ex. print(5 in my_list) - (not in) checks if a given element is absent in a list - & returns True in this case (False is returned if not) ex. print(5 not in my_list)

Functions VS. Methods (details)

- a method is a KIND of function (BUT differs in the way in which it acts, & its invocation style) -owned by data it works for - a function doesn't belong to any data - gets data & may create new data - (generally) produces a result - is owned by the whole code

Method

- a specific KIND of function - gets data & may create new data - (generally) produces a result - able to change the state of a selected entity - owned by the data it works for & requires some specification of the relevant data to invoke it - adding new elements to an existing list can be done w/ methods owned by all the lists, not functions

continue

- a syntactic sugah and a keyword - behaves as if the program has suddenly reached the end of the body; the next turn is started and the condition expression is tested immediately -used when you need to start the next turn of the loop w/out completing the execution of the current turn -Aborts current loop turn but still INSIDE & continuing the entire loop ex. print("\nThe continue instruction:") for i in range(1, 6): if i == 3: continue print("Inside the loop.", i) print("Outside the loop.")

break

- a syntactic sugah and a keyword - exits the loop immediately, and unconditionally ends the loop's operation; the program begins to execute the nearest instruction after the loop's body (not indented) -used when it's unnecessary to continue the loop and you want to stop it's execution, going further -Immediately aborts entire loop ex. print("The break instruction:") for i in range(1, 6): if i == 3: break print("Inside the loop.", i) print("Outside the loop.")

Negative indices

- an element with an index equal to -1 is the last one in the list, likewise -2 would be the one before the last - trying to get elements out of the range of the list will result in error (like before)

pass keyword

- an empty instruction - does nothing but avoids receiving an error - used as placeholder for future code ^in current context, we use it inside the loop body because it's syntax demands at least 1 instruction (just like if, elif, else, while)

range() function (w/ 2 arguments)

- can take 1 or .... 2 argument(s) : > the First argument determines the initial (first) value of the control var. > the Last argument shows the first value that the control var. will NOT be assigned ex. for i in range(2, 8): print("The value of i is currently", i) -outputs the string w/ the current value of i (so begins with 2) until it's value is *7* (altho 2nd argument is 8)

len ( ) function

- checks list's current length - takes list's name as arg. & returns the # of elements currently stored inside it

Build a bit mask to check status of bit

- detects the state of your bit and points to it ex. should point to 3rd bit > 0000000000000000000000000000*1*000 ----> that bit has the weight of 2^3 = 8 - suitable mask could be created by the following declaration: the_mask = 8

Shifting operation

- for single bits - applied only to integer values (CANNOT use floats as arguments for it) - same concept as : 12345 × 10 = 123450 x 10 => shift of all the digits to the left and filling the resulting gap with 0 12340 ÷ 10 = 1234 ÷ 10 => shift of all the digits to the right & nothing more --> EXCEPT the computer does this operation using 2 as the base for binary #'s - shifting a value 1 bit to the left << corresponds to x2 - shifting 1 bit to the right >> corresponds to /2 (rightmost bit is lost) - operator is digraphs << >> value << bits / value >> bits

rearrange / swap the elements

- for swapping variable, changing the order of the assignments will not help - need a 3rd variable that serves as auxiliary storage: variable_1 = 1 variable_2 = 2 auxiliary = variable_1 variable_1 = variable_2 variable_2 = auxiliary - but this is the way python provides which is more convenient and smooth : variable_1 = 1 variable_2 = 2 variable_1, variable_2 = variable_2, variable_1 (this is fine for a few elements, but still tedious for a large # of elements..)

min()

- function returns the lowest number ---- user inputs 3 numbers ----> ex. smallest_number = min(number1, number2, number3) print("The smallest number is:", smallest_number)

Nested if-else statement

- instruction placed after the if is another if NOTE : every else refers to the if which lies at the same indentation level - determines how they pair up Ex. ---> if the_weather_is_good: if nice_restaurant_is_found: have_lunch() else: eat_a_sandwich() else: if tickets_are_available: go_to_the_theater() else: go_shopping()

ELSE keyword used w/ a WHILE loop

- interesting but barely used - always executed once, regardless of whether the loop has entered its body or not (even if the loop hasn't run, the else branch will still be executed)

Logical Values vs. Single Bits

- logical oper.'s take their arguments as a whole regardless of how many bits they contain -result of operations is False or True - they are only aware of the value: zero (when all the bits are reset) means False not zero (when at least one bit is set) means True - logical op.'s do not penetrate into the bit level of its argument - only interested in final integer value

for-loop element swapping

- makes swapping smooth regardless of list length ex. my_list = [10, 1, 8, 3, 5] length = len(my_list) for i in range(length // 2) : my_list[i] , my_list[length - i - 1] = my_list[length - i - 1] , my_list[i] print(my_list) - length var. assigned the list's length for clarity - for loop runs through its body - length // 2 times > if list length is odd, middle is still untouched -swaps ith element >(from the begin. of the list) with the one with an index equal to (length - i - 1) >(from the end of the list) here, for i = 0 (length - i - 1) gives 4; for i equal to 1, it gives 3 - this is exactly what we need for swapping the 1st and last(5th) elements, 2nd and 4th elements, etc.

elif

- shorter form of else if - used to check more than just one condition, and to stop when the first statement which is true is found - seems to be somewhat synonymous with saying "otherwise" Ex. if the_weather_is_good: go_for_a_walk() elif tickets_are_available: go_to_the_theater() elif table_is_available: go_for_lunch() else: play_chess_at_home() ^the way to assemble if-elif-else statements is sometimes called a *cascade*

list comprehension

- special syntax used by Python in order to fill massive lists - it's actually a list, but created on-the-fly during program execution - allows you to concisely & elegantly create new lists from existing ones - it's not described statically [expression *for* element *in* list *if* conditional] - actually an equivalent of : for element in list : if conditional : expression elements in a row ----> (left to right) rows in a matrix | | (top to bottom) V each matrix in an n-dimensional list (ex. 3-D) (front matrix to back matrix)

sort method

- the convenient way to sort - method in code : list.sort() ex. my_list = [8, 10, 6, 2, 4] *my_list.sort()* print(my_list) - output : [2, 4, 6, 8, 10] - ALSO can use reverse( ) - this reverses/flips the list ex. norm = [5, 3, 1, 2, 4] *norm.reverse()* print(norm) - output : [4, 2, 1, 3, 5]

Difference btwn. Var. & List Storage

- the name of an ordinary (scalar) variable is the name of its content - the name of a list is the name of a memory location where the list is stored

del (delete)

- this instruction (which is not a function) removes elements from a list - point to the element to be removed (will make it vanish and reduce the length by 1) ex. [111, 1, 7, 2, 1] del numbers[1] print(len(numbers)) *: 4* print(numbers) *: [111, 7, 2, 1]* NOTE : - you can't access (assign/get a value) of an element which doesn't exist - this will cause an error (particularly an index error)

Index / Indexing

- value inside brackets which selects 1 element of the list; the "position" -indices (multiple index-es) (any expression can be the index as well) - the operation of selecting an element from the list

if-else statement

- we already know what we'll do if the conditions are met, this also tells us what we could do INSTEAD - keyword : "else" (mustn't use "else" without a preceding "if") - same formatting as for if-block In other words, we have a "Plan B" Ex. Format if true_or_false_condition: perform_if_condition_true() else: perform_if_IF_condition_false() perform_invariably() ^this else statement is executed if the IF condition evaluates False - if the IF was True, the if instruction would be executed and statement would end - perform_invariably : no matter what

ex. creating row 2 on the chessboard : all the white pawns w/out list comp.

- we can assume every row on the chessboard is a list row = [ ] --> 2nd board row for i in range(8): --> the current i iterated through all 8 pos.'s- column intersects row.append(WHITE_PAWN)

Set your bit

- you assign a 1 to your bit, while all the remaining bits must remain unchanged - use disjunction property - to set your bit : flag_register |= the_mask

to reset your bit

- you assign a zero to the bit while all the other bits must remain unchanged - use conjunction property as before, but let's use a slightly different mask : 11111111111111111111111111110111 (mask created by negation of all the bits of mask var.) to reset the bit : flag_register &= ~the_mask

Bitwise Operators

-used to compare binary numbers four operators that allow you to manipulate single bits of data -arguments ARE integers, NOT floats -deal with every bit separately but simultaneously & (ampersand) - bitwise conjunction | (bar) - bitwise disjunction ~ (tilde) - bitwise negation ^ (caret) - bitwise exclusive or (xor) other than negation, all of these can be used like this ex. : x = x & y >>> x &= y

3 ways of doing the same thing - which action consumes more resources?

1) assume 1st is largest -- my_list = [17, 3, 11, 5, 1, 9, 7, 15] largest = my_list[0] for i in range(1, len(my_list)): if my_list[i] > largest: largest = my_list[i] print(largest) 2) assumes 1st is largest & compares to itself -- my_list = [17, 3, 11, 5, 1, 9, 7, 15] largest = my_list[0] for i in my_list: if i > largest: largest = i print(largest) 3) assumes 1st is largest & utilizes a slice -- my_list = [17, 3, 11, 5, 1, 9, 7, 15] largest = my_list[0] for i in my_list [1:] : if i > largest: largest = i print(largest)

range() function (w/ 3 arguments)

3rd argument is an increment (step) - a value added to control the variable at every loop turn - it is the difference between each number in the sequence of numbers generated by the function (the default value of the increment is 1) > the First argument determines the initial (first) value of the control var. > the Last argument shows the first value that the control var. will NOT be assigned ex. for i in range(2, 8, 3): print("The value of i is currently", i) OUTPUT: The value of i is currently 2 The value of i is currently 5

Two-dimensional array

>> model perfectly mimics the real chessboard, which is in fact an 8-element list of elements, all single row'ed - elements of the rows are fields (8 of them per row) (kinda like excel cells) - elements of the whole chessboard are rows, 8 of them per chessboard - the board variable is now a 2-dimensional array or in algebraic terms - a matrix

counter

A variable used to count something, usually initialized to zero and incremented in the body of a loop

Infinite Loop

A.k.a an endless loop, is a sequence of instructions in a program which repeat indefinitely (loop endlessly) ex. (will infinitely print the "string") while True: print("I'm stuck inside a loop.")

Binary Operator

An operator that operates on two operands and manipulates them to return a result

KeyboardInterrupt

Ctrl-C > will terminate the program (or Ctrl-Break on some computers)

reading bits and locating your bit in ex.

Each bit of the variable stores one yes/no value. You've also been told that only one of these bits is yours - the third (remember that bits are numbered from zero, and bit number zero is the lowest one, while the highest is number 31). The remaining bits are not allowed to change, because they're intended to store other data. Here's your bit marked with the letter x: flag_register = 0000000000000000000000000000x000

==

Equal To Operator (Equality) compares two arguments & answers the question "are these values equal" ? - returns if operands' values are equal- "True" & if not- "False" - binary operator w/ left-side binding - as opposed to = (an assignment operator) which assigns value tricky ex. "2 == 2." --> "True" > Python is able to convert the integer value into its real equivalent (w/ point) ex. low priority operator compared to the others black_sheep == 2 * white_sheep --> treated equivalently to -----------> black_sheep == (2 * white_sheep)

Rules for Writing Conditional Statements

Ex. Format : if true_or_not: do_this_if_true ^ keyword followed by 1 or more white spaces ^*expression (a question or an answer) whose value is interpreted in terms of "True" (not = 0) or "False" (= 0) ^colon followed by newline, followed by 1 indented* instruction (minimum requirement) or set of instructions (*indent= 4 spaces or tab) - strictly consists of these necessary element in this specific order - Python 3 does not allow mixing spaces and tabs for indentation - it's important to make all indentations exactly the same in all lines (not just looks-wise) in the case of more than 1 instruction - *expression : if the value represents... > the truth : instruction(s) executed > not the truth : instruction(s) omitted and the next executed instruction will be the one after the original indentation level

>

Greater Than Operator compares two arguments & answers the question "is one value greater than the other" (? is strict) ? - "True" --> left value greater than right & "False" is not -binary operators with left-sided binding -higher priority than == and != ex. black_sheep > white_sheep "True" confirms that there's more black sheep than white, "False" denies it

>=

Greater Than or Equal To Operator - special, non-strict variant of > oper. - "True" --> left value greater than or equal to right & "False" is not -binary operators with left-sided binding -higher priority than == and != ex. want to find out whether or not we have to wear a warm hat : degrees_temp_outside ≥ 0.0

if statement

If a python developer falls asleep when he or she counts 120 sheep (or more) The sleep-inducing procedure may be implemented as a special function named sleep_and_dream() ex. 1 instruction if sheep_counter >= 120 : sleep_and_dream() > can read it as: if sheep_counter is greater than or equal to 120, then fall asleep and dream (execute the sleep_and_dream function) ex. >1 instructions & if-block excluded if sheep_counter >= 120 : make_bed() take_shower() sleep_and_dream() feed_the_dog() > can read it as: if sheep_counter is greater than or equal to 120, then make bed, take shower, and sleep & dream (all executed conditionally) > feeding the dog is always executed

Nested Loops

Is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop"

<

Less Than Operator compares two arguments & answers the question "is one value less than the other" ? - "True" --> left value less than right & "False" is not -binary operators with left-sided binding -higher priority than == and != ex. check if there's a risk of being fined by the highway police (? is strict) : current_velocity_mph < 85

<=

Less Than or Equal To Operator - special, non-strict variant of < oper. - "True" --> left value less than or equal to right & "False" is not -binary operators with left-sided binding -higher priority than == and != ex. check if there's a risk of being fined by the highway police (? isn't strict) : current_velocity_mph ≤ 85

DeMorgan's Laws with it's == code

The negation of a conjunction is the disjunction of the negations. not (p and q) == (not p) or (not q) The negation of a disjunction is the conjunction of the negations. not (p or q) == (not p) and (not q)

Multidimensional nature of lists: advanced applications

To find any element of a two-dimensional list, you have to use 2 coordinates: - one vertical (row #) - one horizontal (column #)

Comparison Operator

Used to compare values

While Loop

WHILE repeats the execution of a set of statements as long as the condition is true (as opposed to IF which performs the its statements only once) Format Ex. while conditional_expression: instruction_one instruction_two instruction_three .....instruction_n - each instruction statement inside one WHILE must be indented - Analogy - : while there's something to do : do it when there's nothing to do : nothing happens (if condition's false, nothing executed)

and

a conjunction in logical language -binary logical operator - outcome (going for a walk) depends on simultaneous fulfilment of these two conditions - lower priority than comparison op.'s - (cannot be used in abbrev. form op=) ex in language : if we have some free time, and the weather is good, we will go for a walk. ex in code: counter > 0 and value == 100

or

a disjunction in logical language -binary logical operator - outcome (gift purchase) depends on fulfilment of at least one of these conditions - lower priority than "and" - (cannot be used in abbrev. form op=) ex in language : If you are in the mall or I am in the mall, one of us will buy a gift for Mom.

Conditional Instruction (or Conditional Statement)

a mechanism which will allows you to do something if a condition is met, and not do it if it isn't tips: - knowing what conditions influence our behavior - determining what is/isn't a conditional activity - determining what is/isn't dependent NOTE: Each IF is tested separately. The body of ELSE is executed only if the last IF is False (even if other IF's in btwn were false and the last IF is True, ELSE won't be executed- else only if all conditions are false) ***refer: python essentials part 1: module 3.1.1.13/14 section summary***

bit mask

a sequence of zeros and ones, whose task is to grab the value or to change the selected bits check your sequence and your bit's position/value and get possibilities of obtained bit strings depending on the comparison and what value the bit is set to

Loop's Body

an instruction or set of instructions executed inside the while loop - should be able to change the condition's value, because if the condition is True at the beginning, the body might run continuously to infinity - notice that doing a thing usually decreases the number of things to do)

control variable

any variable after the "for" keyword in a For Loop : auto-counts loop's turns

ex. of simplifying expressions to equivalent forms

because : True = 1 & False = 0 while number != 0: == while number: if number % 2 == 1: == if number % 2: > not using as == code, just shorthand don't feel obliged to code it this way (as short/compact as poss.) ...... readability may be more important

Nested List Comprehension

board = [[EMPTY for i in range(8)] for j in range(8)] -inner part creates a ROW -outer builds LIST OF ROWS

Insert ( ) method

can add a new element at any place in the list, not only at the end - takes 2 arguments: 1st- shows the required location of the element to be inserted; all existing elements to the right of the new element (including the one at the indicated position) are shifted to the right, making space for the new element 2nd- element to be inserted "paste in, this value" ex. list.insert(location, value) - makes former 1st element the 2nd, 2nd to 3rd.. & so on

multi-line printing

can use triple quotes to print strings on multiple lines in order to make text easier to read, or create a special text-based design --> print(""" also works ex. print( """ this is my random multi line code, imagine that i span over more lines! """)

For Loop

counts the "turns" of the loop rather than checking the conditions -checked internally, without any intervention (no need for conditions) -can "browse" large collections of data item by item executes a set of statements many times; it's used to iterate over a sequence

how many numbers have you hit in the lottery? ex. program

drawn = [5, 11, 9, 42, 3, 49] bets = [3, 7, 11, 42, 34, 49] hits = 0 for number in bets: if number in drawn: hits += 1 print(hits) outputs -----> 4

list comprehension examples

ex 1. square = [x ** 2 for x in range(9)] outputs -----> (0, 1, 4, 9, 16, 25, 36, 49, 64) ex 2. twos = [2 ** i for i in range(8)] outputs -----> (1, 2, 4, 8, 16, 32, 64, 128) ex 3. odds = [x for x in square if x%2 != 0] outputs -----> only the odd elements of the squares list: [1, 9, 25, 49, 81]

ex. copying entire list w/ slice

ex. list_1 = [1] list_2 = list_1[:] list_1[0] = 2 print(list_2) outputs --> [1] (the copied contents of list 1 assigned to list 2 does not get "updated" as value 2 in the 1st pos., JUST copies those CONtents)

ex. copying part of the list w/ slice

ex. my_list = [10, 8, 6, 4, 2] new_list = my_list[1:3] outputs --> [8, 6] (pos. 1 =8; pos. 3 - not included, 2 is, 3-1 =2, is 6) - makes a new (target) list, taking elements from the source list - the elements of the indices from [starting pos. : end pos.- 1]

copy the value of 1 element to another

ex. numbers = [10, 5, 7, 2, 1] numbers[1] = numbers[4] --> the value of the 2nd pos. of the new list will now be the same as that of the fifth pos. --> (value of fifth element is copied to 2nd) - each element overall can be accessed in this way [ ]

for-loop variant for processing lists

ex. calculate the sum of all the values stored in my_list - need a var. whose sum will be stored and initially assigned a value of 0 (total) - add all elements of the list to total using the for-loop for i in range(len(my_list)): --> this means the i var. is taking values 0, 1, 2, 3, & 4, and indexing it, selecting the elements in our ex. : my_list = [10, 1, 8, 3, 5] --> doing it this way by utilizing len() makes the code independent of any possible changes in the list's content --> it adds each of these to the total var. like this: total += my_list[i], and gives the final result after looping the whole thing looks like : my_list = [10, 1, 8, 3, 5] total = 0 for i in range(len(my_list)): total += my_list[i] print(total)

Three-dimensional arrays

ex. akin to a huge hotel w/.. - 3 buildings - 15 floors each - 20 rooms on each floor >> need an array which can collect/process information on occupied/free rooms steps: - type of array's elements : Boolean Value (True / False) - summarized analysis of the situation ^ selecting with indexing... 1st index - [0-2] : building # 2nd index - [0-14] : floor # 3rd index - [0-19] : room # (all rooms are initially free) ex. book a room for some newlyweds: in 2nd building, on the 10th floor, room # 14 rooms[1][9][13] = True ex. check for vacancies >> on 15th floor, 3rd building : vacancy = 0 for room_number in range(20): if not rooms[2][14][room] : vacancy += 1 - if all rooms are occupied, vacancy remain @0, if not, the it represents the # of available rooms

name vs. content

ex. name deletion list_1 = ["A", "B", "C"] list_2 = list_1 list_3 = list_2 del list_1[0] del list_2 print(list_3) --> deletes name, but not content --> ['B', 'C'] list_1 = ["A", "B", "C"] list_2 = list_1 list_3 = list_2 del list_1[0] del list_2[:] print(list_3) --> deletes content, not name --> [ ]

ELSE keyword used w/ a FOR loop

ex1.i = 1 for i in range(5): print(i) else: print("else:", i) - The i variable retains its last value ex2. i = 111 for i in range(2, 1): print(i) else: print("else:", i) - i variable assigned before loop w/out loop's execution, control var. retains value it had before loop - if the control variable doesn't exist before the loop starts, it won't exist when the execution reaches the else branch

What is the output of the following code - quiz?

list = [ 3 , 1 , -1 ] list [ -1 ] = list [ -2 ] print ( list ) - the value for that [pos.] in the list is assigned to (right of = assigned to left of =) the value for the other [pos.]

ex. of variable vs. list storage

list_1 = [1] list_2 = list_1 # assigns list_1 to new list_2 #copies the name of the array- NOT its contents list_1[0] = 2 # if value of the 1st pos. in the list is now 2.... print(list_2) # it's now the same for list 2 - in effect, the two names (list_1 and list_2) identify the same location in the computer memory - modifying 1 affects the other, and vice versa

add elements to list (for-loop + append)

my_list = [ ] for i in range(5): my_list.append(i + 1) print(my_list) [1, 2, 3, 4, 5]

add elements to list (for-loop + insert)

my_list = [ ] for i in range(5): my_list.insert(0, i + 1) print(my_list) [5, 4, 3, 2, 1] -output is same sequence, but in reverse order

simple program that finds the location of a given element inside a list

my_list = [1, 2, 3, 4, 5, 6, 7, 8] to_find = 5 found = False for i in range(len(my_list)): found = my_list[i] == to_find if found: break if found: print("Element found at index", i) else: print("absent") - the target value is stored in the to_find variable - current status of the search is stored in the found variable (True/False) - when found becomes True, for loop is exited

program which removes all the number repetitions from the list

my_list = [1, 2, 4, 4, 1, 4, 2, 6] for i in my_list: if my_list[i] in my_list: del my_list[i] print("The list with unique elements only:\n",my_list)

del w/ slices

my_list = [10, 8, 6, 4, 2] del my_list[1:3] print(my_list) outputs --> [10, 4, 2] - deletes that slice (part) of the list that is specified del my_list[:] - deletes all elements; list is empty [ ] del my_list - deletes list ITSELF, not just the content > error will occur w/ print()

One sorting pass thru the list ex.

my_list = [8, 10, 6, 2, 4] # list to sort for i in range(len(my_list)- 1): # need (5 - 1) comparisons (end up w/ 4 comparisons) if my_list[i] > my_list[i + 1]: # compare adj. elements my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i] # If i is greater than the element to the right of it, we swap them print(my_list)

Sorts the list w/ as many passes as needed til goal is met ex.

my_list = [8, 10, 6, 2, 4] # list to sort swapped = True # a lil fake, we need it to enter the while loop while swapped: swapped = False # no swaps so far for i in range(len(my_list)-1): if my_list[i] > my_list[i + 1]: swapped = True # a swap occurred! my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i] print(my_list) to get the user to input their own list of #'s w/ their own range, add this before all of that^ and leave the list [ ] : my_list = [] swapped = True num = int(input("How many elements do you want to sort: ")) for i in range(num): val = float(input("Enter a list element: ")) my_list.append(val)

Negate your bit

negate the bit with the xor operator property and use : flag_register ^= the_mask

append ( ) method

new element may be glued to the end of existing list - takes its argument's value and puts it at the end of the list which owns the method - list's length increases +1 "tack this on the end" ex. list.append(value)

assign new value to an element

numbers = [10, 5, 7, 2, 1] # original list content^ - determine the original position of where you want the substitute to go, then assign your sub. value to that "[position]" : numbers[0] = 111 numbers = [111, 5, 7, 2, 1] # current list content^

Logical vs Bit Operations in practice w/ and

refer to 3.3.1.3 in PythonEssentialsPart1 ex. i = 15 j = 22 LOGICAL "and" Operation: log = i and j log = True BITWISE Operation : bit = i & j > checks each of the corresponding values for the variables' bits and compares each of THOSE 0' and 1's one by one according to the bitwise operation. Then, you can see from referencing the chart what sequence of bits will end up from doing that op. That resulting sequence corresponds to a value of it's own- in this case, its 6

Logical vs Bit Operations in practice w/ negation

refer to 3.3.1.3 in PythonEssentialsPart1 ex. i = 15 j = 22 LOGICAL "neg" Operation: logneg = not i (i is > not 0, so this is > not not 0, not not 0 means 0 > so yields False logneg = False BITWISE Operation : bitneg = ~i the sequence of bits for i are all switched i.e. (NOT i, JUST A SHORTER EX.) 00011001010 becomes >>> 11100110101

selecting a field of the board

requires two indices : - the first selects the row - the second selects the field number inside the row (or the column number) (essentially gaining access to a "cell", but it's the code for it in the board's context) ex. board[2][3]

re- white pawn 2nd row ex. w/ list comp.

row = [WHITE_PAWN for i in range(8)] the code inside the brackets specifies.... - the data to be used to fill the list (WHITE_PAWN) - the clause specifying how many times the data occurs inside the list / iterations (for i in range(8))

setting the pieces

setting the pieces involves stating the board var. , & setting the specific destination on the board, then adding what you want: board[0][0] = ROOK board[0][7] = ROOK board[1] [4] = PAWN

syntactic candy (syntactic sugar)

syntactic SUGAHs are additional and don't improve a language's expressive power- only simplify developer's work

truth table

the results for logic op.'s are determined on the basis of this - gives the set of possible values of arguments and corresponding values (A's and B's represent arguments) ex. A and B A B A and B True and False \ False and True } > all are False False and False / True and True > > True ex. A or B A B A or B True or False \ False or True } > all are True True or True / False or False > > False ex. not A not A False True True False

range() function (basics and w/ 1 argument)

this function is generates all the desired values of *the auto-counter of the loop's turns (*control variable) - only integers as its arguments - generates sequences of integers ex. for i in range(100): # do_something() pass here^, the range function will create - or feed the loop with- subsequent values from the following set: 0, 1, 2.....98, 99; NOTE : in this case, the range() function finishes the job *one step (one integer number)* before the value of its argument (100), because it start its job from 0 - thus the control variable's value is currently 99 here NOTE: if the set generated by the range() function is empty, the loop won't execute its body at all ex. for i in range (1, 1) :

in keyword

this keyword introduces a syntax element describing the range of possible values being assigned to *the auto-counter of the loop's turns (*control variable)

Functions VS. Methods (visually)

typical function invocation : result = function(arg) - takes an argument, does something returns a result typical method invocation : result = data.method(arg) - name of the method is preceded by the name of the data which owns the method & then the .methodname(argument) --> will behave like a function, but can change the internal state of the data from which it's invoked

Shifting operator example

var = 17 var_right = var >> 1 var_left = var << 2 output : 17 8 68 17 >> 1 → 17 // 2 (17 floor-div. by 2^1→ 8) (shift to right by 1 bit is same as integer division by 2) *floor division rounds down 17 << 2 → 17 * 4 (17 x2^2) → 68 (shift to left by 2 bits is same as integer multiplication by 4)

Rules of cascade

way to assemble if-elif-else statements -----> -"else" is always the last branch of a cascade, regardless of the use of "elif" - else is an optional part of the cascade, and may be omitted - if there is no else branch, it's possible that none of the available branches is executed. - if there is an else branch in the cascade, only one of all the branches is executed opt. - if any if-elif-else branches has just one instruction, the instruction may continue to be written w/out indentation on the same line after ":"

bitwise conjunction property

x & 1 = x x & 0 = 0

bitwise disjunction property

x | 1 = x x | 0 = 0


संबंधित स्टडी सेट्स

sublimation, vaporization , condensation, deposition, melting, freezing

View Set

Addison Johnson_Boards Questions

View Set

Are the effects of privation reversible?

View Set

Iggy Chapter 56: Care of Patients with Noninflammatory Intestinal Disorders

View Set

INFS2608 Lecture 1 - Introduction

View Set

Midterm Exam Exp. 1-9 Monday night

View Set

Health Care System/Organizations

View Set

Ch. 3: Financial Instruments, Financial Markets, and Financial Institutions - Money and Banking

View Set