Computer Science/coding Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Variables

A

Used to store data/information so that it can easily be repeated or reused throughout the code

In Python variable are used for things that are subject to change

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

Primitive data

A

The most basic forms of data:

Strings
Boolean (defined in Python as true or false (1 or 0))
Number

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

Operators

A

Different symbols that represent an operation

Enable us to process data and transform it

Arithmetic operators - make calculations
Comparison operators - determine the relationship between two values resulting in a Boolean
Logical operators - determine the logical state of multiple Boolean values or expressions resulting in another Boolean

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

Functions

A

Used in coding lots they are sequences of instructions that perform specific tasks

The inputs are called parameters

The actual values for each input are called arguments

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

Lists

A

Order items so that they’re in a specific sequence

The position of a value in a list is called its index

Adding things to the end of an existing list is called appending them to the end

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

Print statement

A

Used in Python to get the computer to ‘say’ something

e.g. print “Hello, world” makes the computer display that

Mismatched quotation marks will cause an error

Python 3 also requires brackets

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

Modulo operator

A

Indicated by %

It returns the remainder after a division is performed

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

Comments

A

Pieces of information used to describe the code

Use a # followed by the comment

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

Multi line strings

A

Use triple quotation marks

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

Converting between data types

A

Use str() for converting to a string

Use int() to convert to a numeric data type

float() to make it a decimal

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

len()

A

Determines the length of a string

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

“Ryan”.lower()

“Ryan”.upper()

A

Makes all the letters in the string lowercase

So this would give ryan

Makes all the letters in the string uppercase

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

str()

A

Turns non-strings into strings

E.g. 2 to “2”

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

% operator

A

Used to combine strings with variable

The % variable will replace the %s in the string

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

Boolean operators order

A

Not

And

Or

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

Lists

A

come in these brackets []

to choose an item from a list use its index - remember to count from 0 (positive indexing)

can also choose negative indexing, but this is rarely used only for long lists (the last item had an index -1, the next one -2 and so on)

list slicing - use a colon to access a few items in the list e.g. [1:9] will access index 1 to 8 of the list (the last index is discluded)

e.g.

will = [jalksjfl, fslakdjf, fjlaj]

they can have mixed data types

if you have a list within a list, rather than accessing and then saving as a variable you can chain indices to access something

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

Dictionary

A

similar to a list but has ‘keys’ instead of indices and the contents are in { }

they come in the form key : value

to retrieve a value from a list you use the same form as lists

dictionary values can be of any data type whilst dictionary keys can be of any except lists and dictionaries

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

What two rules must be adhered to when naming variables?

A

Variable names cannot start with a number

We must only use letters, numbers or underscores

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

concatenation

A

The process of linking two or more strings together, usually involving the str() function

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

open()

reader()

list()

A

used to open files

used to read files (must be imported from the csv module)

transforms files into lists

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

For loops

A

Consist of an iteration variable, an iterable variable and a body

The indented code in the body gets repeated as many times as there are elements in the iterable variable

each time the code in the loop is executed its called an iteration

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

Comparison operators

A

== An operator used to describe/determine if two values are equal

The result is either true or false (boolean)

!= An operator used to describe/ determine if two values aren’t equal

there are also > < >= and <=

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

type()

A

Used to determine the data type of whatever is found between the brackets

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

If statements

A

Conditional statements that usually involve some sort of comparison

They must be followed by a boolean value or an expression that evaluates to a boolean value

logical operators : and or

these are added to the if statements to add more conditions

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

How does python use multiple booleans?

A

It combines them to a single boolean

when using and : will only be true if all the individual booleans are true

when using or : will only be false if all the individual booleans are false

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

else

A

Only executed if the if statement preceding it is false

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

Compound statement

A

When an if statement is combined with an else clause

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

elif

A

used within an if statement

it is only executed if the preceding clauses (e.g. if or elif)
resolve to false and the elif condition resolves to true

improves efficiency as it means the computer doesn’t iterate over redundant code

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

adding values to an empty dictionary

A

takes the form dictionary_name[index] = value

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

Why can’t dictionaries and lists be keys?

A

hash() python uses this to try and convert each dictionary key to an integer even if its not that type

the hash command doesn’t transform lists and dictionaries to integers hence lists and dictionaries can’t be keys

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

in operator

A

used to determine if certain keys exist within a dictionary

or used in loops

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

min()

max()

A

used to determine the minimum and maximum values

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

How does the len() function work

A

Imagine we have a list - list = [1, 2, 3, 4, 5]

if we use a loop and a variable called length we can manually determine the length:

length = 0

for value in list:
length += 1

This would give us an output of 5 and that is effectively how the len() function works

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

How does the sum function work?

A

Imagine we have: list = [1, 2, 4, 5, 64]

