0% found this document useful (0 votes)
513 views

Kenny-230723-Python Super Cheat Sheet

The document summarizes key Python keywords and their uses. It covers boolean values and operators, control flow keywords like if/else and for/while loops, data types including integers, floats, strings, and their basic operations. Functions are defined using def and return values. Classes are defined using class to create user-defined data types.

Uploaded by

vanjchao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
513 views

Kenny-230723-Python Super Cheat Sheet

The document summarizes key Python keywords and their uses. It covers boolean values and operators, control flow keywords like if/else and for/while loops, data types including integers, floats, strings, and their basic operations. Functions are defined using def and return values. Classes are defined using class to create user-defined data types.

Uploaded by

vanjchao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Python Cheat Sheet: Keywords 

“​A puzzle a day to learn, code, and play​” → Visit ​finxter.com 

Keyword  Description  Code example 

False​, ​True  Data values from the data type Boolean  False​ == (​1 ​> ​2​), ​True​ == (​2 ​> ​1​)

and​, ​or​, ​not  Logical operators:  x, y = ​True​, ​False


(x ​and​ y)​ → both x and y must be True  (x ​or​ y) == ​True​ ​# True
(x ​or​ y)​ → either x or y must be True  (x ​and​ y) == ​False​ ​ True
#
(​not​ x)​ → x must be false  (​not​ y) == ​True​ ​ True
#

break  Ends loop prematurely  while​(​True​):


​break​ ​# no infinite loop
print(​"hello world"​)

continue  Finishes current loop iteration  while​(​True​):


​continue
print(​"43"​) ​# dead code

class Defines a new class → a real-world concept   class​ ​Beer​:


(object oriented programming)  ​def​ ​__init__​(self)​:
  self.content = ​1.0
def  Defines a new function or class method. For latter,  ​def​ ​drink​(self)​:
first parameter (“self”) points to the class object.  self.content = ​0.0
When calling class method, first parameter is implicit. 
becks = Beer() ​# constructor - create class
becks.drink() ​# beer empty: b.content == 0

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"​)

for​, ​while  # For loop declaration # While loop - same semantics


for​ i ​in​ [​0​,​1​,​2​]: j = ​0
print(i)  while​ j < ​3​:
print(j)
j = j + ​1

in  Checks whether element is in sequence  42​ ​in​ [​2​, ​39​, ​42​] ​# True

is  Checks whether both elements point to the same  y = x = 3


object  x​ ​is​ ​y​ ​# True
[​3​] ​is​ [​3​] ​# False

None  Empty value constant  ​ ​()​:


def​ f
x = ​2
f() ​is​ ​None​ ​# True

lambda  Function with no name (anonymous function)  (lambda​ x: x + ​3)(3)​ ​# returns 6

