Composite Part 2 Flashcards

1
Q

When passing a list as a parameter to a function in Python, it is important to understand that the parameter ——-rather than ———. This means that any modifications made to the list within the function will ——-

A

receives a reference to the list
a new copy of the list
affect the original list outside the function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Reassigning references vs modifying them

A

However, it’s important to note that reassigning a new value to the reference itself (the parameter) will not affect the original list outside the function. For example, if you assign a new list to the parameter, it will only create a local variable inside the function, and the original list remains unchanged. Therefore, when working with list parameters in Python, modifications made to the list itself (such as appending elements, modifying values) will affect the original list, while reassigning a new list to the parameter will not affect the original list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How many list and references in this function:

def fun1():
    aListCopy = [1, 2, 3]
    aListCopy = [2, 3 ,4]
    print (aListCopy)

fun1()
A

In the given fun1() function, there are two lists and one reference.

The first list [1, 2, 3] is created and assigned to the variable aListCopy.
The second list [2, 3, 4] is created and assigned to the same variable aListCopy. This reassignment causes the previous list [1, 2, 3] to be discarded.
Finally, the value of aListCopy (which is the second list [2, 3, 4]) is printed.
Therefore, there are two lists created in the function, but the reference aListCopy refers to the second list [2, 3, 4]. The first list [1, 2, 3] is no longer accessible after the reassignment.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Passing variables not lists you are….Changes made to the paraeters are only made …..

A

making a copy of the value stored in the variable and passing it into the function. Changes made to the paraeters are only made to local variables so you mucg return value back to the caller inorder to be retained.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

when you return lists?

A

So, whether you need to return and pass lists as parameters depends on the specific requirements and design of your code. If you want to modify the original list, it’s not necessary to return and pass it explicitly. But if you want to create a modified version of the list without modifying the original, returning and passing the list can be a good practice.
ex:
~~~
def double_list_elements(my_list):
doubled_lst = [2 * element for element in my_list]
return doubled_lst

my_list = [1, 2, 3, 4, 5]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Which is faster? Passing by value or passing by reference with a list?

A

pass by reference

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Common way to avoid overflowing a list (2)

A

-Use a constant in conjuction with the list
- use the length function len toget the length of list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Lens function

A

The len() function in Python is a built-in function that returns the length of an object. The object can be a string, list, tuple, dictionary, or any other iterable or container data type.

Here’s the general syntax of the len() function:

my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length)  # Output: 5
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Pass by value vs pass by reference difference

A

In “pass by value,” a copy of the argument’s value is passed to the function. Any changes made to the parameter inside the function do not affect the original value of the argument outside the function. The function works with its own local copy of the value.

In “pass by reference,” a reference to the argument is passed to the function. Instead of a copy of the value, the function receives a reference to the original object. Any modifications made to the parameter inside the function will directly affect the original object outside the function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Immutable objects (like numbers(floast, integers), strings, tuples) are passed by

A

value
Any modifications made to the parameter inside the function do not affect the original object outside the function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Mutable objects (like lists, dictionaries)

A

Any modifications made to the parameter inside the function will affect the original object outside the function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

whats the output:
~~~
my_string = “Hello, World!”
length = len(my_string)
print(length)
~~~

A

13

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

how to use lens to find rows and columns:

my_2d_list = [[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]]
A
num_rows = len(my_2d_list)
print("Number of rows:", num_rows)  # Output: 3

num_columns = len(my_2d_list[0])
print("Number of columns:", num_columns)  # Output: 3
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

2-d List is a list…..

A

containing rows of 1D lists

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

For 2-D lists, lists elements are specified in the order of

A

[row] [column]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

in 2-d list. specifying only a single set of brackets….

A

specifies the row

17
Q

Whats the output:
~~~
table = [ [0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]]

for r in range (0, 4, 1):
print (table[r])
~~~

A
[0, 0, 0]
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]
18
Q

Whats the output:
~~~
table = [ [0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]]

for r in range (0,4, 1):
for c in range (0,3,1):
print(table[r][c], end=””)
print()
~~~

A
000
111
222
333
19
Q

What is the output?
~~~
table = [ [0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]]

print (table)
~~~

