0% found this document useful (0 votes)
7 views2 pages

Cheat Sheet127 2

Yea

Uploaded by

bano.nikolas.227
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)
7 views2 pages

Cheat Sheet127 2

Yea

Uploaded by

bano.nikolas.227
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/ 2

Python: INDEX/SLICING EXAMPLE:

Strings: • str = 'yellow'


• Indexing/Slicing: • str[1] # => 'e'
• str[-1] # => 'w'
Functions:
• str[4:6] # => 'ow' Power of 2 up to 6: 256, 128, 64,32,16,8,4,2,0 Dec to Binary ⇒ if dec is 75 we pick 64 as it is
• int() - Converts numbers to integer form lowest that is closer to 75 and subtract until 0 while
• float() - Converts numbers to float form • str[:4] # => 'yell' doing the same. The number used will turn 1
• ord() - Converts unicode character to integer (see ASCII table) • str[-3:] # => 'low' unused 0 starting from the highest number picked,
• chr() - Converts integer to unicode character (see ASCII table) Conversions: here 64.
• range(start, stop, step) - returns a sequence of numbers, starts at 0 by default, increments by 1 (by default), and stops right before a specified number. • Hex to Dec ⇒ Example: (25)16
= (2 × 161) + (5 × 160)
——————
= (2 × 16) + (5 × 1)
Methods:
= 32 + 5
• .split() - Splits a string into a list where each word is a list item
• str.split[index](separator, maxsplit) = 37
• [ i: ] - indices beginning at i till end of string
• [ :i ] - indices beginning at start of string till i • Binary to Dec ⇒ Example: (1011)2
• [ i:j ] - indices beginning at i ending at j = (1 × 23) + (0 × 22) + (1× 21) + (1 × 20)
• [ - i ] - indices starting from END of string = (1 × 8) + (0 × 4) + (1× 2) + (1 × 1)
=8+0+2+1
.split() example: Colors: = 11
x = "p,o,t,a,t,o"
newList = x[2:7].split(",") • Hex = # RR GG BB
print(newList) • Black = # 00 00 00
Output: ['o', 't', 'a'] • White = # FF FF FF UNIX/Linux:
• Gray = # 80 80 80 • pwd — prints path to current directory
• .count() - returns the number of times something occurs • Purple = (1.0, 0, 1.0) • ls — prints contents of current directory [ $ls z* — prints all files that start with z ] [ $ls *zz* — prints all files that contains the
• Cyan = (0,1,1) letters “zz” ] [ $ls -l — prints contents in “long” form ]
• .len() - returns the number of the length of the string or list
• pipes ( | ) — takes the data flowing out of a command and directs it into the next command
• .upper() - converts all characters to uppercase characters
• Decimal = (1.0, 1.0, 1.0) where 1.0 is the max value • grep — filter for characters [ $ls -l | grep "Oct" — prints files modified in Oct ]
• .lower() - converts all characters to lowercase characters • wc — counts the number of lines output [ ls -l | grep "Oct" | wc -l — prints out a number (integer) ]
• 8-bit = (255, 255, 255) where 255 is the max value
———————————— • mv — move file [ $mv [file] [new name of file] — moves and renames file ]
Python Libraries: • mkdir — make directory [ $mkdir Potato — Makes directory named “Potato” ]
• cd — change directory [ $cd .. OR $cd ../ — goes up one directory ] [ $cd ~ — returns to home directory]
Turtles | “ import turtle ”:

inner loop if the element is smaller than the threshold,


grid, looping for rows in outer loop and columns in
(e) Use a nested loop to consider every element in
• git clone - can access programs by cloning the website. Git fetch- fetch the changes in an existing directory.
• turtle = turtle.Turtle() - creates a turtle
• turtle.color( ) - changes pen color | turtle.colormode ( ) — set out of 1.0 or 255
(b) Ask the user for a number as a threshold.

• turtle.shape(“arrow”) - changes pen shape. Shapes: arrow, turtle, circle, etc


• turtle.stamp( ) - stamps turtle at current position Arithmetic and Logic:
• turtle.left/right ( ) - changes angle of pen in degrees • % — Modulo operator: returns remainder of x/y — Example: 5/2 = 2 R 1 (this will return 1 as it is the remainder)
• turtle.exitonclick( ) - exits turtle graphics window when clicked • // — Floor division: rounds the result down to the nearest whole number
(a) Ask the user for text file name

