Programming Questions Flashcards

1
Q

Explain Decorators

A

Alright, imagine you’re going into a theme park, but instead of you just rushing straight to the roller coaster, there’s this cool, funky hat you have to wear. This hat isn’t just any hat. It gives you superpowers like making you run super fast to get to the roller coaster quicker, or maybe it makes you invisible so you can skip the line. That’s essentially what decorators do in Python. They’re like these magical hats for your functions.

So, let’s break it down, StatQuest style, with a simple example to really nail it.

The Basics: Wrapping Up Functions

Think of your Python function as someone going to a theme park (yeah, that’s you!). Now, this function wants to do something fun, like print a message. Normally, you’d just go in, get on the ride, and that’s it. But what if we could make that experience even cooler?

Enter the decorator, aka the “magical hat”. You put this hat on (or, in Python terms, you wrap your function with a decorator), and suddenly, your simple trip to the theme park becomes much more exciting.

A Simple Magical Hat: The Decorator

Let’s say we have a magical hat called @my_decorator. This hat makes you shout with excitement before and after the ride. Here’s how you make this magical hat:

```python
def my_decorator(func):
def wrapper():
print(“Wooo! Going on the ride!”)
func()
print(“Wow! That was awesome!”)
return wrapper
~~~

And here’s how you wear it:

```python
@my_decorator
def my_ride():
print(“Weee, I’m on the ride!”)
~~~

When you go to the theme park (call my_ride()), here’s what happens:

Wooo! Going on the ride!
Weee, I'm on the ride!
Wow! That was awesome!

What’s Happening?

  1. Before the Ride (Function Call): The decorator makes you shout with excitement before the ride starts. This is like the code that runs before your function does its thing.
  2. During the Ride: This is your function doing what it was always meant to do. In our theme park analogy, this is you, enjoying the ride, shouting “Weee!”.
  3. After the Ride: The decorator makes you express how awesome the ride was. Similarly, this is code that runs after your function.

Why It’s Super Cool

Decorators allow you to enhance your functions without changing the fun (code) inside. It’s like getting all the benefits of those superpowers without having to permanently change anything about yourself. You can add logging, timing, or any other super cool features with ease.

Real-World Use

Imagine you’re developing a game, and you want to track how long each game level takes to complete. Instead of rewriting the timing code for every level, you just create a magical hat (decorator) that does it for you. You slap that hat on every level function, and voilà, you’re now tracking completion times with minimal code and maximum efficiency.

Wrapping Up

So, decorators are like your ticket to a more exciting, efficient, and super-powered coding experience. They let you add awesome features to your functions without changing the core fun (logic) inside. And just like in a theme park, the possibilities are endless. Welcome to the magical world of Python decorators!

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

Describe the difference between a list, tuple, and dictionary in Python. When would you use each data type?

A

Alright, let’s dive into the fun world of Python’s data structures, where each one is like a unique container for your data, each with its own special features!

Lists: The Flexible Friends

Imagine a list as a train where each carriage can hold any item you like. You can add more carriages (elements), remove them, or even change what’s inside them while the train is on its journey. That’s a list for you: ordered, changeable, and it allows duplicate elements.

```python
my_list = [‘apple’, ‘banana’, ‘cherry’]
~~~

When to Use Lists?
- When you have a collection of items in an order, and you anticipate modifying this collection by adding, removing, or changing items.

Tuples: The Trusty Constants

Now, think of a tuple like a train where the carriages are locked in with what they carry from the start. You can’t add more, take away, or change what’s inside once the journey begins. Tuples are ordered, unchangeable, and they allow duplicate elements.

```python
my_tuple = (‘apple’, ‘banana’, ‘cherry’)
~~~

When to Use Tuples?
- When you have a collection of items that shouldn’t change through the life of your program. They’re faster than lists and protect your data from being altered.

Dictionaries: The Smart Organizers

Imagine a dictionary as a giant warehouse where everything has a specific place marked by a label. Instead of remembering the exact location, you just need to know the label (key) to find your item (value). Dictionaries are unordered (as of Python 3.7, they are considered ordered, in the sense that they remember the insertion order), changeable, and do not allow duplicates of keys.

