Programming Flashcards

1
Q

What are functions used for?

A

Encapsulating code to do a particular job.
They create modularity
Promote good variable scoping and crearer control flow.

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

What is an argument of a function?

A

The bit in brackets
‘def function(argument):’
A function can have many arguments

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

What is the scope of a variable

A

The area of the code from which the variable can be used. Global variable have global scope (can be used anywhere), but function declared in a module can only be used in that module unless they are passed into another function as an argument.

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

Unknown and unlimited arguments

A

‘*args’ is passed into a function as the argument to represent an unknown number of arguments.
‘**kwargs’ is passed into a function as the argument to represent key work arguments, e.g. “conf.xml”. These arguments are accessed by their key rather than position

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

Pep8

A

PEP8 is a general style guide for commenting

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

PEP257

A

PEP257 specifies docstrings that describe functions and modules

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

RegEx characters

., ^, $, *, +, ?, []

A

. -Matches any characters except new line
^ -Matches the start of a string and immediately after new line
$ -Matches end of a string
* -Resulting RegEx matches 0 or more repetitions of given character(s)
+ -Resulting RegEx matches 1 or more repetitions of given character(s)
? -Resulting RegEx matches 0 or 1 repetition of given character(s) [not greedy]
[] -Used to indicate a set of characters in a set . E.g. [0-9A-Fa-f]

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

Environment variables

A

import time
print(time.gmtime())
the gmtime bit is an environment variable

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

Scripts - Inline direct execution

A
  • Start to end execution
  • Threads are created and managed per run or job
  • The route through the program is largely predetermined and independent of other programs
  • Idempotent programs – output should be reproducible (except for intentional randomness) with the same input
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Asynchronous execution

A
  • Asynchronous jobs are run from a queue and don’t have to be executed in the order they occur
  • Crucial for automation
  • This can improve load management by reducing bottlenecks although can create concurrency issues
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Example of asynchronous event driven architecture

A

Websites use this

Flask

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

Python Path

A

Environment variable where additional modules are stored - pip installs to here.

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

Module used to schedule commands for a specific time

A

Sched module

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

What is ‘@app.route(“/home”)’

A

Code for flsk to show code run when the /home page of your website is run

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

Restful API calls

A

Using API key with a url to use data from a website in a program.
Data usually received in a .json file, and relevant parts can be taken from this.

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

Software reliability - Defensive programming

A

Used for edge cases to stop program crashing

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

Software reliability - Exceptions

A

An exception is raised when one one of these errors occurs:
IndexError I ValueError I EOFError I AssertionError I SyntaxError I
IndentationError I KeyboardInterrupt
or you can define your own exceptions

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

Try-except (try-catch)

A

The try: … except: statement attempts to run code, but if it would raise an exception (crash the program), the code below except is executed instead

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

try … except … finally

A

The try: … except: … finally: overrides all error handling as final block. The code under ‘finally’ will run regardless of any raised exceptions.

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

‘raise’ keyword

A

To raise an exception in your code use the keyword raise - this is beneficial for defensive programming.

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

Keyword for unit testing in python

A
'assert'
assert function(“test”) == “test result”
try:
tests()
except AssertionError as message:
print(message)
game_play()

assert “rat” in word_lookup(“tar”), “word_lookup: FAILED“

22
Q

Logging

A

• Log files keep a log of system activity
• Like a ledger they are immutable
• If something is created and then deleted the live system should have no record of it. However, the log should retain the update record
showing the existence of something for that period
- Logs record a persistent history of the system
• Log files have two main uses:
- Tracing errors; An error log
- Recording system events; A system log

23
Q
Slicing a string
string = "hello"
a = string[1:3]
b = string[0:6:2]
a =...
b =...
A
string = "hello there"
a = string[1:3]
b = string[0:6:2]
a = "el"
b = "hlo" (stride = 2)
24
Q

Dictionaries

A

A dictionary behaves like a list, but it can be ’indexed’ by
arbitrary variables. (Is like JSON)
D = { ’ dracula ’ : 18 , ’a ’ : 1113 , ’ mystery ’ : 6}

25
Q

Order of keys and values

A
  • If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are
    called with no intervening modifications to the dictionary
    • then the lists will directly correspond
  • This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys())
26
Q

zip function

A