return  Terminates execution of the function and passes the  def​ ​incrementor​(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
True​ ​or F​ alse​.  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 

Integer,  An integer is a positive or negative number  ## 3. Arithmetic Operations


Float  without floating point (e.g. ​3​). A float is a  x, y = ​3​, ​2
positive or negative number with floating point  print(x + y) ​# = 5
precision (e.g.​ ​3.14159265359​).  print(x - y) ​# = 1
  print(x * y) ​# = 6
The ‘​//​’ operator performs integer division.  print(x / y) ​# = 1.5
The result is an integer value that is rounded  print(x // y) ​# = 1
toward the smaller integer number   print(x % y) ​# = 1s
(e.g. 3​ ​ // ​2​ == ​1​).  print(-x) ​# = -3
  print(abs(-x)) ​# = 3
print(int(​3.9​)) ​# = 3
print(float(​3​)) ​# = 3.0
print(x ** y) ​# = 9

String  Python Strings are sequences of characters.   ## 4. Indexing and Slicing


  s = ​"The youngest pope was 11 years old"
The four main ways to create strings are the  print(s[​0​]) ​# 'T'
following.  print(s[​1​:​3​]) ​# 'he'
  print(s[​-3​:​-1​]) ​# 'ol'
1. Single quotes  print(s[​-3​:]) ​# 'old'
'Yes' x = s.split() ​# creates string array of words
2. Double quotes  print(x[​-3​] + ​" "​ + x[​-1​] + ​" "​ + x[​2​] + ​"s"​)
"Yes"
# '11 old popes'
3. Triple quotes (multi-line) 
"""Yes
## 5. Most Important String Methods
We Can"""
y = ​" This is lazy\t\n "
4. String method 
print(y.strip()) ​# Remove Whitespace: 'This is lazy'
str(​5​) == ​'5'​ ​# True 
print(​"DrDre"​.lower()) ​# Lowercase: 'drdre'
5. Concatenation 
print(​"attention"​.upper()) ​# Uppercase: 'ATTENTION'
"Ma"​ + ​"hatma"​ ​# 'Mahatma' 
print(​"smartphone"​.startswith(​"smart"​)) ​# True
  print(​"smartphone"​.endswith(​"phone"​)) ​# True
print(​"another"​.find(​"other"​)) ​# Match index: 2
These are whitespace characters in strings. 
print(​"cheat"​.replace(​"ch"​, ​"m"​)) ​# 'meat'
● Newline \​ n
print(​','​.join([​"F"​, ​"B"​, ​"I"​])) ​# 'F,B,I'
● Space ​ s
\
print(len(​"Rumpelstiltskin"​)) ​# String length: 15
● Tab ​ t
\ print(​"ear"​ ​in​ ​"earth"​) ​# Contains: True
Python Cheat Sheet: Classes 
“​A puzzle a day to learn, code, and play​” → Visit ​finxter.com 
  Description  Example 

Classes  A class encapsulates data and functionality: data as  class​ ​Dog​:
attributes, and functionality as methods. It is a blueprint  """ Blueprint of a dog """
for creating concrete instances in memory.  
# class variable shared by all instances
species = [​"canis lupus"​]

def​ ​__init__​(self, name, color)​:


self.name = name
self.state = ​"sleeping"
self.color = color

def​ ​command​(self, x)​:


if​ x == self.name:
self.bark(​2​)
elif​ x == ​"sit"​:
Instance  You are an instance of the class human. An instance is a  self.state = " ​ sit"
concrete implementation of a class: all attributes of an  else​:
instance have a fixed value. Your hair is blond, brown, or  self.state = " ​ wag tail"
black--but never unspecified. 
  def​ ​bark​(self, freq)​:
Each instance has its own attributes independent of  for​ i ​in​ range(freq):
other instances. Yet, class variables are different. These  print(​"["​ + self.name
are data values associated with the class, not the  + ​"]: Woof!"​)
instances. Hence, all instance share the same class 
variable ​species ​in the example. 
​ black"​)
bello = Dog(​"bello"​, "
Self  The first argument when defining any method is always  alice = Dog(​"alice"​, "​ white"​)
the ​self ​argument. This argument specifies the 
​ black
print(bello.color) #
instance on which you call the method. 
  print(alice.color) #​ white
self ​gives the Python interpreter the information about 
the concrete instance. To ​define ​a method, you use s ​ elf bello.bark(​1​) ​# [bello]: Woof!
​ n instance 
to modify the instance attributes. But to ​call a
method, you do not need to specify ​self​.  alice.command(​"sit"​)
print(​"[alice]: "​ + alice.state)
Creation  You can create classes “on the fly” and use them as  # [alice]: sit
logical units to store complex data types. 
  bello.command(​"no"​)
class​ ​Employee()​: print(​"[bello]: "​ + bello.state)
pass # [bello]: wag tail
employee = Employee()
employee.salary = ​122000 alice.command(​"alice"​)
employee.firstname = ​"alice" # [alice]: Woof!
employee.lastname = ​"wonderland" # [alice]: Woof!

print(employee.firstname + ​" " bello.species += [​"wulf"​]


+ employee.lastname + ​" " print(len(bello.species)
+ str(employee.salary) + ​"$"​) == len(alice.species)) ​# True (!)
# alice wonderland 122000$ 
Python Cheat Sheet: Functions and Tricks 
“​A puzzle a day to learn, code, and play​” → Visit ​finxter.com 
    Description  Example  Result 

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)

help(func)  Returns documentation of ​func  help(str.upper()) '... to uppercase.'

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 ...'

Swapping numbers  Swapping variables is a breeze in Python.  a, b = ​'Jane'​, ​'Alice' a = ​'Alice'


No offense, Java!  a, b = b, a b = '​ Jane'

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 

Question Code Question Code

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 

Find duplicate def​ ​find_duplicates​(elements): Compute def​ i ​ ntersect​(lst1, lst2):


number in duplicates, seen = set(), set() the res, lst2_copy = [], lst2[:]
integer list ​for​ element ​in​ elements: intersection ​for​ el ​in​ lst1:
​if​ element ​in​ seen: of two lists ​if​ el ​in​ lst2_copy:
duplicates.add(element) res.append(el)
seen.add(element) lst2_copy.remove(el)
​return​ list(duplicates)  ​return​ res

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 

Remove all lst = list(range(​10​)) + list(range(​10​)) Reverse def​ ​reverse​(string):


duplicates from lst = list(set(lst)) string using ​if​ len(string)<=​1​: r
​ eturn​ string
list print(lst) recursion ​return​ reverse(string[​1​:])+string[​0​]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  print(reverse(​"hello"​)) ​# olleh

Find pairs of def​ ​find_pairs​(l, x): Compute a, b = ​0​, ​1


integers in list pairs = [] the first n n = ​10
so that their ​for​ (i, el_1) ​in​ enumerate(l): Fibonacci for​ i ​in​ range(n):
sum is equal to ​for​ (j, el_2) ​in​ enumerate(l[i+​1​:]): numbers print(b)
integer x ​if​ el_1 + el_2 == x: a, b = b, a+b
pairs.append((el_1, el_2)) # 1, 1, 2, 3, 5, 8, ...
​return​ pairs 

Check if a def​ ​is_palindrome​(phrase): Sort list with def​ ​qsort​(L):


string is a ​return​ phrase == phrase[::​-1​] Quicksort ​if​ L == []: ​return​ []
palindrome print(is_palindrome(​"anna"​)) ​# True algorithm ​return​ qsort([x ​for​ x ​in​ L[​1​:] ​if​ x< L[​0​]]) + L[​0​:1
​ ​] +
qsort([x ​for​ x ​in​ L[​1​:] ​if​ x>=L[​0​]])
lst = [​44​, ​33​, 2​ 2​, 5
​ ​, ​77​, ​55​, ​999​]
print(qsort(lst))
# [5, 22, 33, 44, 55, 77, 999] 

Use list as # as a list ... Find all def​ ​get_permutations​(w):


stack, array, l = [​3​, ​4​] permutation ​if​ len(w)<=​1​:
and queue l += [​5​, ​6​] ​# l = [3, 4, 5, 6] s of string ​return​ set(w)
smaller = get_permutations(w[​1: ​ ])
# ... as a stack ... perms = set()
l.append(​10​) ​# l = [4, 5, 6, 10] ​for​ x ​in​ smaller:
l.pop() ​# l = [4, 5, 6] ​for​ pos ​in​ range(​0,
​ len(x)+​1​):
perm = x[:pos] + w[​0​] + x[pos:]
# ... and as a queue perms.add(perm)
l.insert(​0​, ​5​) ​# l = [5, 4, 5, 6] ​return​ perms
l.pop() ​# l = [5, 4, 5]  print(get_permutations(​"nan"​))
# {'nna', 'ann', 'nan'}
Python Cheat Sheet: NumPy 
“​A puzzle a day to learn, code, and play​” → Visit ​finxter.com 
Name  Description  Example 

a.shape  The shape attribute of NumPy array a keeps a tuple of  a = np.array([[​1​,​2​],[​1​,​1​],[​0​,​0​]])
integers. Each integer describes the number of elements of  print(np.shape(a)) ​# (3, 2) 
the axis. 

a.ndim  The ndim attribute is equal to the length of the shape tuple.  print(np.ndim(a)) ​# 2

*  The asterisk (star) operator performs the Hadamard product,  a = np.array([[​2​, 0


​ ​], [​0​, ​2​]])
i.e., multiplies two matrices with equal shape element-wise.  b = np.array([[​1​, 1​ ​], [​1​, ​1​]])
print(a*b) ​# [[2 0] [0 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.var(a)  Calculates the variance of a numpy array.  a = np.array([​2​, ​6​])


print(np.var(a)) ​# 4.0

np.std(a)  Calculates the standard deviation of a numpy array  print(np.std(a)) ​# 2.0

np.diff(a)  Calculates the difference between subsequent values in  fibs = np.array([​0​, 1
​ ​, ​1​, ​2​, ​3​, ​5​])
NumPy array a  print(np.diff(fibs, n=​1​))
# [1 0 1 1 2]

np.cumsum(a)  Calculates the cumulative sum of the elements in NumPy  print(np.cumsum(np.arange(​5​)))


array a.  # [ 0 1 3 6 10]

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.max(a)  Returns the maximal value of NumPy array a.  a = np.array([​10​,​3​,​7​,​1​,​0​])


print(np.max(a)) ​# 10

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]
Bitcoin
A Peer-to-Peer Electronic Cash System
Abstract. A purely peer-to-peer version of electronic cash would allow online payments to be sent directly from one party to another without going through
a financial institution. Digital signatures provide part of the solution, but the main benefits are lost if a trusted third party is still required to prevent double-
spending. We propose a solution to the double-spending problem using a peer-to-peer network. The network timestamps transactions by hashing them into
an ongoing chain of hash-based proof-of-work, forming a record that cannot be changed without redoing the proof-of-work. The longest chain not only
serves as proof of the sequence of events witnessed, but proof that it came from the largest pool of CPU power. As long as a majority of CPU power is
controlled by nodes that are not cooperating to attack the network, they'll generate the longest chain and outpace attackers. The network itself requires
minimal structure. Messages are broadcast on a best effort basis, and nodes can leave and rejoin the network at will, accepting the longest proof-of-work
chain as proof of what happened while they were gone.

