Finkster-Python Cheatsheet
Finkster-Python Cheatsheet
Finkster-Python Cheatsheet
🤖 Artificial General Intelligence (AGI): AGI refers to a hypothetical 🌌 GPT-4: GPT-4 is a more advanced version of the GPT series,
AI that can perform any intellectual task a human being can do, expected to have larger model size and enhanced capabilities
demonstrating human-like cognitive abilities across diverse domains. compared to its predecessors.
🚀 Singularity: A theoretical point in the future when AI 🏋️ Pre-training: Pre-training is the initial phase of training a deep
advancements lead to rapid, uncontrollable, and transformative learning model on a large dataset, often unsupervised
changes in society, potentially surpassing human comprehension.
🎛️ Fine-tuning: Fine-tuning is the process of adapting a pre-
🛡️ AI Safety: AI safety is the study and practice of building AI trained model for a specific task by training it on labeled data
systems that operate securely and align with human values, ensuring related to that task, refining its performance.
that they benefit humanity without causing harm.
🎯 Zero-shot learning: Zero-shot learning is a machine learning
🧭 Alignment Problem: The alignment problem is the challenge of approach where a model can make predictions or complete tasks
designing AI systems that understand and act upon human intentions, without being explicitly trained on that task's data.
values, and goals, rather than optimizing for unintended objectives.
🧪 Few-shot learning: Few-shot learning is a machine learning
🧠 OpenAI: OpenAI is an AI research organization that focuses on approach where a model can quickly adapt to new tasks by
developing artificial general intelligence (AGI) that benefits everybody. learning from a small number of labeled examples.
💡 Deep Learning: Deep learning is a subfield of machine learning 📜 Token: A token is a unit of text, such as a word or subword, that
that uses artificial neural networks to model complex patterns and serves as input to a language model.
make predictions or decisions based on input data.
🔪 Tokenizer: A tokenizer is a tool that breaks down text into
🕸️ Artificial Neural Network: An artificial neural network is a individual tokens for processing by a language model.
computational model inspired by the human brain's structure and 🖼️ Context window: The context window is the maximum number
function, consisting of interconnected nodes called neurons that of tokens that a language model can process in a single pass,
process and transmit information. determining its ability to capture context in input data.
🎓 Supervised Learning: Supervised learning is a machine learning
💡 Prompts: Prompts are input text given to a language model to
approach where a model is trained on a dataset containing input- generate a response or complete a specific task.
output pairs, learning to predict outputs based on new inputs.
🎨 Prompt Engineering: Prompt engineering is the process of
🌐 Unsupervised Learning: Unsupervised learning is a machine designing effective prompts to elicit desired responses from
learning approach where a model learns patterns and structures within language models, improving their utility and reliability.
input data without explicit output labels, often through clustering or
dimensionality reduction. 🤖 ChatGPT: ChatGPT is a conversational AI model developed by
OpenAI based on the GPT architecture, designed to generate
🎮 Reinforcement Learning from Human Feedback (RLHF): RLHF human-like responses in text-based conversations.
is a method that combines reinforcement learning with human
feedback, allowing AI models to learn from and adapt to human 📚 InstructGPT: InstructGPT is an AI model developed by
preferences and values. OpenAI, designed to follow instructions given in prompts, enabling
it to generate more task-specific and accurate responses.
💬 Natural Language Processing (NLP): NLP is a field of AI that
focuses on enabling computers to understand, interpret, and generate 🔧 OpenAI API: The OpenAI API is a service provided by OpenAI
human language. that allows developers to access and utilize their AI models, such
as ChatGPT, for various applications.
📚 Large Language Models: Large language models are AI models
trained on vast amounts of text data, capable of understanding and 🎨 DALL-E: DALL-E is an AI model developed by OpenAI that
generating human-like text. generates images from textual descriptions, combining natural
language understanding with image generation capabilities.
⚙️ Transformer: The Transformer is a deep learning architecture
designed for sequence-to-sequence tasks, known for its self-attention 🐍 LaMDA: LaMDA is Google's conversational AI model designed
mechanism that helps capture long-range dependencies in data. to engage in open-domain conversations, understanding and
generating responses for a wide range of topics.
👁️ Attention mechanism: Attention mechanisms in neural networks
enable models to weigh the importance of different input elements 🧭 Midjourney: AI program and service that generates images
relative to one another, improving their ability to capture context. from natural language descriptions, called "prompts", similar to
OpenAI's DALL-E and Stable Diffusion
🔄 Self-attention: Self-attention is a type of attention mechanism
used in transformers that allows the model to relate different positions 🌊 Stable Diffusion: A deep learning, text-to-image model
of a single sequence. released in 2022 and used to generate detailed images conditioned
on text descriptions. Also used for inpainting, outpainting, and
📖 BERT (Bidirectional Encoder Representations from generating image-to-image translations guided by a text prompt.
Transformers): BERT is a pre-trained transformer-based model
developed by Google for natural language understanding tasks, which 📈 Diffusion models: Diffusion models are a class of models that
can be fine-tuned for specific applications. represent the spread of information, influence, or other phenomena
through a network.
🚀 GPT (Generative Pre-trained Transformer): GPT is a series of AI
models developed by OpenAI, designed for natural language 🔄 Backpropagation: Backpropagation is a widely-used
processing tasks and capable of generating coherent, contextually optimization algorithm in neural networks that minimizes the error
relevant text. between predicted outputs and true outputs by adjusting the
model's weights.
🌐 GPT-3.5: GPT-3.5 is an intermediate version of the GPT series,
bridging the gap between GPT-3 and GPT-4 in terms of model size
and capabilities.
False, True Data values from the data type Boolean False == (1 > 2), True == (2 > 1)
if, elif, else Conditional program execution: program starts with x = int(input("your value: "))
“if” branch, tries the “elif” branches, and finishes with if x > 3: print("Big")
“else” branch (until one branch evaluates to True). elif x == 3: print("Medium")
else: print("Small")
in Checks whether element is in sequence 42 in [2, 39, 42] # True
return Terminates execution of the function and passes the def i ncrementor(x):
flow of execution to the caller. An optional value after return x + 1
the return keyword specifies the function result. incrementor(4) # returns 5
Python Cheat Sheet: Basic Data Types
“A puzzle a day to learn, code, and play” → Visit finxter.com
Description Example
Boolean The Boolean data type is a truth value, either ## 1. Boolean Operations
alse.
True or F x, y = True, False
print(x and not y) # True
The Boolean operators ordered by priority: print(not x and y or x) # True
not x → “if x is False, then x, else y”
x and y → “if x is False, then x, else y” ## 2. If condition evaluates to False
x or y → “if x is False, then y, else x” if None or 0 or 0.0 or '' or [] or {} or set():
# None, 0, 0.0, empty strings, or empty
These comparison operators evaluate to True: # container types are evaluated to False
1 < 2 and 0 <= 1 and 3 > 2 and 2 >=2 and
print("Dead code") # Not reached
1 == 1 and 1 != 0 # True
A map(func, iter) Executes the function on all elements of list(map(lambda x: x[0], ['red', ['r', 'g', 'b']
D the iterable 'green', 'blue']))
V
A map(func, i1, ..., Executes the function on all k elements of list(map(lambda x, y: str(x) + ' ' + ['0 apples', '2
ik) the k iterables y + 's' , [0, 2, 2], ['apple', oranges', '2
N
C 'orange', 'banana'])) bananas']
E
string.join(iter) Concatenates iterable elements ' marries '.join(list(['Alice', 'Alice marries Bob'
D separated by string 'Bob']))
F filter(func, Filters out elements in iterable for which list(filter(lambda x: True if x>17 [18]
U iterable) function returns False (or 0) else False, [1, 15, 17, 18]))
N
C string.strip() Removes leading and trailing print(" \n \t 42 \t ".strip()) 42
T whitespaces of string
I
O sorted(iter) Sorts iterable in ascending order sorted([8, 3, 2, 42, 5]) [2, 3, 5, 8, 42]
N
sorted(iter, Sorts according to the key function in sorted([8, 3, 2 , 42, 5], key=lambda [42, 2, 3, 5, 8]
S
key=key) ascending order x: 0 if x==42 e lse x)
zip(i1, i2, ...) Groups the i-th elements of iterators i1, list(zip(['Alice', 'Anna'], ['Bob', [('Alice', 'Bob'),
i2, ... together 'Jon', 'Frank'])) ('Anna', 'Jon')]
Unzip Equal to: 1) unpack the zipped list, 2) zip list(zip(*[('Alice', 'Bob'), [('Alice', 'Anna'),
the result ('Anna', 'Jon')])) ('Bob', 'Jon')]
enumerate(iter) Assigns a counter value to each element list(enumerate(['Alice', 'Bob', [(0, 'Alice'), (1,
of the iterable 'Jon'])) 'Bob'), (2, 'Jon')]
T python -m http.server Want to share files between PC and phone? Run this command in PC’s shell. <P> is any port number 0–65535. Type <
R <P> IP address of PC>:<P> in the phone’s browser. You can now browse the files in the PC directory.
I
C Read comic import antigravity Open the comic series xkcd in your web browser
K
S
Zen of Python import this '...Beautiful is better than ugly. Explicit is ...'
Unpacking arguments Use a sequence as function arguments def f(x, y, z): return x + y * z
via asterisk operator *. Use a dictionary f(*[1, 3, 4]) 13
(key, value) via double asterisk operator ** f(**{'z' : 4, 'x' : 1, 'y' : 3
}) 13
Extended Unpacking Use unpacking for multiple assignment a, *b = [1, 2, 3, 4, 5] a = 1
feature in Python b = [2, 3, 4, 5]
Merge two dictionaries Use unpacking to merge two dictionaries x={'Alice' : 18} z = {'Alice': 18,
into a single one y={'Bob' : 27, 'Ann' : 22} 'Bob': 27, 'Ann': 22}
z = {**x,**y}
Python Cheat Sheet: 14 Interview Questions
“A puzzle a day to learn, code, and play” → Visit finxter.com
Check if list l = [3, 3, 4, 5, 2, 111, 5] Get missing def g et_missing_number(lst):
contains print(111 in l) # True number in return set(range(lst[len(lst)-1])[1:
]) - set(l)
integer x [1...100] l = list(range(1,100))
l.remove(50)
print(get_missing_number(l)) # 50
Check if two def i s_anagram(s1, s2): Find max l = [4, 3, 6, 3
, 4,
888, 1,
-11, 22, 3]
strings are return set(s1) == set(s2) and min in print(max(l)) # 888
anagrams print(is_anagram("elvis", "lives")) # True unsorted list print(min(l)) # -11
a.ndim The ndim attribute is equal to the length of the shape tuple. print(np.ndim(a)) # 2
np.matmul(a,b), a@b The standard matrix multiplication operator. Equivalent to the print(np.matmul(a,b))
@ operator. # [[2 2] [2 2]]
np.arange([start, ]stop, Creates a new 1D numpy array with evenly spaced values print(np.arange(0,10,2))
[step, ]) # [0 2 4 6 8]
np.linspace(start, stop, Creates a new 1D numpy array with evenly spread elements print(np.linspace(0,10,3))
num=50) within the given interval # [ 0. 5. 10.]
np.average(a) Averages over all the values in the numpy array a = np.array([[2, 0], [0, 2]])
print(np.average(a)) # 1.0
<slice> = <val> Replace the <slice> as selected by the slicing operator with a = np.array([0, 1, 0, 0
, 0])
the value <val>. a[::2] = 2
print(a) [2 1 2 0 2]
#
np.sort(a) Creates a new NumPy array with the values from a a = np.array([10,3,7,1,0])
(ascending). print(np.sort(a))
# [ 0 1 3 7 10]
np.argsort(a) Returns the indices of a NumPy array so that the indexed a = np.array([10,3,7,1,0])
values would be sorted. print(np.argsort(a))
# [4 3 1 2 0]
np.argmax(a) Returns the index of the element with maximal value in the a = np.array([10,3,7,1,0])
NumPy array a. print(np.argmax(a)) # 0
np.nonzero(a) Returns the indices of the nonzero elements in NumPy array a = np.array([10,3,7,1,0])
a. print(np.nonzero(a)) # [0 1 2 3]
ChatGPT Prompting Cheat Sheet
How Prompt Engineering Works Rule #4 – First try without examples, then try giving
Note: Prompt engineering designs and optimizes prompts for some examples.
language models.
Extract brand names from the text below.
It's important in NLP and language generation. Prompt formats
guide the model and can be used for tasks like product Text: {your text here}
descriptions or conversational AI.
Brand names:
Reliable prompt formats exist, but exploring new formats is
encouraged.
Extract brand names from the texts below.
"{your input here}" is a placeholder for text or context
Text 1: Finxter and YouTube are tech companies. Google
Rules of Thumb and Examples is too.
Brand names 2: Finxter, YouTube, Google
Rule #1 – Instructions at beginning and ### or """ to ###
separate instructions or context
Text 2: If you like tech, you’ll love Finxter!
Brand names 2: Finxter
Rewrite the text below in more engaging language. ###
Text: """ Write a 5-sentence sales page, sell sand in the desert.
{your text containing pricing data}
""" Rule #7 – Use leading words to nudge the model
towards a pattern
Extract house pricing data from the following text.
Write a Python function that plots my net worth over 10
Desired format: """ years for different inputs on the initial investment
House 1 | $1,000,000 | 100 sqm and a given ROI
House 2 | $500,000 | 90 sqm
... (and so on) # Python function that plots net worth over 10
""" # years for different inputs on the initial
# investment and a given ROI
Text: """
{your text containing pricing data} import matplotlib
"""
def plot_net_worth(initial, roi):
The prompt should contain all the necessary information provided to you. Ask the user more
questions until you are sure you can create an optimal prompt.
Your answer should be clearly formatted and optimized for ChatGPT interactions. Be sure to start
by asking the user about the goals, the desired outcome, and any additional information you may
need.
The Ultimate Python Cheat Sheet
Keywords Basic Data Structures
Keyword Description Code Examples Type Description Code Examples
List Stores a sequence of l = [1, 2, 2] Dictionary Useful data structure for cal = {'apple' : 52, 'banana' : 89,
elements. Unlike strings, you print(len(l)) # 3 storing (key, value) pairs 'choco' : 546} # calories
can modify list objects (they're
Reading Read and write elements by print(cal['apple'] < cal['choco'])
mutable).
and specifying the key within the # True
Adding Add elements to a list with (i) [1, 2].append(4) # [1, 2, 4] writing brackets. Use the keys() cal['cappu'] = 74
elements append, (ii) insert, or (iii) list [1, 4].insert(1,9) # [1, 9, 4] elements and values() functions to print(cal['banana'] < cal['cappu'])
concatenation. [1, 2] + [4] # [1, 2, 4] access all keys and values of # False
the dictionary
print('apple' in cal.keys()) # True
Removal Slow for lists [1, 2, 2, 4].remove(1) # [2, 2, 4]
print(52 in cal.values()) # True
Reversing Reverses list order [1, 2, 3].reverse() # [3, 2, 1]
Dictionary You can access the (key, for k, v in cal.items():
Sorting Sorts list using fast Timsort [2, 4, 2].sort() # [2, 2, 4] Iteration value) pairs of a dictionary print(k) if v > 500 else ''
with the items() method. # 'choco'
Indexing Finds the first occurrence of [2, 2, 4].index(2)
an element & returns index. # index of item 2 is 0 Member- Check with the in keyword if basket = {'apple', 'eggs',
Slow worst case for whole list [2, 2, 4].index(2,1) ship set, list, or dictionary contains 'banana', 'orange'}
traversal. # index of item 2 after pos 1 is 1 operator an element. Set membership print('eggs' in basket) # True
is faster than list membership. print('mushroom' in basket) # False
Stack Use Python lists via the list stack = [3]
operations append() and pop() stack.append(42) # [3, 42] List & set List comprehension is the l = ['hi ' + x for x in ['Alice',
stack.pop() # 42 (stack: [3]) comprehe concise Python way to create 'Bob', 'Pete']]
stack.pop() # 3 (stack: []) nsion lists. Use brackets plus an # ['Hi Alice', 'Hi Bob', 'Hi Pete']
expression, followed by a for
Set An unordered collection of basket = {'apple', 'eggs', clause. Close with zero or l2 = [x * y for x in range(3) for y
unique elements (at-most- 'banana', 'orange'} more for or if clauses. in range(3) if x>y] # [0, 0, 2]
once) → fast membership O(1) same = set(['apple', 'eggs', Set comprehension works
squares = { x**2 for x in [0,2,4]
'banana', 'orange']) similar to list comprehension.
if x < 4 } # {0, 4}
Adding Add elements to a list with (i) append, (ii) [1, 2, 2].append(4) # [1, 2, 2, 4]
elements insert, or (iii) list concatenation. [1, 2, 4].insert(2,2) # [1, 2, 2, 4]
The append operation is very fast. [1, 2, 2] + [4] # [1, 2, 2, 4]
Reversing This reverses the order of list elements. [1, 2, 3].reverse() # [3, 2, 1]
Indexing Finds the first occurrence of an element in [2, 2, 4].index(2) # index of element 2 is "0"
the list & returns its index. Can be slow as [2, 2, 4].index(2,1) # index of el. 2 after pos 1 is "1"
the whole list is traversed.
Set A set is an unordered collection of unique basket = {'apple', 'eggs', 'banana', 'orange'}
elements (“at-most-once”). same = set(['apple', 'eggs', 'banana', 'orange'])
Dictionary The dictionary is a useful data structure for calories = {'apple' : 52, 'banana' : 89, 'choco' : 546}
storing (key, value) pairs.
Reading and Read and write elements by specifying the print(calories['apple'] < calories['choco']) # True
writing key within the brackets. Use the keys() and calories['cappu'] = 74
elements values() functions to access all keys and print(calories['banana'] < calories['cappu']) # False
values of the dictionary. print('apple' in calories.keys()) # True
print(52 in calories.values()) # True
Dictionary You can access the (key, value) pairs of a for k, v in calories.items():
Looping dictionary with the items() method. print(k) if v > 500 else None # 'choco'
Membership Check with the ‘in’ keyword whether the basket = {'apple', 'eggs', 'banana', 'orange'}
operator set, list, or dictionary contains an element. print('eggs' in basket) # True
Set containment is faster than list print('mushroom' in basket) # False
containment.
List and Set List comprehension is the concise Python # List comprehension
Comprehens way to create lists. Use brackets plus an l = [('Hi ' + x) for x in ['Alice', 'Bob', 'Pete']]
ion expression, followed by a for clause. Close print(l) # ['Hi Alice', 'Hi Bob', 'Hi Pete']
with zero or more for or if clauses. l2 = [x * y for x in range(3) for y in range(3) if x>y]
print(l2) # [0, 0, 2]
Set comprehension is similar to list # Set comprehension
comprehension. squares = { x**2 for x in [0,2,4] if x < 4 } # {0, 4}