zips 2 lists together to create a list of tuple pairs of items of the same index from either list. Only as long as the shorter list.

27
Q

making dictionaries with zip() and dict()

A

zip together a list of keys and a list of values, then dict(the zip) to make it into a dictionary.

28
Q

How would you increment the value of one key? (‘dracula’)

A

D [’dracula’] += 1

29
Q

How would you add a new item to the dictionary? (‘stake’)

A

D [’stake’] = 1

30
Q

How would you check whether a key exists?

A

’ dracula ’ in D
True
»> ’ coffin ’ in D
False

31
Q

How would you remove a key-value pair?

A

Same as list but key instead of index -

D.pop(‘mystery’)

32
Q

How is hashing used in a dictionary?

A

The keys are hashed and the hash identifies each key

33
Q

When to use dictionary/list

A

Use lists when there is a natural order to the keys/indices,

but dictionaries when there is no particular order

34
Q

Immutable vs mutable

A

Immutable variables are not changed in place (memory location), while
mutable variables are changed in place

35
Q

Tuples

A
  • Immutable sequences

* Automatically packed and unpacked on assignment

36
Q

when is ‘a is b’ true

A

when a and b hold the same position in memory

37
Q

a = “hello”
b = “hello”
a is b =…
a == b =…

A

a = “hello”
b = “hello”
a is b = False
a == b = True

38
Q
a = 20
b = 20
c = 500
d = 500
a is b =...
a == b =...
c is d =...
c == d =...
A
a = 20
b = 20
c = 500
d = 500
a is b = True (since 20 < 256)
a == b = True
c is d = False
c == d = True
39
Q

What is recursion?

A

When something is defined in terms of itself (calls itself from within)
Needs a base case to escape the loop when a certain condition is met. At each recursion we get closer to this case.

40
Q

What make a function a first class object?

A
A function is a first class object because you can 
• Store functions in collections
• Use functions as arguments to other functions
• Use functions as return values of other functions
• Create new functions from preexisting functions at run-time
41
Q

reduce — accumulating a result from a list

A

reduce applies the function of two arguments cumulatively to the items in the sequence S, resulting in a single value. If initial is supplied it is placed before the other items in the sequence.
- reduce(function, sequence) reduces the sequence cumulatively to a scalar result.
reduce( lambda x , y : x + y , [1 , 2 , 3 , 4 , 5])
= 15
(Computes ((((1 + 2) + 3) + 4) + 5))

42
Q

map function

A
• map(function, sequence [sequence, sequence, ...]) applies function to each item
in sequence (or sequences)
43
Q

filter function

A

• filter(function, sequence) returns the list comprising the items in sequence for which function returned True. (Same as our sieve.)

44
Q

Insertion sort

A

Build a new list from the old one inserting each element in the correct
place
Takes about N^2 operations
Useful for small lists

45
Q

Bubble sort

A
Go through the list swapping pairs of adjacent elements that are out
of order; repeat until list is sorted
On average takes about N
2 operations.
Not practical - insertion better
46
Q

Shell sort

A
  • Sort pairs of elements far apart from each other.
  • Progressively reduce the gap between elements to be compared.
  • This can move out-of-order elements into position faster than neighbour exchange
47
Q

Merge sort

A

divide the list into rough halves, sort each half and merge the results
on average about Nlog2(N) operations
Suitable for sorting very large lists which must be stored offline
Can be implemented in-place, but complicated and not fast

48
Q

Python standard sort

A

Standard sort is list method that sorts in-place
The ‘sorted’ function returns a copy of the sorted list
> S = sorted ( L )

49
Q

Software Development Lifecycle (7 steps)

A

1) Planning - resourcing and setting up the environment
2) Requirements engineering - fleshing out the technical requirements
3) Design + prototype - does it work with test examples
4) Software development - writing production software
5) Testing - providing tests to demonstrate functionality
6) Deployment - publish and run the software in the wild
7) Operation and maintenance - upkeep

50
Q

What is a python package

A
• A Python package is just a directory containing python modules
• Python provides a module namespace within packages
 - package.module
• Python also provide 'setuptools' and 'distutils' to help configure, build
and distribute coherent package resources
51
Q

__init__.py package

A
  • Necessary for package to be recognised
  • Initialise any code for the package and set __all__ variables
  • Often empty for basic projects