1. Introduction p = probability an honest node finds the next block


8. Simplified Payment Verification q = probability the attacker finds the next block
Commerce on the Internet has come to rely almost exclusively It is possible to verify payments without running a full qz = probability the attacker will ever catch up from z blocks behind
on financial institutions serving as trusted third parties to network node. A user only needs to keep a copy of the block
process electronic payments. While the system works well headers of the longest proof-of-work chain, which he can get
enough for most transactions, it still suffers from the inherent The proof-of-work also solves the problem of determining
by querying network nodes until he's convinced he has the
weaknesses of the trust based model. Completely non- representation in majority decision making. If the majority
longest chain, and obtain the Merkle branch linking the Given our assumption that p > q, the probability drops
reversible transactions are not really possible, since financial were based on one-IP-address-one-vote, it could be
transaction to the block it's timestamped in. He can't check exponentially as the number of blocks the attacker has to
institutions cannot avoid mediating disputes. The cost of subverted by anyone able to allocate many IPs. Proof-of-work
the transaction for himself, but by linking it to a place in the catch up with increases. With the odds against him, if he
mediation increases transaction costs, limiting the minimum is essentially one-CPU-one-vote. The majority decision is
chain, he can see that a network node has accepted it, and doesn't make a lucky lunge forward early on, his chances
practical transaction size and cutting off the possibility for represented by the longest chain, which has the greatest
blocks added after it further confirm the network has become vanishingly small as he falls further behind.
small casual transactions, and there is a broader cost in the proof-of-work effort invested in it. If a majority of CPU power
accepted it. We now consider how long the recipient of a new
loss of ability to make non-reversible payments for non- is controlled by honest nodes, the honest chain will grow the
transaction needs to wait before being sufficiently certain the
reversible services. With the possibility of reversal, the need fastest and outpace any competing chains. To modify a past
sender can't change the transaction. We assume the sender is
for trust spreads. Merchants must be wary of their customers, block, an attacker would have to redo the proof-of-work of
an attacker who wants to make the recipient believe he paid
hassling them for more information than they would the block and all blocks after it and then catch up with and
him for a while, then switch it to pay back to himself after
otherwise need. A certain percentage of fraud is accepted as surpass the work of the honest nodes. We will show later that
some time has passed. The receiver will be alerted when that
unavoidable. These costs and payment uncertainties can be the probability of a slower attacker catching up diminishes
happens, but the sender hopes it will be too late.
avoided in person by using physical currency, but no exponentially as subsequent blocks are added.
The receiver generates a new key pair and gives the public
mechanism exists to make payments over a communications To compensate for increasing hardware speed and varying
key to the sender shortly before signing. This prevents the
channel without a trusted party. interest in running nodes over time, the proof-of-work
sender from preparing a chain of blocks ahead of time by
What is needed is an electronic payment system based on difficulty is determined by a moving average targeting an
working on it continuously until he is lucky enough to get far
cryptographic proof instead of trust, allowing any two willing average number of blocks per hour. If they're generated too
As such, the verification is reliable as long as honest nodes enough ahead, then executing the transaction at that
parties to transact directly with each other without the need fast, the difficulty increases.
control the network, but is more vulnerable if the network is moment. Once the transaction is sent, the dishonest sender
for a trusted third party. Transactions that are overpowered by an attacker. While network nodes can verify starts working in secret on a parallel chain containing an
computationally impractical to reverse would protect sellers 5. Network transactions for themselves, the simplified method can be alternate version of his transaction.
from fraud, and routine escrow mechanisms could easily be The steps to run the network are as follows: fooled by an attacker's fabricated transactions for as long as The recipient waits until the transaction has been added to
implemented to protect buyers. In this paper, we propose a 1) New transactions are broadcast to all nodes. the attacker can continue to overpower the network. One a block and z blocks have been linked after it. He doesn't
solution to the double-spending problem using a peer-to-peer 2) Each node collects new transactions into a block. strategy to protect against this would be to accept alerts from know the exact amount of progress the attacker has made,
distributed timestamp server to generate computational 3) Each node works on finding a difficult proof-of-work for network nodes when they detect an invalid block, prompting but assuming the honest blocks took the average expected
proof of the chronological order of transactions. The system is its block. the user's software to download the full block and alerted time per block, the attacker's potential progress will be a
secure as long as honest nodes collectively control more CPU 4) When a node finds a proof-of-work, it broadcasts the transactions to confirm the inconsistency. Businesses that Poisson distribution with expected value:
power than any cooperating group of attacker nodes. block to all nodes. receive frequent payments will probably still want to run their
5) Nodes accept the block only if all transactions in it are own nodes for more independent security and quicker
2. Transactions valid and not already spent. verification. To get the probability the attacker could still catch up now,
We define an electronic coin as a chain of digital signatures. 6) Nodes express their acceptance of the block by working we multiply the Poisson density for each amount of progress
on creating the next block in the chain, using the hash of
Each owner transfers the coin to the next by digitally signing 9. Combining and Splitting Value he could have made by the probability he could catch up from
a hash of the previous transaction and the public key of the the accepted block as the previous hash. that point:
Although it would be possible to handle coins individually, it
next owner and adding these to the end of the coin. A payee Nodes always consider the longest chain to be the correct one
would be unwieldy to make a separate transaction for every
can verify the signatures to verify the chain of ownership. and will keep working on extending it. If two nodes broadcast
cent in a transfer. To allow value to be split and combined,
different versions of the next block simultaneously, some
transactions contain multiple inputs and outputs. Normally
nodes may receive one or the other first. In that case, they Rearranging to avoid summing the infinite tail of the
there will be either a single input from a larger previous
work on the first one they received, but save the other branch distribution...
transaction or multiple inputs combining smaller amounts,
in case it becomes longer. The tie will be broken when the
and at most two outputs: one for the payment, and one
next proof- of-work is found and one branch becomes longer;
returning the change, if any, back to the sender.
the nodes that were working on the other branch will then
switch to the longer one. Converting to C code...
New transaction broadcasts do not necessarily need to
#include <math.h>
reach all nodes. As long as they reach many nodes, they will
double AttackerSuccessProbability(double q, int z) {
get into a block before long. Block broadcasts are also tolerant double p = 1.0 - q;
double lambda = z * (q / p);
of dropped messages. If a node does not receive a block, it
It should be noted that fan-out, where a transaction double sum = 1.0;

The problem of course is the payee can't verify that one of the will request it when it receives the next block and realizes it int i, k;
depends on several transactions, and those transactions
owners did not double-spend the coin. A common solution is missed one. for (k = 0; k <= z; k++) {
depend on many more, is not a problem here. There is never double poisson = exp(-lambda);
to introduce a trusted central authority, or mint, that checks the need to extract a complete standalone copy of a for (i = 1; i <= k; i++)
every transaction for double spending. After each 6. Incentive transaction's history. poisson *= lambda / i;

transaction, the coin must be returned to the mint to issue a By convention, the first transaction in a block is a special sum -= poisson * (1 - pow(q / p, z - k));
}
new coin, and only coins issued directly from the mint are transaction that starts a new coin owned by the creator of the
10. Privacy
trusted not to be double-spent. The problem with this block. This adds an incentive for nodes to support the return sum;
The traditional banking model achieves a level of privacy by }
solution is that the fate of the entire money system depends network, and provides a way to initially distribute coins into
limiting access to information to the parties involved and the
on the company running the mint, with every transaction circulation, since there is no central authority to issue them. Running some results, we can see the probability drop off
trusted third party. The necessity to announce all transactions
having to go through them, just like a bank. The steady addition of a constant of amount of new coins is exponentially with z.
publicly precludes this method, but privacy can still be
We need a way for the payee to know that the previous analogous to gold miners expending resources to add gold to q=0.1 q=0.3
maintained by breaking the flow of information in another z=0 P=1.0000000 z=0 P=1.0000000
owners did not sign any earlier transactions. For our circulation. In our case, it is CPU time and electricity that is z=1 P=0.2045873 z=5 P=0.1773523
place: by keeping public keys anonymous. The public can see
purposes, the earliest transaction is the one that counts, so expended. z=2 P=0.0509779 z=10 P=0.0416605
that someone is sending an amount to someone else, but z=3 P=0.0131722 z=15 P=0.0101008
we don't care about later attempts to double-spend. The only The incentive can also be funded with transaction fees. If z=4 P=0.0034552 z=20 P=0.0024804
without information linking the transaction to anyone. This is z=5 P=0.0009137 z=25 P=0.0006132
way to confirm the absence of a transaction is to be aware of the output value of a transaction is less than its input value, z=6 P=0.0002428 z=30 P=0.0001522
similar to the level of information released by stock z=7 P=0.0000647 z=35 P=0.0000379
all transactions. In the mint based model, the mint was aware the difference is a transaction fee that is added to the z=8 P=0.0000173 z=40 P=0.0000095
exchanges, where the time and size of individual trades, the
of all transactions and decided which arrived first. To incentive value of the block containing the transaction. Once z=9 P=0.0000046 z=45 P=0.0000024
"tape", is made public, but without telling who the parties z=10 P=0.0000012 z=50 P=0.0000006
accomplish this without a trusted party, transactions must be a predetermined number of coins have entered circulation,
were.
publicly announced [1], and we need a system for participants the incentive can transition entirely to transaction fees and be Solving for P less than 0.1%...
to agree on a single history of the order in which they were completely inflation free. P < 0.001 q=0.30 z=24
q=0.10 z=5 q=0.35 z=41
received. The payee needs proof that at the time of each The incentive may help encourage nodes to stay honest. If a q=0.15 z=8 q=0.40 z=89
q=0.20 z=11 q=0.45 z=340
transaction, the majority of nodes agreed it was the first greedy attacker is able to assemble more CPU power than all q=0.25 z=15
received. the honest nodes, he would have to choose between using it
to defraud people by stealing back his payments, or using it to
generate new coins. He ought to find it more profitable to
12. Conclusion
3. Timestamp Server As an additional firewall, a new key pair should be used for We have proposed a system for electronic transactions
The solution we propose begins with a timestamp server. A play by the rules, such rules that favour him with more new
each transaction to keep them from being linked to a without relying on trust. We started with the usual framework
timestamp server works by taking a hash of a block of items coins than everyone else combined, than to undermine the
common owner. Some linking is still unavoidable with multi- of coins made from digital signatures, which provides strong
to be timestamped and widely publishing the hash, such as in system and the validity of his own wealth.
input transactions, which necessarily reveal that their inputs control of ownership, but is incomplete without a way to
a newspaper or Usenet post [2-5]. The timestamp proves that were owned by the same owner. The risk is that if the owner prevent double-spending. To solve this, we proposed a peer-
the data must have existed at the time, obviously, in order to 7. Reclaiming Disk Space of a key is revealed, linking could reveal other transactions to-peer network using proof-of-work to record a public
get into the hash. Each timestamp includes the previous Once the latest transaction in a coin is buried under enough that belonged to the same owner. history of transactions that quickly becomes computationally
timestamp in its hash, forming a chain, with each additional blocks, the spent transactions before it can be discarded to impractical for an attacker to change if honest nodes control a
timestamp reinforcing the ones before it. save disk space. To facilitate this without breaking the block's
11. Calculations majority of CPU power. The network is robust in its
hash, transactions are hashed in a Merkle Tree [7][2][5], with unstructured simplicity. Nodes work all at once with little
We consider the scenario of an attacker trying to generate an
only the root included in the block's hash. Old blocks can then coordination. They do not need to be identified, since
alternate chain faster than the honest chain. Even if this is
be compacted by stubbing off branches of the tree. The messages are not routed to any particular place and only
accomplished, it does not throw the system open to arbitrary
interior hashes do not need to be stored. need to be delivered on a best effort basis. Nodes can leave
changes, such as creating value out of thin air or taking
money that never belonged to the attacker. Nodes are not and rejoin the network at will, accepting the proof-of-work
4. Proof-of-Work going to accept an invalid transaction as payment, and honest chain as proof of what happened while they were gone. They
To implement a distributed timestamp server on a peer-to- nodes will never accept a block containing them. An attacker vote with their CPU power, expressing their acceptance of
peer basis, we will need to use a proof- of-work system similar can only try to change one of his own transactions to take valid blocks by working on extending them and rejecting
to Adam Back's Hashcash [6], rather than newspaper or back money he recently spent. invalid blocks by refusing to work on them. Any needed rules
Usenet posts. The proof-of-work involves scanning for a value The race between the honest chain and an attacker chain and incentives can be enforced with this consensus
that when hashed, such as with SHA-256, the hash begins can be characterized as a Binomial Random Walk. The success mechanism.
with a number of zero bits. The average work required is event is the honest chain being extended by one block, References
exponential in the number of zero bits required and can be increasing its lead by +1, and the failure event is the attacker's [1] W. Dai, "b-money," http://www.weidai.com/bmoney.txt, 1998.
verified by executing a single hash. chain being extended by one block, reducing the gap by -1. [2] Massias, et al., "Design of a secure timestamping service with minimal trust requirements,"
In 20th Symposium on Information Theory in the Benelux, May 1999.
For our timestamp network, we implement the proof-of- A block header with no transactions would be about 80 bytes.
The probability of an attacker catching up from a given [3] S. Haber, W.S. Stornetta, "How to time-stamp a digital document," In Journal of Cryptology,
work by incrementing a nonce in the block until a value is If we suppose blocks are generated every 10 minutes, 80 vol 3, no 2, pages 99-111, 1991.
deficit is analogous to a Gambler's Ruin problem. Suppose a [4] Bayer et al., "Improving the efficiency and reliability of digital time-stamping," In Sequences
found that gives the block's hash the required zero bits. Once bytes * 6 * 24 * 365 = 4.2MB per year. With computer
gambler with unlimited credit starts at a deficit and plays II: Methods in Comm., Security and Computer Science, p. 329-334, 1993.
the CPU effort has been expended to make it satisfy the systems typically selling with 2GB of RAM as of 2008, and [5] S. Haber, W.S. Stornetta, "Secure names for bit-strings," In Proceedings of the 4th ACM
potentially an infinite number of trials to try to reach Conference on Computer and Communications Security, pages 28-35, April 1997.
proof-of-work, the block cannot be changed without redoing Moore's Law predicting current growth of 1.2GB per year, [6] A. Back, "Hashcash - a denial of service counter-measure,"
breakeven. We can calculate the probability he ever reaches
the work. As later blocks are chained after it, the work to storage should not be a problem even if the block headers http://www.hashcash.org/papers/hashcash.pdf, 2002.
breakeven, or that an attacker ever catches up with the [7] R.C. Merkle, "Protocols for public key cryptosystems," In Proc. 1980 Symposium on Security
change the block would include redoing all the blocks after it. must be kept in memory. and Privacy, IEEE Computer Society, pages 122-133, April 1980.
honest chain, as follows [8]: [8] W. Feller, "An introduction to probability theory and its applications," 1957.