sum_manual = 0

for value in list:
sum_manual += value

This is effectively what the sum function does

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

Built-in functions

A

These are functions which pre-exist and can be readily used with python e.g. len() sum()

But python also allows us to build our own functions

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

How we make functions?

A

e.g. to make a function to square numbers:

def square(a_number):
      squared_number = a_number * a_number 
      return squared_number 

to find the square of 6 we would then use square(a_number = 6) or we could use square(6)

Input variables like a_number are known as parameters, whereas 6 is known as the argument - the parameter a_number took in 6 as an argument

we start with a def statement to introduce defining the function

we specify the name of the variable that will serve as an input and then show what we want to do with that input

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

The definition of a function

A

The three elements that make up the definition are:

The def statement

The body

The return statement

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

Keyword arguments

A

When inputting the argument into the function the order doesn’t matter

e.g. subtract(a, b)

subtract(a=10, b=7) = 3 and subtract(b=7, a=10) = 3

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

Positional argument

A

The argument isn’t as clearly defined as keyword arguments so order does matter

e.g. def subtract(a, b):
return a - b

subtract(10, 7) isn’t the same as subtract(7, 10) as we are using positional arguments

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

Interfering with built in functions

A

Don’t name your functions the same as built in functions as this could confuse you and will alter the way the function operates

It leads to abnormal function behaviour

You should also avoid naming variables or lists after built in functions

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

Default arguments

A

Creating a function with some of the parameters being certain default values

e.g. def add_value(x, constant = 10):
return x + constant

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

What if we want to produce a function that can be used to produce either the sum of two numbers or the difference between two numbers?

A

We use multiple return statements with a conditional statement:

def sum_or_difference(a, b, do_sum = true):
       if do_sum:
               return a + b 
       else:
               return a - b
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

Tuple

A

Another data type very similar to a list

It’s in this form: (9, 0) or this form 9, 0

Used for storing multiple values

Just as lists they support positive and negative indexing

Differences between tuples and lists - existing values can be modified in lists but they can’t in tuples

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

Functions with multiple outputs

A

We can have functions that return more than one variable

e.g. a function that returns the difference between two numbers and the sum of two numbers

This returns a tuple
If you put square brackets around the variables in the return statement then this returns a list

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

Immutable data types

A

Can’t change their state after they have been created

Booleans
Strings 
Floats 
Integers 
Tuples
46
Q

Mutable data types

A

Their state can be changed after being created

Lists
Dictionaries
Sets

47
Q

Scope

A

The part of the a program where a variable can be accessed

Local scope - variables defined in a function (outside the function such variables would be undefined)

Global scope - variables defined in the main program (global variables)

48
Q

Functions and temporary memory

A

Python only has a ‘temporary memory’ for variables used within a function

If such variables are used outside the function they are undefined thus causing an error

49
Q

str.replace()

A

A method used to replace part of a string

We substitute str for the variable name of the string we want to modify, then in the brackets we first put the substring we want to replace and then what we want to replace it with

e. g will = ‘my favourite colour is red’
will. replace(‘red’, ‘green’)

This will replace red with green

50
Q

str.title()

A

returns the string with the first letter of each word as a capital letter

str is replaced by the variable name of the string

51
Q

str.split()

A

Used to split a string in two resulting in a list

The name of the variable replaces str and the point at which the split needs to take place goes in the brackets

e. g. date = ‘2002-2003’
date. split(‘-‘) = [‘2002’, ‘2003’]

52
Q

Inserting a variable into a string using %

A

stuff_in_string = “Shepherd %s is %d years old.” % (shepherd, age)
print(stuff_in_string)
Shepherd Martha is 34 years old.

53
Q

Inserting a variable into a string using the string format method

A

shepherd = “Mary”
string_in_string = “Shepherd {} is on duty.”.format(shepherd)
print(string_in_string)
Shepherd Mary is on duty.

54
Q

Recursive functions

A

Functions that can call themselves

The function will continue to call itself until a base condition is satisfied

If there wasn’t a base condition the function would call itself infinitely

55
Q

Example of a recursive function - finding factorials

A
def factorial(x):
    if x == 1:
        return 1 
    else:
        return (x * factorial(x - 1))

The base condition is x == 1 so the function will keep repeatedly calling itself until x == 1

this is how it works, let’s say x = 5:

factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1 

hence factorial(5) = 5 * 4 * 3 * 2 * 1

56
Q

Anonymous/ lambda functions

A

functions that are defined without a name

rather than being defined by def they are instead defined by lambda

Generally used as arguments for higher order functions

syntax is as follows:

lambda arguments : expression

It can have any number of arguments but only one expression

e.g. lambda x : x * 2 
# this is a function that will double its input 

