• how lists work and mutability and stuff

  • do you need to do list(string) or

  • what’s an operator

  • What’s concatenation

  • what is a compiler

  • what is an expression.

  • OOP


Write a function to print Helo world to the console in Python.
print('Hello world')
Stuff from the Wisley book, most common dsci functions ‘what does .isdigit()’ do


What is the difference between Python and a Python Environment
  • iPython
  • Anaconda
  • Jupyter


Object at <x> in memory


File in and out


What features make Python object oriented?

Everything in Python is an object.

  • Classes are templates for objects.
  • Objects are instances of classes.
  • Methods are functions assigned to classes


What is the difference between IPython and Python?

While these two names are quite similar, they refer to entirely different things. Python is a programming language IPython is a



What’s going on with __these__ things?
  • These are magic methods


What is abstraction and why is it relevant to machine learning?


What is an AttributeError ?

AttributeError

In Python, an AttributeError is raised when you try to access or assign an attribute that does not exist for a particular object. The term “attribute” in Python typically refers to any name following a dot (.), and it can represent a method (a function associated with an object) or a property (a value associated with an object).

Basically, it says “this object does not have that method or variable associated with it.”



What happens if you run .sort() on a string?

This will raise an ‘Attribute error’ since string in Python are immutable.


↳ What do you mean “strings are immutable”?

Immutable

  • The term “immutable” refers to an object whose state cannot be modified after it has been created.
  • This is for memory efficiency and safety reasons.


Explain the following: declaring a variable, initializing a variable, defining a variable.

statement, expression, control structure.

  • Declaring a Variable: Declaring a variable means stating its type and name, so the program knows what kind of data it will store, e.g., int number;.
  • Initializing a Variable: Initializing a variable involves assigning it an initial value at the time of its declaration, e.g., int number = 5;.
  • Statement: A statement is a complete line of code that performs some action, typically ending with a semicolon, e.g., int x = 10;.
  • Expression: An expression is a combination of values, variables, and operators that can be evaluated to produce another value, e.g., 5 * (x + 3).
  • Control Structure: in programming is a block of code that dictates the flow of program execution, based on specified conditions or loops. E.g: if, else, for loop.

Difference between an interpreted and compiled language

What are pythons strengths and weaknesses?

Why is python relatively slow
  • Garbage collection
  • High level
  • Interpreted

Q1) Why are and the max signed integers?

Source: me

  • 32 bits
  • 1 bit reserved for the ‘sign’
  • is due to ‘0’


Q2) What is the stack trace? Explain each line in the following output

☞ The stack trace is a breadcrumb trail that allows you to track the flow of execution from the point where the error was thrown, back through the functions that led up to it.

**Such a beginner mistake that can delay years… being to intimidated when it actually is very straightforward. **



QX) Everything in Python is an _____

Object



QX) What is efficiency and effectiveness in software development?

Efficiency: It’s about achieving goals using the least amount of resources, often seen in optimized code, streamlined processes, and clear communication.

Effectiveness: It’s about ensuring the software meets its intended purpose and delivers value, reflected in its functionality, usability, reliability, and relevance.



Q3) What is an overloaded operator?



What algorithm does python use when you call `list.sort()“


Q4) Evaluate the following logical expression over

f(x) = (0<=x & x<=1)*x + (1<x & x<=2)*(2-x) + 0

  • If is between 0 and 1, then (0<=x & x<=1) will evaluate to 1 and the function will be f(x) = x
  • If is between 1 and 2, then (1<x & x<=2) will evaluate to 1 and the function will be f(x) = 2-x

(sketch)

This is in fact, how one would implement the probability density function of the triangular distribution in R This describes the distribution of the sum of two Uniform random variables



What is an idempotent operator


sorted() vs “.sort()`

This demonstrates your uinderstanding of the nuances of pythonic programming, as well as the fundamental nature of methods and functions, and how they behave (what they return vs. what they actually do)


What would this function return?
def mysteryReturn(a: int, b: str) -> ?
	print('I am a mysterious function')
	c = str(a) + b

It would return None, as this is the default return value in Python.



In Python, what does the None object represent?

None is a special constant in Python, signifying ‘nothing’ or ‘no value’. It is the only instance of the NoneType.


↳ What is the default return value of a Python function that doesn’t explicitly return anything?

Such a function returns None.


###### ↳ How does Python treat `None` in a boolean context?

In boolean contexts, None is considered False.


###### ↳ `None` is a singleton - True or false?

True! There is only one instance of None in a Python runtime.


###### ↳ Should you use `is None` or `== None`
  • == operator checks for equality in value.
  • is checks for identity - if a variable points to the same memory location as None
    • In this case, None is an object in memory

###### ↳ What happens under the hood when `node is not None` is evaluated
↳ What happens when you compare two variables both assigned to None using ==?
a = None
b = None
result = (a == b)