✅ Download High-Resolution PDF: https://blog.finxter.com/bitcoin-whitepaper-poster


Bitcoin Whitepaper Cheat Sheet
Download PDF: https://blog.finxter.com/bitcoin-whitepaper-cheat-sheet
Abstract: A purely peer-to-peer (P2P) version of electronic cash for direct payments without centralized financial institutions based on digital signatures. We
propose a solution to the double-spending problem using a P2P network using timestamped transactions in an ongoing chain of hash-based proof-of-work
(PoW). This block-chain forms a record that cannot be changed without redoing the PoW. The longest chain not only serves as proof of the sequence of events
witnessed, but proof that it came from the largest pool of CPU power. As long as a majority of CPU power is controlled by nodes not cooperating to attack the
network, they'll generate the longest chain and outpace attackers. The network requires minimal structure. Messages are broadcast on a best effort basis.
Nodes leave and join the network at will, accepting the longest PoW chain to learn about the current state of the chain.

1. Introduction Weaknesses eCommerce: (1) Relies on financial institutions 6. Incentive The first block "coinbase" transaction creates a new coin &
as trusted 3rd parties for ePayments. (2) Non-reversible native transactions sends it to block creator incentivizing miners to secure the network and
impossible leading to costly mediation. (3) Trust-based system increase circulating coins fairly w/o central authority. Plus, transaction fees will fully
scrutiny & fraud. Bitcoin fixes this: An electronic payment system based on replace coinbase mining incentive once 21M BTC have been mined. No
cryptographic proof for direct transactions without trusted third party. inflation! This incentivizes honesty among nodes. If an attacker amasses
Bitcoin uses a peer-to-peer distributed timestamp server to establish the more CPU power than all honest nodes, they can either defraud others by
chronological order of transactions. The system's security relies on honest reversing payments - or generate BTC revenue fairly which is likely to be
nodes collectively having more CPU power than any group of attacker nodes. more profitable while securing their own wealth.