```python
my_dict = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
~~~

When to Use Dictionaries?
- When you need a logical association between key:value pairs. Ideal for fast lookups where you can access any item without knowing its index, just its key.

Recap and When to Use Each

  • Use a List when you have a collection of items in order, which you might need to alter during the execution of your program. Great for stacks, queues, or simply a collection of items that are logically grouped together.
  • Use a Tuple for fixed collections of items. They’re perfect for data that doesn’t change, like the days of the week, or when you want to pass a collection of items around your program without worrying about it being modified.
  • Use a Dictionary for when you need a map of unique keys to values. This is useful for implementing relationships, looking up values, or managing data in a way where you want to identify each element by a unique key.

Each of these data structures serves its purpose based on what you’re trying to achieve in terms of data organization, speed, and functionality in your Python adventure.

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

Explain the concept of object-oriented programming in Python and its core principles (encapsulation, inheritance, and polymorphism).

A

Object-Oriented Programming (OOP) is a programming paradigm that uses “objects” to design applications and computer programs. It utilizes several techniques from previously established paradigms, including modularity, polymorphism, and encapsulation. Python, being an object-oriented programming language, naturally supports the OOP paradigm with classes and objects.

Core Concepts of OOP in Python:

  1. Encapsulation
    Encapsulation is like packing a package for shipment. You put items (data) and the methods to handle these items into a single unit called a class. This mechanism keeps the data safe from outside interference and misuse. In Python, you create a class to encapsulate data and functions. You can restrict access to methods and variables from outside interference by making them private using the underscore prefix, such as _privateVar or \_\_veryPrivateVar.

```python
class Car:
def __init__(self, model, year):
self.model = model # public
self.__year = year # private

def get_car_year(self):
    return self.\_\_year ~~~
  1. Inheritance
    Inheritance is like a child inheriting traits from their parents. It allows one class (the child class or subclass) to inherit the attributes and methods of another class (the parent class or superclass). This promotes code reuse and a hierarchical organization of classes. In Python, inheritance is achieved by passing the parent class as a parameter to the definition of the child class.

```python
class Vehicle: # Parent class
def general_usage(self):
print(“General use: transportation”)

class Car(Vehicle): # Child class
def specific_usage(self):
print(“Specific use: Road trip”)

car = Car()
car.general_usage() # Inherited method
car.specific_usage()
~~~

  1. Polymorphism
    Polymorphism means “many shapes” in Greek. It refers to the way in which different object classes can share the same method name, but those methods can act differently based on which object calls them. In simpler terms, it allows the same interface for different underlying forms (data types). In Python, polymorphism is often achieved through method overriding (where a method in a subclass has the same name as a method in the parent class but does something different) or duck typing.

```python
class Dog:
def speak(self):
return “Woof!”

class Cat:
def speak(self):
return “Meow!”

Polymorphism in action
for animal in [Dog(), Cat()]:
print(animal.speak())
~~~

Summary
Object-Oriented Programming in Python organizes code around the concept of objects. These objects are instances of classes designed with the core principles of encapsulation (bundling data and methods), inheritance (hierarchy and reuse), and polymorphism (one interface, many implementations). These principles help manage complexity in large applications, enhance code reusability, and make software easier to maintain and extend.

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

Explain the concept of modules and packages in Python and how they are used to organize code.

A

Modules and packages in Python are fundamental concepts for organizing and structuring your code to make it more manageable, reusable, and maintainable. Think of them as a way to compartmentalize and categorize your code into logical groups.

Modules: The Building Blocks

A module is essentially a single Python file that contains a set of functions, classes, variables, and runnable code. You can think of a module as a toolbox where each tool serves a specific purpose. For example, a module might contain a collection of functions for performing mathematical operations, handling dates and times, or interacting with web servers.

Modules serve multiple purposes:
- Code Reusability: Once you’ve written code in a module, you can use it in other Python scripts and applications by importing it.
- Namespace Separation: Modules help avoid conflicts between identifiers (names of variables, functions, classes, etc.) by segregating namespaces.