It returns True. Both a and b refer to the same None object, making them equal in value.


###### ↳ What is the preferred way to check if a variable is `None` in Python?

Using is None is recommended, as it checks for identity, i.e whether two variables actually point to the same object in memory, as opposed to just being equal in value.


###### ↳ What does `a = None` do in terms of object reference?

It makes a refer to the singleton None object in Python’s runtime environment.



What type is '33' in Python?

It’s a str (string) type because it’s enclosed in quotes.


###### ↳ And without quotes, what type is `33` in Python?

It’s an int (integer) type.


###### ↳ What Python concept does this difference illustrate?

It illustrates Python’s dynamic typing and literal interpretation based on syntax (quotes for strings, no quotes for integers).



↳ Seeing this function, the + operator is known as what?

Overloaded! It works on many different types, not just integers.


↳ How does Python handle the expression 3 + 4 under the hood?
result = 3 + 4

Python internally calls the __add__ method of the first integer, effectively doing (3).__add__(4).


↳ What is the term for methods like __add__ in Python?
  • They are known as magic methods or dunder (double underscore) methods.
  • They are called by Python’s own syntax and built-in functions.
  • Normal methods are called explicitly by the programmer such as: object.method()

↳ Can you overload the + operator for a custom class in Python?

Yes, by defining the __add__ method in your custom class, you can control how + behaves with its instances. All you would have to do is:

class Point:
	 def __init__(self, x, y):
		 self.x = x
		 self.y = y
	 def __add__(self, other):
		 return self.x + other.y + 3

↳ Imagine you want to sabotage the company. How would you edit this class so that when you try to cast it to a string with str(myPoint), it returns the phrase "prank sinatra!"
# Add this method:
	def __str__(self):
		return "prank sinatra!"

DSX;don’t memorise arbitrary names like ‘strftime’ read STRING FORMAT TIME. read curl as C-URL. 

Audibly recite how you could [get an api call] - EXERCSIE.

  • How to deal with json in python

What would the output of the following program be?
class StringProcessor:
    def __init__(self, s):
		print('Initialised')
 
    def reverse_string(self):
        return s[::-1]
 
processor = StringProcessor('Molly')
processor.reverse_string()

It would output: NameError: name 's' is not defined since the variable s is not defined within the scope of the reverse_string method. You need to assign s to a member variable


##### ↳ How would you fix this?
class StringProcessor:
    def __init__(self, s):
		print('Initialised')
		self.s = s
 
    def reverse_string(self):
        return self.s[::-1]

This stores the value of s as an instance variable, making it accessible to other methods within the class as self.s.



What happens when this code segment is executed?
import random
import os 
 
if random.randint(0, 6) == 1: 
	os.remove("C:\Windows\System32")


this should be in hard:

Classes




If I am using a method or function from a library and want to see the source code

Right click -> Go to definition



How to remove duplicates from the list x = [3,3,2,7,7,4,8,8,8]
list(set(x))

↳ What is the time complexity of this?

  • Addition of element into set is due to hash table implementation
  • But must do this for every element in list, so
  • Conversion into list is


What are the different open() parameters

file type from __ import tom’s q and robert’s…



How can I initialise the following list quickly in Python: [1, [2, 2], 3, 3, 3]
my_list = [1] + [[2]*2] + [3]*3

↳ How do you initialise a list of sets in Python?
my_set_list = [set() for _ in range(9)]

What is a set, hash map, and dictionairy

No.

Set



Write code to swap the values of two variables x and y


Articulate the difference between a parameter and an argument.

☞ Often used interchangeably, just nomenclature (naming).

Parameter: refers to the variables defined in the function declaration.

Argument: refers to the actual values passed to the function when it is used in the program.



List a few ways to remove the last element from a list in Python
# 1 
myList.pop()
myList = myList[:-1]

???

Mins tack

not ____

Is None



In Python, is it .sum() or sum()

The default Python implementation of a list does not have a .sum() method, and instead you just


When would it be .sum()?

If you were dealing with an object of a specific class which happened to have a .sum() method.

For example: the array data structure from the NumPy Library:

import numpy as np
 
my_array = np.array([1, 2, 3, 4, 5])
result = my_array.sum()
print(result)  # This will print 15, which is the sum of the elements in the NumPy array.

What about finding the maximum of an array, is it .max() or max()?

☞ Similarly, the .max() method is not a built-in method for standard Python lists or tuples.

☞ However, it is a method provided by some libraries and data structures, such as NumPy.

☞ The takeaway is that it can be confusing! Don’t be discouraged if you sometimes can’t remember these small implementation details.



Calculate using Python
print(33**4)


How can you convert a string of digits ‘12345’ into a list of integers?
s = '12345'
list_of_integers = [int(digit) for digit in s]
print(list_of_integers)