2. Transactions An electronic coin is a chain of digital signatures, transferred 7. Reclaiming Disk Space Once the latest transaction in a coin is buried
through digital signing of transaction hashes & public keys of next owners. under enough blocks, discard spent transactions before it to save disk space.
Problem: Double spending of coins! Fiat System: Central authority checks To do this without breaking the block hash, use a Merkle Tree with only the
every transaction. Bitcoin: Publicly announce all transactions o no previous root included in the block's hash. Old blocks can then be compacted by
owner signed earlier transactions w/o central authority. Create a system removing branches of the tree.
ensuring global majority consensus of transaction order.

3. Timestamp Server Bitcoin's solution begins with a timestamp server that 8. Simplified Payment Verification You can verify your payments w/o a full
takes a hash of a block of items to be timestamped. We publish the hash. The network node by only keeping a copy of the block headers from the longest
timestamp proves the data must have existed at the time to get into the PoW chain obtained by querying network nodes for the chain and Merkle
hash. Each timestamp includes the previous timestamp in its hash, forming a branch that connects the transaction to its timestamped block. The
chain, with each additional timestamp reinforcing the ones before it. transaction's hash placement in the chain shows it has been accepted by a
network node, with subsequent blocks confirming this acceptance. The
4. Proof of Work (PoW) Bitcoin uses a PoW system to create a P2P verification method works if honest nodes dominate the network.
timestamp server. Collectively, miners find a value that starts with several Businesses or individuals might still prefer running their own nodes for
zero bits when hashed with SHA-256. The PoW difficulty is the number of enhanced security and faster verification.
zero bits. PoW is achieved by incrementing a nonce in the block until a value
gives the block's hash the required zero bits. The work needed is exponential
in the zero bits required: Each additional zero doubles the average work.
Altering the block would require redoing the work for all subsequent blocks.
PoW also helps in majority decision-making ("one-CPU-one-vote") so that the
heaviest chain with most CPU effort determines the majority decision. If
honest nodes control most CPU power, their chain will grow fastest. To
change a past block, an attacker must redo the PoW for that and all following
blocks to surpass the honest nodes' work. The chances of a slower attacker
catching up decrease exponentially as new blocks are added. PoW difficulty 9. Combining and Splitting Value Bitcoin allows to split and combine value
adjusts targeting average six blocks per hour, compensating for varying node by allowing transactions one or multiple in- and outputs.
hardware speeds and mining interest. If blocks are generated too quickly,
difficulty increases. 10. Privacy The traditional banking model achieves privacy by limiting
6. Network – Steps to Run (1) Broadcast new transactions to all nodes. (2) information access. Bitcoin makes all transactions public, but privacy can still
Each node gathers new transactions into a block. (3) Nodes work to find a be maintained by keeping public keys anonymous. You can see that X sends
difficult proof-of-work for their block. (4) When a node finds a proof-of-work, BTC to Y, but without being able to link (X,Y) to anyone. Tip: use a new key
it broadcasts the block. (5) Nodes only accept block if all its transactions are pair for each transaction to prevent them from being linked to common
valid and unspent. (6) Nodes show block acceptance by creating the next owner. Some linking will always be possible because multi-input transactions
block in the chain, using the accepted block's hash as the previous hash. reveal that their inputs were owned by the same owner.
Notes: Nodes consider the heaviest chain as correct & work to extend it. If
two nodes broadcast different next blocks, receiving nodes work on the first 11. Calculations Assuming p>q, probability of attacker catching up drops
but save the other in case its chain becomes heavier. The tie breaks when the exponentially as the no. blocks increases. Without early luck and with the
next PoW is found and one branch grows heavier. Nodes then switch to the odds against him, the attacker's chances become vanishingly small as he falls
heavier branch. The Bitcoin protocol tolerates dropped messages because further behind.
new transaction broadcasts don't need to reach all nodes to get into a block
quickly. Nodes request missed blocks when they receive the next block.
OpenAI Glossary Cheat Sheet
🤖 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.