so double = lambda x : x * 2
double(5) = 10

57
Q

filter()

A

This is a higher - order function which takes a function and a list as its arguments and filters the list according to the function

e.g. mylist = [2, 4 ,6, 9]

newlist = list(filter(lambda x : (x%2 == 0), mylist)

newlist = [2, 4, 6]

58
Q

Why do we use an asterix before an argument of a function? - Python arbitrary arguments

A

This is used when we do not know the number of arguments we are going to pass through the function in advance

It allows us to use a random number of arguments

59
Q

docstring

A

Below the initial header of a function we can use triple quotation marks to produce a string which explains what the function does

This is documentation and it is good programming practice

Use this or comments

60
Q

global keyword

A

This is used to make changes to a global variable from within a function

If this keyword is used outside the function then it has no effect

61
Q

config. py

update. py

A

A single module used to store global variables

A single module used to change global variables

62
Q

python modules

A

A python file containing statements and definitions

Used to break down a large programme into smaller, organised files

We use the import function to import a module and the module.function()

e.g. import example
# this imports example.py
example.add(1, 2) 
#this makes use of the add function already defined in example
63
Q

Renaming modules in a file

A

use ‘as’

e.g. import math as m 
#this renames math to m
64
Q

Importing specific variables and functions from a module

A

use ‘from’

e.g. from math import pi
#this imports the pi variable from math 

or we can import all:

from math import *

65
Q

dir()

A

the name of a module is entered in the brackets

this function then returns a list of all the attributes (e.g. functions and variables)

66
Q

Python packages

A

A group of similar or related modules, often used for the same project etc

Must contain a init.py file for it to be considered a package even if this is empty

67
Q

isinstance()

A

used to identify if an object is in a certain class or type

syntax is like this: isnstance(object, classinfo)

its result is true or false

68
Q

complex numbers

A

in the form a + bj

where a is the real part and b is the imaginary part

69
Q

string slicing

A

strings can be sliced the same way a list can be sliced

70
Q

:.2f

A

This results in a precision of two decimal places

This is used when formatting a string to contain a given number

This must come after the thousands separator if its present

71
Q

:,

A

Used when formatting a string to contain a given number

It puts commas for every thousand to make the number easier to read

This must come before the precision

72
Q

dict.items()

A

returns a list of the dictionary’s (key, value) tuple pairs

the name of the dictionary replaces dict

73
Q

Procedural programming

A

Writing code in a number of sequential steps, sometimes these steps are combined to form functions

74
Q

Object-oriented programming

A

Code is designed around objects

In OOP the type of an object is known as its class

Focuses on creating reusable code - this concept is known as DRY (don’t repeat yourself)

75
Q

Object

A

An entity which stores data

It combines data and functions

76
Q

Class

A

Defines specific properties an object of that class will have

The rules for naming classes are the same as for naming functions and variables

We say two different objects of the same class are two instances of that class

The class can be thought of as a design and the object is the thing that we build using that design

77
Q

Class definitions

A

These are like the ‘code blueprints’ for a class

They contain the information needed to create that class

its in the format:

class myclass():
#details of the class go here

similar to defining a function

78
Q

Snake case

A

the convention used for naming functions and variables

uses lower case words with underscores like_this

79
Q

Pascal case

A

the convention used for naming classes

uses no spaces and capital letters for the start of each word LikeThis

80
Q

Instantiation

A

Creating an object of a defined class

‘Instantiate an object of that class’

An instance is a specific object created from a particular class

81
Q

pass

A

A keyword that allows us to leave the details of a class empty when defining it, without raising an error

82
Q

methods

A

used as part of the definition of a class to allow objects of that class to perform certain actions

can be thought of as special functions that belong to a particular class

methods are created as functions within a class by using indentation

we have to create one of the parameters to be self

83
Q

attributes

A

special variables that belong to a particular class

attributes let us store particular values about each instance of the class

data is stored inside objects using attributes

attributes are the characteristics of the objects

84
Q

__init__() method

A

This is used to define what is done with arguments provided at instantiation

It runs when an instance is created

It’s most common usage is to store data as a attribute

It’s a constructor that creates variables that contain values for each instance of the class - these values are specific to each instance due to the different arguments

85
Q

self

A

The first argument passed to every method, the convention is to call this self as it represents the instance we are calling the function on

This prevents an error occurring

e.g. class MyClass():
            def printclass(self):
                      print(self)

mc = MyClass()
mc.printclass()

This will print the object itself - mc

86
Q

What is a set in python?

A

Created using the set() function or by placing values in {}

It’s an unordered collection of items with each item being unique (no duplicates) and each item must be immutable

The set itself is mutable it can have elements added or subtracted

It can be used to perform mathematical set operations

87
Q

How to change a set in python by adding elements?

A

They are unordered so they don’t support indexing or slicing

set. add() can be used to add individual elements to the set where the name of the set replaces set in this method
set. update() can be used to add multiple elements to the set

Duplicates are avoided

88
Q

How to subtract elements from a set in python?

A

Elements can be removed via the set.discard() method and the set.remove() method

The only difference is that if discard is used and the element isn’t in the set it will remain unchanged

However, using remove in this scenario would result in an error

89
Q

set. pop()

set. clear()

A

This can be used to add or remove elements from a set but it is completely random as to what element will be removed

All the items of a set can be removed using clear

90
Q

Finding the union of two sets

A

Use the union() operator e.g. for union of set A and B
A.union(B)

OR use | e.g. print(A|B)

91
Q

Finding the intersection of two sets

A

use the intersection method - e.g. for A intersection with B A.intersection(B)

or use & e.g. print(A & B)

92
Q

Finding the difference of set A

A

This is known as the elements that are only in set A but not in B

in python its called the difference of A and B (A - B)

its found using print(A - B) or using the difference method

e.g. A.difference(B)

93
Q

Set symmetric difference

A

This is all the elements in sets A and B except those that are common in both

We use the ^ operator or the set.symmetric difference method

94
Q

Frozensets

A

These are another class

They are immutable sets and they are created using the frozenset() function

95
Q

Inheritance

A

A way of creating a new class using the details of an existing class without modifying it

The child class inherits the functions of the parent class

We use the super() function to help achieve this

e.g, super().__init__() within the brackets of init would be the names of the attributes to be inherited

96
Q

Polymorphism

A

The ability in OOP to use a common interface (often a function) that can be used by multiple form (data types/classes)

97
Q

__Big__O

A

This is a measure of how long it takes to complete a particular algorithm when scaling it up

98
Q

Constant time

A

When a computer performs a task that goes to the end of an array and looks at the last thing - the time taken to do this is independent of the number of items

99
Q

Linear time O(n)

A

The time it takes to complete the task is directly proportional to the number of items

100
Q

O(n^2)

A

The time it takes to process n items is directly proportional to n^2

This needs to be avoided in algorithms as much as is possible

101
Q

O(n!)

A

The time taken to complete the task is directly proportional to n! where n is the number of items

An algorithm of O(n!) is to be avoided at all costs

102
Q

Arrays

A

A data type similar to a list in which you can store values only of the same data type

It isn’t a fundamental data type so you have to import the array module

syntax is as follows arrayname = (typecode, [values])

the typecode defines the type of array

you can use indexing and most list methods

103
Q

Using pandas for opening data

A

pandas is a software library that can be used to open and display csv files

We use panda.read_csv() to read the file

and filename.describe() to show the data

filename.columns shows the column names

104
Q

using pandas to remove missing values

A

use filename.dropna(axis = 0)

105
Q

re.search() method

A

This takes in two arguments, a string and a regular expression and it searches the string for the regular expression

e.g. re.search(‘will’, [aeiou])

It either returns match or none

It is usually followed by an if statement

106
Q

Regular expressions

A

These are common patterns that we can search for in a string using the re.search() method

107
Q

listname.sort() method

A

Used to sort an list

By default the method sorts based on ascending order either alphabetically or numerically

listname.sort(reverse=True) will sort it based on descending order

108
Q

Linear search

A

Checks to see if the first item in the list is the item we are looking for, then it checks the third, fourth, fifth etc

It keeps checking until it finds the item we are looking for or until it reaches the end of the list

It’s O(n)

109
Q

example function to perform a linear search

A
def linear_search(item, my_list)
     i = 0 
     found = False 
     while i < len(my_list) and found == False:
         if my_list[i] == item:
             found = False 
         else:
              i = i + 1 
      return found
110
Q

Binary search

A

Relies on having a sorted list

Starts in the middle and if the item we are looking for is higher then anything lower than the middle is discarded and vice versa if its lower

This is repeated with the bit of the list that’s left - each time the length of the list that is left is halving

This process repeats until the item is found

111
Q

example of a binary search algorithm

A
def binary_search(item, my_list):
    found = false 
    first = 0 
    last = len(my_list) - 1 
    while first <= last and found == False:
            midpoint = (first + last)// 2 
            if my_list[midpoint] == item:
                  found = True 
            else:
               if my_list[midpoint] < item:
                     first = midpoint + 1
               else:
                     last = midpoint - 1 
           return found
112
Q

Insertion sort

A

Takes the second item in the list and compares it to the first item in the list, if it is greater than the first item then it remains where it is but if its smaller we move it before the first item. This process continues except the comparisons have to be with more items as this progresses to ensure it goes in the right location