To use a module in your Python program, you use the import statement. For example, to use the math module, you would do the following:

```python
import math
print(math.sqrt(16)) # Outputs: 4.0
~~~

Packages: Collections of Modules

A package is a way of organizing related modules into a single directory hierarchy. In essence, it’s a directory that contains a special file named \_\_init\_\_.py (which can be empty) and one or more module files and sub-packages. You can think of a package as a folder on your computer that organizes related files.

Packages allow for a hierarchical structuring of the module namespace using dot notation. For instance, a package named my_package could contain a module called my_module. To use a function my_function from this module, you would import it like this:

```python
from my_package.my_module import my_function
~~~

This hierarchical structure makes it easier to organize larger projects by grouping related modules together, improving code readability and maintainability.

Practical Uses and Benefits

  • Organization: Packages and modules help organize code in a logical and manageable way. For large projects, this organization is crucial for understanding and maintaining the codebase.
  • Namespace Management: By dividing a large codebase into smaller modules and packages, you can avoid conflicts in naming variables, functions, and classes.
  • Scalability: With modules and packages, you can easily scale your project by adding new modules and packages without affecting existing functionality.
  • Collaboration: When working on a project with a team, modules and packages allow work to be divided among team members without causing merge conflicts in the codebase.

In summary, modules and packages are essential tools in Python for structuring and organizing your code. They allow you to break down complex systems into manageable parts, making your code easier to write, understand, and maintain.

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

Explain joins in python

A

(modifier).join(list)

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

Explain a split in python

A

(string).split(on whatever)

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

How do you remove special characters from a string?

A

re.sub(r’[^a-zA-Z0-9\s]’, ‘’, s) Format is re.sub(regexpression,’‘,string)

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

What must you do to perform % // etc on a list?

A

np.array

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

With a dataframe how would you groupby a column and then take the average price of that group?

A

df.groupby(‘groupbycolumn’)[‘colinterest’].mean()

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

How would you sort a groupby

A

AVG_PROCE = df.groupby(groupbycolumn)[colinterest].mean().sort_values(ascending=False)

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

Explain Depth-First Search (DFS)

A

You’re in a maze and you explore one path as far as possible before trying another.

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

Write an example of DFS

A

def DFS(graph, start, visited=None):
# If not visited initalize set
if visited is None:
visited = set()
# If it’s not add to set
visited.add(start)
print(start) # Here’s where we’re looking now

for next in graph[start] - visited:
    DFS(graph, next, visited)
return visited
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Explain Breadth-First Search (BFS)

A

You’re in a maze and you explore all paths that branch off from a starting point before moving deeper in a maze.

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

Write example code of BFS

A

from collections import deque

def BFS(graph, start):
visited, queue = set(), deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex) # Here’s where we’re looking now
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)

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

What is the command for sed text sub in a file?

A

sed ‘s/old/new/’ file Note that this command will only replace the first occurrence on each line. To replace all occurrences on a line, you add the g flag at the end of the command, like so:

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

What is the command for sed text sub in a file for all occurences!

A

The g flag! sed ‘s/old/new/g’ file

17
Q

How do you actually modify the text occurrence of the file in place?

A

sed -i ‘s/Hello/Hi/g’ filepath

18
Q

How do you delete a pattern from a file with sed

A

sed -i ‘/pattern/d’ file

19
Q

How could you do the phone number sequence thang

A

from itertools import product
(‘’).join(k) for k in product(*[var_list[n] for n in num_string])

20
Q

Donts for flask

A

Don’t put the url in the arg and jsonify the data instead:

e.g. return jsonify(daily_mean.to_dict(orient=’records’))

21
Q

linux : pwd

A

prints the current working directory

22
Q

rmdir

A

removes the directory

23
Q

grep

A

Searches for patterns within files:
grep <search_term> file.txt</search_term>

24
Q

man

A

man ls -> displays the manual for ls command
just displays the manual for the command

25
Q
A