Cheat Sheet Download Link: https://blog.finxter.com/openai-glossary/


Python OpenAI API Cheat Sheet
Full Blog Tutorial: https://blog.finxter.com/openapi-cheat-sheet/

Getting Started Using GPT-4


Installation (CMD, Terminal, Shell, Powershell) system = 'You only reply in emojis!'
pip install openai prompt = 'Who are you?'
# or
pip3 install openai res = openai.ChatCompletion.create(
model="gpt-4",
First Prompt messages=[
import os {"role": "system",
import openai "content": system},
{"role": "user",
# Create, copy, and paste your API key here: "content": prompt}
openai.api_key = "sk-123456789" ],
max_tokens=100,
response = openai.Completion.create( temperature=1.2)
model="text-davinci-003",
prompt="2+2=", print(res['choices'][0]['message']['content'])
temperature=0, max_tokens=10) # Answer:

JSON Output Format Generating Images Programmatically with DALL-E


{"choices": [ prompt = "An oil painting of a dancing robot
{ in the style of Monet"
"finish_reason": "stop",
"index": 0, response = openai.Image.create(
"logprobs": null, prompt=prompt,
"text": "4\n\n2+2=4" n=1,
} size="256x256")
],
"created": 1682409707, url = response["data"][0]["url"]
"id": "cmpl-797uNKSjEKE5cMlod1MeXkueIetkC", print(url)
"model": "text-davinci-003", # https://...
"object": "text_completion",
"usage": {
"completion_tokens": 8, Resolution Price
"prompt_tokens": 4, 1024x1024 $0.020 / image
"total_tokens": 12
} 512x512 $0.018 / image
}
256x256 $0.016 / image

Example Sentiment Analysis Arguments Python OpenAI API Call


prompt = """Do sentiment analysis on the ✓ model: Specifies the model version, e.g., 'gpt-4.0-turbo'.
following text. Text: 'Oh, I just adore how ✓ prompt: The input text for the model to process (e.g., question)
the sun shines so brightly at 5 a.m., waking ✓ max_tokens: Maximum tokens in the response. Roughly
me up every single morning!'""" equates to number of words.
✓ temperature: Controls output randomness (0 to 1). Higher
response = openai.Completion.create( value leads to more random replies.
engine="text-davinci-003", ✓ top_p: Nucleus sampling strategy (0 to 1). Model will only
prompt=prompt, consider subset of tokens whose probability exceeds top_p.
max_tokens=200, ✓ n: Number of independent completions to explore.
n=1, ✓ stream: Use streaming mode (True or False) to return results
stop=None, incrementally (e.g., for real-time apps).
temperature=0.5 ✓ echo: Include input prompt in output (True or False).
) ✓ stop: Stopping sequence(s) for generation (string or list of
strings).
sentiment = response.choices[0].text.strip() ✓ presence_penalty: Penalizes similar tokens in output.
print(sentiment) ✓ frequency_penalty: Penalizes frequent tokens in output.
# Sentiment: Positive

Download 11 FREE Python + OpenAI ChatGPTCheat Sheets:


https://blog.finxter.com/subscribe/
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. ###

{your input here} Text 3: {your text here}


Brand names 3:
Rewrite the text below in more engaging language.
Rule #5 – Fine-tune if Rule #4 doesn’t work
Text: """
{your input here} Fine-tuning improves model performance by training on more examples,
resulting in higher quality results, token savings, and lower latency requests.
"""
GPT-3 can intuitively generate plausible completions from few examples,
known as few-shot learning.
Rule #2 – Be specific and detailed about the desired Fine-tuning achieves better results on various tasks without requiring
context, outcome, length, format, and style. examples in the prompt, saving costs and enabling lower-latency requests.
Example Training Data
Write a short story for kids {"prompt":"<input>", "completion":"<ideal output>"}
{"prompt":"<input>", "completion":"<ideal output>"}
{"prompt":"<input>", "completion":"<ideal output>"}
Write a funny soccer story for kids that teaches the
...
kid that persistence is key for success in the style of
Rowling.
Rule #6 – Be specific. Omit needless words.
Rule #3 – Give examples of desired output format ChatGPT, write a sales page for my company selling sand
in the desert, please write only a few sentences,
nothing long and complex
Extract house pricing data from the following text.

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):