• turtle.pensize( ) - changes pen size


Pseudocode example

• turtle.penup/down( ) - lifts pen up/down (up = draw, down = don’t draw) • == — Equality operator: if both values are equal, returns true. If unequal, returns false
• turtle always starts as (at angle): ➤ • != or <> — Equality operator: if both values are unequal, returns true. If equal, returns false
• += — Addition assignment: x+=3 is the same as x=x+3
add the element to total.

——————
(d) Set total to be zero.
(c) Load data into grid.

Random | “ import random ”: • -= — Subtraction assignment: x-=7 is the same as x=x-7


• random.randrange(start, stop, step) - returns randomly element from range
(f) Report total.

• random.random() - returns a random float value between 0 and 1


More Operators:
• random.randint() - returns an integer number selected element from the specified range
• > — greater than
——————
• >= — greater than or equal to
Folium | “ import folium ”: • < — less than
• map = folium.Map (location=[40.768731, -73.964915]) • <= — less than or equal to
• x = df.groupby(column).get_group(row in column)
Uses nested loop, index
• map.save(outfile)
• for index,row in df.iterrows(): slicing, and if/else statements Python Specific:
lat = row[ "Latitude" ] • ** — Exponentiation assignment: in Python, x^3 is written as x**3
lon = row[ "Longitude" ]
name = row[ "Name" ] C++ Specific (probably won’t be on the exam tbh):
newMarker = folium.Marker([lat, lon],popup=name) Decimal to Hex: • pow() — Exponentiation assignment: in C++, x^3 is written as pow(x, 3)
newMarker.add_to(map)
Divide the decimal by 16 until you • && — logical AND
—————— • || — logical OR
reach 0
Matplotlib | “import matplotlib.pyplot as plt”: Example:
• plt.show() - shows image LOGIC:
3284→ 3284/16 = 205 R 4
• plt.imread() - loads image as array into pyplot
204/16 = 12 R 13 Loops:
• plt.imsave() - saves array as image
• for [variable] in range(num): — loops num times
—————— 12/16 = 0 R 12
• for [variable] in range(start, stop, step): — loops as many times as indicated by the range
Pandas | “ import pandas as pd ”: 4→4 • for [variable] in [list]: — loops through list
Python library used for working with data sets (Dataframes) 13 → D • for [variable] in range(num): — loops num times
12 → C • for [variable] in “Potato”: — loops through each character in the string “Potato”
• df = pd.read_csv('file.csv') - loads .csv file data into dataframe named “df” CD4
Nested Loops:
• #Libraries for plotting and data processing: • The inside loop always runs first. This is the column (x-axis), then the row (y-axis). Everything in the first loop must finish running before
import pandas as pd ● df.groupby() the outer loops runs. MATCH THE VARIABLES!!
• for i in range (num):
import matplotlib.pyplot as plt ● .get_group() //do work in outer loop
● .value_count()[:10] ⇒ print 10 highest things/elements
for j in range (num):
#Names in the column //do work in inner loop WHILE LOOP EXAMPLE: WHILE LOOP EXAMPLE:
print (message) n = 5 n = 0
inputFile = input("Enter name of input file: ")
while n > 0: while n > 0:
outputFile = input("Enter name of output file: ") n -= 1 n -= 1
Conditionals: print(n) print(n)
• if, elif — else if, else:
homeless = pd.read_csv(inputFile) • if (condition true): Output: Output:
homeless[ "Fraction Children" ] = homeless[ "Total Children in Shelter" ]/homeless[" Total Individuals in Shelter" ] //your code here
elif (condition true): 4 Code does not execute.
homeless.plot(x = "Date of Census", y = "Fraction Children") //your code here 3
else: 2
//your code here 1
The controlling statement
fig = plt.gcf() 0 is false.
fig.savefig(outputFile) • while:
• while (condition true):
—————— //your code here — code is executed indefinitely unless if something modifies the condition
Numpy | “import numpy as np”:
• np.zeros — Return a new array of given shape and type, filled with zeros. Sets the canvas black
Translate the following python program to a complete C++
• np.ones — Return a new array of given shape and type, filled with ones. Sets the canvas white C++: program:
• #include <iostream> — imports libraries to use cout, cin #Python Loops
• using namespace std; — allows to use the functions for i in range(0,101,25):
The following changes the color of an image: • int main { } — every program requires this to operate print(i+5, i-5)
• img = plt.imread('csBridge.png') #Read in image from csBridge.png • cout << — prints to the terminal
#Converted to C++
• cin >> — takes the users input
plt.imshow(img) #Load image into pyplot #include <iostream>
using namespace std;
plt.show() #Show the image (waits until closed to continue) • for (arg 1; arg 2; arg 3) { } — standard definite loop function int main(){
• arg 1 — executed (one time) before the execution of the code block for (int i = 0; i < 101; i += 25) {
• arg 2 — defines the condition for executing the code block Cout << i+5 << “ “ << i-5 << endl;
img2 = img.copy() #make a copy of our image • arg 3 — executed (every time) after the code block has been executed }
img2[:,:,1] = 0 #Set the green channel to 0 return 0;
• if (condition 1) { } - runs if condition 1 is FALSE }
img2[:,:,2] = 0 #Set the blue channel to 0 • else if (condition 2) { } - runs if condition 1 is FALSE
• else { } - runs if both condition 1 and 2 are FALSE
plt.imshow(img2) #Load our new image into pyplot • while (condition) { } — standard indefinite loop
plt.show() #Show the image (waits until closed to continue) • All lines of code end with ; — (ex. cout << “Hello World!”;)
• Both endl and “\n” signify a new line — cout << “Hello World” << endl; is the same as cout << “Hello World!\n”; (Otherwise, the text
plt.imsave('reds.png', img2) #Save the image we created to the file: reds.png continues without going to the next line.)
• Do not use commas to separate, use << and include spaces “ “.
np.load.txt() ⇒
import pandas as pd Prints multiplication table
def getData(): def print_mult_table(n): #Flood Map
""" # Iterate 10 times from i = 1 to 10
Asks the user for the name of the CSV and for i in range(1, 11): # Takes elevation data of NYC and displays coastlines
Returns a dataframe of the contents. print(n, ’X’, i, ’=’, n*i) import numpy as np
""" def validate_input(num): import matplotlib.pyplot as plt
inF = input(’Enter CSV file name: ’) while(num < 1 or num > 10): elevations = np.loadtxt(‘elevationsNYC.txt’)
df = pd.read_csv(inF) print(’Please enter a number between 1 and 10.’) #Base image size on shape (dimensions) of the elevations:
return(df) num = int(input("Display the multiplication table of? ")) mapShape = elevations.shape + (3,)
return num floodMap = np.zeros(mapShape)
# Display multiplication table of an input number in range 1 - 10
def main(): for row in range (mapShape[0]):
num = int(input("Display multiplication table of? ")) for col in range(mapShape[1]):
num = validate_input(num)
def getLocale(): #print the multiplication table of num CODE BELOW:
""" print_mult_table(num) if elevations[row,col] <= 0: #below sea level
Asks the user for latitude and longitude of the user’s current location and floodMap[row,col,2] = 1.0 #set the blue channel to 100%
Returns those floating points numbers. elif elevations[row,col] <= 6: #flooding likely
""" floodMap[row,col,0] = 1.0 #sets the red channel to 100%
lat = float(input(’Enter current latitude: ’)) else:
lon = float(input(’Enter current longitude: ’)) floodMap[row,col,1] = 1.0 #set the green channel to 100%
return(lat, lon)
#saves the image:
def computeDist(x1,y1,x2,y2): plt.imsave(‘floodMap.png’, floodMap)
"""
Computes the squared distance between two points (x1,y1) and (x2,y2) and
Returns (x1-x2)² + (y1-y2)²
"""
d = (x1 - x2)**2 + (y1 - y2)**2
return(d) #Snow count
#Import the packages for images and arrays:
import matplotlib.pyplot as plt
import numpy as np
Folium example: Python
import folium def diffFreq (s1 , s2 , ch ): imageFile = input("Enter file name: ")
return s1.count(ch) != s2.count(ch) #if ca = plt.imread(imageFile) #Read in image
import webbrowser
occurrences of ch are not equal returns True countSnow = 0 #Number of pixels that are almost white
import os t = 0.75 #Threshold for almost white-- can adjust between 0.0 and
nycMap = folium.Map(location=[40.75, -74.125]) def existDiffFreq(s1, s2, s3):
1.0
nycMarker = folium.Marker([40.7531, -73.9823], popup= 'New York Public for ch in s3:
Library') if diffFreq(s1 , s2 , ch): #For every pixel:
nycMarker.add_to(nycMap) return True
filename = "ny_public_library.html" return False for i in range(ca.shape[0]):
def main(): for j in range(ca.shape[1]):
nycMap.save(filename) print(existDiffFreq(’abcd’, ’bcae’, ’abc’)) #False #Check if red, green, and blue are > t:
print(existDiffFreq(’abcd’, ’bcae’, ’abd’)) #True if (ca[i,j,0] > t) and (ca[i,j,1] > t) and (ca[i,j,2] > t):
webbrowser.open('file://' + os.path.realpath(filename)) countSnow = countSnow + 1
if __name__ == ’ __main__ ’:
main()
print("Snow count is", countSnow)

MIPS:
#Loop through characters this only prints ‘!’
ADDI $sp, $sp, -100 # Set up stack #Circuit example
ADDI $s3, $zero, 1 # Store 1 in a register
ADDI $t0, $zero, 33 # Set $t0 at 33 (!)
ADDI $s2, $zero, 99 # How many “!” chars are printed
SETUP: SB $t0, 0($sp) # Next letter in $t0
ADDI $sp, $sp, 1 # Increment the stack
SUB $s2, $s2, $s3 # Decrease the counter by 1
BEQ $s2, $zero, DONE # Jump to done if $s0 == 0
J SETUP # If not, jump back to SETUP for loop
DONE: ADDI $t0, $zero, 0 # Null (0) to terminate string
SB $t0, 0($sp) # Add null to stack
ADDI $sp, $sp, -99 # How many “!” chars are printed (not (in1 or in2) and (not in2)) or (((in2 and not in3) or in3) and not in3)
ADDI $v0, $zero, 4 # 4 is for print string
-read the circuit right to left ( to draw)
ADDI $a0, $sp, 0 # Set $a0 to stack pointer for printing
syscall # Print to the log
#Nand circuit
#This program asks the user for the name of a .png (image) file //Population Growth
and displays the upper right quarter of the image
#Import the packages for images and arrays: #include <iostream>
using namespace std;

import matplotlib.pyplot as plt int main()


import numpy as np {
int years;
cout << “Please enter years:\n”;
inF = input(’Enter file name: ’)
cin >> years;
img = plt.imread(inF) #Read in image from
float Bp = 12.4/100;
height = img.shape[0] #Get height float Dp = 8.4/1000;
float p = 325.7;
width = img.shape[1] #Get width
int starting = 2017;
print(height,width) out = not (in1 and in2)
years = starting + years;
img2 = img[height/2:, :width/2] #Crop to upper right corner cout << “years\t” << starting << “\t” << p <<
endl;

plt.imshow(img2) #Load our new image into pyplot


while (starting < years) {
plt.show() #Show the image starting = starting + 1;
p = p + (Bp*p) - (Dp*p);
cout << "years\t" << starting << "\t" << p <<
endl;
#PYTHON CODE (NESTED LOOP) }
return 0;
def enigma(n): def help(x): }
for i in range(1, n+1): for j in range(x):
help(i) print((x+j)*2, end=’’) #Prints ticket price for the Museum of Natural History
print()
What is the output for enigma(5)? #include <iostream>
using namespace std;
int main()
{
cout << "Please enter your age: ";
int age;
#include <iostream> cin >> age;
using namespace std; if (age <= 12)
int main() cout << "Child: $12.50\n";
{ else if (age < 65)
int count = 5; Output: cout << "Adult: $22.00\n";
int num = 2; 5 2 else
4 1 cout << "Senior: $17.00\n";
while(count > 0 && num >= 0){ 3 1 return 0;
count << count << “” << num << endl; 2 0 }
count -=1; 1 0
if(count % 2 == 0)
num -=1;
}
return 0;
}

You might also like