A
[[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]

Prints entire list

20
Q

Whats the output

table = [ [0, 0, 0],
          [1, 1, 1],
          [2, 2, 2],
          [3, 3, 3]]

print (table[0])
A
[0, 0, 0]
21
Q

Whats the output:

table = [ [["a", "b"], 0, 0],
          [1, 1, 1],
          [2, 2, 2],
          [3, 3, 3]]

print (table[0][0][0])
A
a

In this example, table[0][0][0] retrieves the first element of the table, which is [“a”, “b”]. Then, it accesses the first element of [“a”, “b”], which is “a”, and finally prints it using the print() function.

22
Q

WHat is overflowing 2d list

A

A situation where you try and access or modify an element in a 2-D list using invalid or out of bound indices.

23
Q

A variable that appears to be a list is really a

A

reference to a list

24
Q

The reference and the list are

A

2 seperate memory location!

25
Q

How to copy a list
append way

A
def make_copy(old_world): 
    new_world = []
    max_row = len(old_world)
    max_column = len(old_world[0])
    for r in range(0,max_row,1):
        temp_row = []
        new_world.append(temp_row)
        for c in range(0,max_column,1):
            temp_row.append(old_world[r][c])
    return (new_world)  
26
Q

how many references and lists?

alist = [1, 2, 3]
print(alist[0])
A

2 reference 1 list

27
Q

Copy listy with for loop

A
    for r in range (0,SIZE,1):
        for c in range (0,SIZE,1):
            destination[r][c] = source[r][c]
28
Q

Shallow Copy

A

Copies what is stored in the reference (variables point to same list)

29
Q

Deep Copy

A

Copies data by creating a new list. Copy each peice of data (list elements) from one list to another

30
Q

boundary checking example:

A
import random

SIZE = 4
FIELD = " "
FOREST = "^"
WATER = "W"
BURNT = "F"

def display(world):
   r = -1
   c = -1
   for r in range (0,SIZE,1):
      for c in range (0,SIZE,1):
         print(world[r][c], end="")
      print()
   print()

def editLocation(row,column,world):
   world[row][column] = "!"

def generateElement(randomNumber):
    element = ERROR
    if ((randomNumber >= 1) and (randomNumber <= 50)):
        element = FIELD
    elif ((randomNumber >= 51) and (randomNumber <= 80)):
        element = FOREST
    elif ((randomNumber >= 81) and (randomNumber <= 100)):
        element = WATER
    else:
        element = ERROR
    return(element)

def getLocation():
    outOfBounds = True
    row = -1
    column = -1
    while (outOfBounds == True):
       print("Enter location of square to change to a !")
       row = int(input("Enter a row (0-3): "))
       column = int(input("Enter a column (0-3): "))
       outside = isOut(row,column)
       if (outside == True):
          print("Row=%d, Col=%d" %(row,column), end = " ")
          print("is outside range of 0-" + str(SIZE) + "." )
       else:
          outOfBounds = False
    return(row,column)
  
def initialize():
    world = []
    r = -1
    c = -1
    randomNumber = -1
    newElement = ERROR
    for r in range (0,SIZE,1):
        randomNumber = random.randrange(1,101)
        element = generateElement(randomNumber)
        tempRow = [element] * SIZE
        world.append(tempRow)  # Add in new empty row
        print(tempRow)
    return(world)

def isOut(row,column): #boundary checking
    outside = False
    if ((row < 0) or \
        (row >= SIZE) or \
        (column < 0) or \
        (column >= SIZE)):
        outside = True
    return(outside)

MAIN EXECUTION POINT
def start():
    stillRunning = True
    answer = ""
    row = -1
    column = -1
    world = initialize()
    while(stillRunning): 
        row,column = getLocation()
        editLocation(row,column,world)
        answer = input("Hit enter to continue,'q' to quit: ")
        if ((answer == "q") or (answer == "Q")):
            stillRunning = False

start()
31
Q

Creating 2-D list with the append function for both rows and columns:

A
aGrid = []
noRows = int(input("Number rows: "))
noColumns = int(input("Number columns: "))
#Create list
for r in range (0,noRows,1):
    aGrid.append ([])
    for c in range (0,noColumns,1):
        aGrid[r].append("*")
#Display list
for r in range (0,noRows,1):
   for c in range (0,noColumns,1):
      print(aGrid[r][c], end="")
   print()

First append adds an empty row to the list (line 13)
Second append adds sucessive elements to the newly