Bonus Prompt – Let ChatGPT Design the Optimal Prompt


New models are created frequently, and the performance of subsequent models can be an order of
magnitude. You are a robot for creating prompts. You need to gather information about the user’s
goals, examples of preferred output, and any other relevant contextual information.

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

Boolean The Boolean data type is ## Evaluates to True:


False, Boolean data type False == (1 > 2)
either True or False. 1<2 and 0<=1 and 3>2 and 2>=2 and 1==1
True True == (2 > 1)
Boolean operators are and 1!=0
ordered by priority:
Logical operators ## Evaluates to False:
not → and → or
and, → Both are true True and True # True bool(None or 0 or 0.0 or '' or [] or
or, → Either is true True or False # True {} or set())
not → Flips Boolean not False # True
Rule: None, 0, 0.0, empty strings, or empty container
1, 2, 3 types evaluate to False
break Ends loop prematurely while True:
break # finite loop Integer, An integer is a positive or ## Arithmetic Operations
Float negative number without x, y = 3, 2
continue Finishes current loop iteration while True: decimal point such as 3. print(x + y) # = 5
continue print(x - y) # = 1
print("42") # dead code A float is a positive or print(x * y) # = 6
negative number with print(x / y) # = 1.5
class Defines new class class Coffee: floating point precision print(x // y) # = 1
# Define your class such as 3.1415926. print(x % y) # = 1
print(-x) # = -3
def Defines a new function or class def say_hi(): Integer division rounds print(abs(-x)) # = 3
method. print('hi') toward the smaller integer print(int(3.9)) # = 3
(example: 3//2==1). print(float(3)) # = 3.0
if, Conditional execution: x = int(input("ur val:")) print(x ** y) # = 9
elif, - “if” condition == True? if x > 3: print("Big")
else - "elif" condition == True? elif x == 3: print("3") String Python Strings are ## Indexing and Slicing
- Fallback: else branch else: print("Small") sequences of characters. s = "The youngest pope was 11 years"
s[0] # 'T'
String Creation Methods: s[1:3] # 'he' Slice [::2]
for, # For loop # While loop does same
while for i in [0,1,2]: j = 0 1. Single quotes s[-3:-1] # 'ar'
print(i) while j < 3: >>> 'Yes' s[-3:] # 'ars' 1 2 3 4
print(j); j = j + 1 2. Double quotes
>>> "Yes" x = s.split() 0 1 2 3
in Sequence membership 42 in [2, 39, 42] # True 3. Triple quotes (multi-line) x[-2] + " " + x[2] + "s" # '11 popes'
>>> """Yes
is Same object memory location y = x = 3 We Can""" ## String Methods
x is y # True 4. String method y = " Hello world\t\n "
[3] is [3] # False >>> str(5) == '5' y.strip() # Remove Whitespace
True "HI".lower() # Lowercase: 'hi'
None Empty value constant print() is None # True 5. Concatenation "hi".upper() # Uppercase: 'HI'
>>> "Ma" + "hatma" "hello".startswith("he") # True
lambda Anonymous function (lambda x: x+3)(3) # 6 'Mahatma' "hello".endswith("lo") # True
"hello".find("ll") # Match at 2
return Terminates function. Optional def increment(x): Whitespace chars: "cheat".replace("ch", "m") # 'meat'
return value defines function return x + 1 Newline \n, ''.join(["F", "B", "I"]) # 'FBI'
result. increment(4) # returns 5 Space \s, len("hello world") # Length: 15
Tab \t "ear" in "earth" # True

Complex Data Structures


Type Description Example Type Description Example

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}

Subscribe to the 11x FREE Python Cheat Sheet Course:


https://blog.finxter.com/python-cheat-sheets/
Python Cheat Sheet: Complex Data Types
“A puzzle a day to learn, code, and play” → Visit finxter.com
Description Example

List A container data type that stores a l = [1, 2, 2]


sequence of elements. Unlike strings, lists print(len(l)) # 3
are mutable: modification possible.

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]

