Partial preview of the text
Download Intro to Computer Science Python latest update with complete verified solutions 2025.pdf and more Exams Biology in PDF only on Docsity!
Intro to Computer Science: Python latest update with complete verified solutions 2025 Computer Science The study of computation and : computational devices What are the two major components of computation algorithms and abstraction algorithm A set of instructions demonstrating : how to explicitly perform a task Are algorithms always the same? Most of the steps are standardized, { and are thus the same for solving any : one of a given class of problems Certain details may be changed to ! provide problem-specific solutions algorithm? Finite number of steps What are the four components of any Eventually ends well-defined, explicit instructions { solves a general class of problems What are the four ways in which we measure algorithms? Correctness Robustness Efficiency Clarity Correctness The ability of an algorithm to produce the right output for all inputs Robustness The ability of an algorithm to handle unexpected inputs Efficiency The ability of an algorithm to not take too long when performing a task Clarity The ability of an algorithm to be easily understandable and alterable Abstraction a simplified representation of something more complex. Abstractions allow you to hide details to help you manage complexity, focus on relevant concepts, and reason about problems at a higher level. heavy abstraction removing all fine details, leaving only major components intact. What does a programming language do? converts instructions that are provided by the user into machine code output (implements an algorithm) Python a high level, very readable, high abstraction coding language x=4+4 print () Print statement Variable Constant Operator How does assignment work in Python (three step process) 1. Interprets the variable on the left side of the = 2. Evaluates the statement on the ' right side of the = 3. Assigns the value to the stored variable in memory Order of operations (Python) () parentheses. ** exponentiation * multiplication, / division, % remainder ! + addition, - subtraction How can we swap variable values in Python (two methods) 1. temp = x x=y y=xX 2. Simultaneous assignment X,Y=y,X Relational Operators in Python Compare two values and return a ‘ Boolean ==,!l= >=, <=,>,< mor ie Logical Operators in Python Check for a condition and return a Boolean And, Not, Or Explain how and, not, and or work and - if all conditions are true, output is true or - if at least one condition is true, output is true not - if condition is false, output is false Describe the precedence for the logical operators in Python : Not first, then and, then or Data Type (Python) An implicitly understood class of data that is given to all variables, literals, and constants in Python What are the five main data types List, string, Boolean, character and : integer How can we check the data type in Python? type () How does "+" work differently for numbers and strings in Python With strings, it will concatenate whatever is within the "" : With numbers, it will output a sum float vs. integer. Which one has precedence (i.e., if you entered 7 + 7.0, would the response be a float or an integer)? floats are decimal values, integers are : integers floats take precedence (14.0) How do we convert values into different types float (integer ) = integer.O int (float ) = float rounded down Booleans a data type that contains the values | True and False what are the two values in the Boolean data class? True, False (capitalized) how do relational operators work with individual letters? letters are compared to one another based on their order, from a-z-A-Z no real values assigned to each letter, just ambiguous assignment that how do relational operators work with strings? : The first letters are compared. If they match, the second letters are ! compared, and so on. what is False in Python : any empty data structure (0, 0.0, : empty string, None objects (data | type), etc. : compares their ordered position ! everything else is True When does Python stop evaluating? (give two examples for and and or statements) Python stops evaluating when it knows the value of a Boolean. For ' example, if we have: ! 1 > 2 and 4>2, Python will stop evaluating after the first statement, because it already knows that the i entire statement is False 2, Python will stop evaluating after : the first statement, because it already ‘ knows that the entire statement is alternatively, if we have 2 > 1 or 4 > True What statements should we avoid when attempting to keep our Booleans simple? == True == False double negatives if statement A line that determines whether or not you run a certain chunk of code if-else statement allows your program to perform one action if the Boolean expression evaluates to true and a different action if the Boolean expression evaluates to false. ' identical to if statements, but adds an alternative set of instructions for False Boolean instances, whereas if statements just stop/skip in this instance if-elif-else statement ' similar to if-else, but allows for different conditions ! can end in else, but doesn't need to if-elif-else syntax if elif else can have as many elifs as you want for loop Loops that have a predetermined beginning, end, and increment (step interval). parameter specifications for for loops 1 parameter = end (start set to 0, increment to 1) Try-Except Statement Python executes all of the statements underneath try. If there is no error, then Python does nothing and skips over all the statements underneath except. However, if Python crashes while inside the try portion, it recovers and jumps over to except, where it executes all the statements underneath there. what can you do to an except statement to make it more versatile you can type except to prompt specific sets of commands for specific error types when do we use functions in python? when we want to perform the same operation repeatedly throughout a program. how can functions make debugging easier? you only have to fix one instance of the buggy code, rather than every individual instance of the body within the program how do we define a function? how do we call a function? (syntax) def (): () function reusable code that takes arguments as input, performs a computation, and returns a result global keyword allows you to use a non-parameter function within a body of statements is variable definition/reassignments within functions local or global (i.e, if local, any defined variables and any variable value changes will not be you define or reassign a variable value within a function, will the changes/definition be present outside of the function). present outside of the function parameter a piece of information that a function : needs to work properly (one that is ; not the same in every use of the : function) how many parameters can a function have? ' can have none, can have : (theoretically) an infinite amount what does a return statement do? the value after the return command will be evaluated and associated with the specific function call, which can then be used outside of the function. After this assignment, the function ends. eg. funcname (x): return 2x print(funcname(7)) -> 14 print vs. return return will store the returned value in the specific function call in question, whereas print will simply display any values on the screen (following the function, these values are destroyed and cannot be referenced again). what is the associated value of any function call that does not have a return statement? ' None how do we call a function within a module how do we import a specific function from a module does this make a difference? from import when a function is imported in this way, we don't have to use dot notation when we call the function overloaded operator An operator that can operate on two or more types of operands (+ and * serve different functions when working with strings, integers, floats, etc). what are the two ways we can iterate through strings? How are these two ways different from one another? for in: for in range (len(): in the first case, the iterating variable : is a character in the string; in the second case, the iterating variable is a number corresponding to an index position. slicing a string the process of finding a subset of characters from a string. [xy] (range of char including x index, but not y) [x] (range from x index to end of string) [:y] (range from beginning of string to 1 before y) [x] (x index of string) [:] (whole string) can we use negative index positions when slicing a string? yes, it just counts down from the last character to the first : the last character has an index of -1 how can we check if a string is contained within another string? what is the order of characters that python uses for relational operators capitals have lower value than lower : case levels | lower alphabet letters have lower ' value than higher alphabet letter z has higher value than any other : letter, A has the lowest method a function that is specific to one type : of object how do we call functions? '() strings are immutable. How can we alter a string given this reality? ! none of its methods can change the : content of a String object : we can only alter strings through : reassignment what function can we use to find out all of the methods associated with a data type? dir(datatype) what does .find() do? returns the beginning index of the : first occurrence of the argument : within a given string what does .replace(x,y) do? replaces all x with y in a string .insert(xy) inserts (doesn't replace) y (element) : at index position x -Pop() vs. .pop(x) removes the final value of a list and returns it vs. the value at the x index position remove () removes the first occurrence of a given element from a list sort (); how can we reverse sort? sorts elements in a list from largest to smallest if we want to reverse sort, we put reverse=True in the parentheses how does the calling process work differently for methods and functions functions are called with the name : and arguments methods are called with dot notation |sort() vs. print(!) aliasing occurs when two variables reference the same list changes in one mean changes to the : base reference, changing both variable values i A=[1,2,3] B=A B[1]=20000 print(A) -> [1,20000,3] list computation (+ and *) + appends a value to the end of a list, * repeats the contents of the list a number of times how can we avoid aliasing when it comes to list references? two methods B = A[:] (take a slice of list 1 that is actually the entirety of the list and assign it to list 2) foriin A: B = B.append(i) what does the range function do? how many parameters can it take, and what do these represent? it creates a range of numerical values which can be turned into a list with range() 1 parameter will generate a list of values between 0 and x-1 2 parameters will generate a list of values between x and y-1 3 parameters will generate a list of values between x and y with increment z, stopping when the values are about to hit/pass y. how do we reference a nested list value (list [x))[y] where list 1 is the outer list, x is the : index position of the inner list, and y : is the desired reference value within ! the inner list. what are the 3 major differences between lists and tuples? lists are mutable, tuples are not lists are [], tuples are () lists have access to a number of methods, tuples can only use count are typical test values always enough to ensure that a program works? no, look through the program for specific anticipated points of failure and test for those as well what can happen if we don't unit test? things can go wrong, and given the integrality of programs within our world, even a minor bug can have major consequences (lost of funds with Knight Corp, loss of life with : Therac-25 and the Boeing 757 MAX planes, etc.) how can we initialize a dictionary in python? dict() or = {} what are dictionaries filled with? items, which are key-value pairs how to add an item to a dictionary dict[key] = value can we change keys in a dictionary? can we change values? we can't change keys, but we can change their values dict[key] = new value dictionaries function like parallel lists what is the main difference between dictionaries and lists? dictionaries have no internal order, whereas lists do therefore, you have to use specific search methods to get values in lists. why are lists so powerful? because they are very fast (due to organization) and can handle a lot of data in only one object how can we check if a certain key value is present in a dictionary? key in dict incrementation/addition structure for dictionaries if key in dict: dict[key] += 1 else: dict[key] = 1 what is the primary function of a . ye counting dictionary? dict.keys() what are the three main dictionary methods? how can we make them usable? dict.values() dict.items() returns a list of the respective target have to put list() around it and assign it to a variable to make it a usable list list comprehension A neat syntactical way to process ! elements in a sequence and return a ' list with the results. making a new list out of an old list in a single line of code syntax for list comprehension newlist = [x for x in oldlist if ] you don't need the condition (if you don't have it, it will just make a new list of every value in the old list with whatever you have done to the first x applied to it) e.g. newlist = [x*3 for x in oldlist]