Removal Removing an element can be slower. [1, 2, 2, 4].remove(1) # [2, 2, 4]

Reversing This reverses the order of list elements. [1, 2, 3].reverse() # [3, 2, 1]

Sorting Sorts a list. The computational complexity [2, 4, 2].sort() # [2, 2, 4]


of sorting is superlinear in the no. list
elements.

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.

Stack Python lists can be used intuitively as stack = [3]


stacks via the two list operations append() stack.append(42) # [3, 42]
and pop(). stack.pop() # 42 (stack: [3])
stack.pop() # 3 (stack: [])

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}
Book:
Complexity appears in Project Lifecycle Cyclomatic Complexity Runtime Complexity
Complexity
• Project Lifecycle
“A whole, made up • Code Development
of parts—difficult to • Algorithmic Theory
analyze, understand, • Processes
or explain". • Social Networks
• Learning & Your Daily Life

→ Complexity reduces productivity and focus. It’ll consume your precious time. Keep it simple!

80/20 Principle Pareto Tips Minimum Viable


1. Figure out your success metrics.
Majority of effects come 2. Figure out your big goals in life. Product (MVP)
from the minority of causes. 3. Look for ways to achieve the same A minimum viable
things with fewer resources. product in the
4. Reflect on your own successes software sense is code
5. Reflect on your own failures that is stripped from
6. Read more books in your industry. all features to focus on
7. Spend much of your time the core functionality.
improving and tweaking existing How to MVP?
products • Formulate
8. Smile. hypothesis
9. Don't do things that reduce value • Omit needless
Maximize Success Metric: features
#lines of code written • Split test to validate
each new feature
Clean Code Principles Unix Philosophy • Focus on product-
1. You Ain't Going to Need It 1. Simple’s Better Than market fit
2. The Principle of Least Surprise Complex • Seek high-value and
3. Don't Repeat Yourself 2. Small is Beautiful (Again) low-cost features
4. Code For People Not Machines 3. Make Each Program Do One Performance Tuning 101
5. Stand on the Shoulders of Giants Thing Well Premature Optimization
1. Measure, then improve
6. Use the Right Names 4. Build a Prototype First "Programmers waste enormous 2. Focus on the slow 20%
7. Single-Responsibility Principle 5. Portability Over Efficiency amounts of time thinking about […] 3. Algorithmic optimization
8. Use Comments 6. Store Data in Flat Text Files the speed of noncritical parts of their wins
9. Avoid Unnecessary Comments 7. Use Software Leverage programs. We should forget about 4. All hail to the cache
10. Be Consistent 8. Avoid Captive User small efficiencies, say about 97 % of 5. Solve an easier problem
11. Test Interfaces the time: premature optimization is version
12. Think in Big Pictures 9. Program = Filter the root of all evil." – Donald Knuth 6. Know when to stop
13. Only Talk to Your Friends 10. Worse is Better
14. Refactor 11. Clean > Clever Code “… the source code of ultimate human performance" – Kotler
15. Don’t Overengineer 12. Design Connected Programs Flow
Flow Tips for Coders
16. Don’t Overuse Indentation 13. Make Your Code Robust
1. Always work on an explicit
17. Small is Beautiful 14. Repair What You Can — But
practical code project
18. Use Metrics Fail Early and Noisily
2. Work on fun projects that
19. Boy Scout Rule: Leave Camp 15. Write Programs to Write
fulfill your purpose
Cleaner Than You Found It Programs
3. Perform from your
strengths
Less Is More in Design How to Simplify Design? 4. Big chunks of coding time
1. Use whitespace 5. Reduce distractions:
2. Remove design elements smartphone + social
3. Remove features How to Achieve Flow? (1) clear 6. Sleep a lot, eat healthily,
4. Reduce variation of fonts, read quality books, and
font types, colors goals, (2) immediate feedback, and
exercise → garbage in,
5. Be consistent across UIs (3) balance opportunity & capacity. garbage out!

Focus 3-Step Approach of


Efficient Software Creation
You can take raw resources and 1. Plan your code
move them from a state of high 2. Apply focused effort
entropy into a state of low entropy— to make it real.
using focused effort towards the 3. Seek feedback
attainment of a greater plan.
Figure: Same effort, different result.
Subscribe to the 11x FREE Python Cheat Sheet Course:
https://blog.finxter.com/python-cheat-sheets/

You might also like