Posts

Showing posts from May, 2018

Python 3.4 - Caesar Cipher

Caesar ciphers take a list of values and rotates through them to give them a different value. The program below takes from the alphabet and creates a cipher of the message. It returns many variations of the cipher then returns the actual message. import string import collections def caesar (rotate_string , number_to_rotate_by): upper = collections.deque(string.ascii_uppercase) lower = collections.deque(string.ascii_lowercase) upper.rotate(number_to_rotate_by) lower.rotate(number_to_rotate_by) upper = '' .join( list (upper)) lower = '' .join( list (lower)) return rotate_string.translate( str .maketrans(string.ascii_uppercase , upper)).translate( str .maketrans(string.ascii_lowercase , lower)) my_string = 'This is the message' my_string2 = caesar(my_string , 1 ) for i in range ( len (string.ascii_uppercase)): print (i , "|" , caesar(my_string2 , i)) /Users/mattfassnacht/PycharmProjects/untitled12/venv/bin/pyt...

Coding for UWAV - Views

Creating the apps for your website you need to have the site direct the user to certain pages. By adding what the website should do when a page is requested is stored in views. It gives a function response. def searchpage ( request ): return HttpResponse( "<h1>This is the searchpage!</h1>" ) https://www.youtube.com/watch?v=nAn1KpPlN2w

Coding for UWAV - Django Apps

In Django it seems like each functionality of a site, each page that does something different, is handled as an app. It is to be treated separately but part of the whole.  The map and search function is an app. The submitting page is an app.The user-page is an app. The joining page is an app. The setting page is an app. The event page is an app. Once installed the app contains several pre-made python files for specific purposes: __init__.py is the initializer (leave it alone) admin.py is the place where you have your admin controls apps.py is where you have your settings for this specific app models.py is the database and how you will store the data (i.e. classes, dictionaries, tables) tests.py is for tests to see if things are working views.py is for functions for user requests and responses https://www.youtube.com/watch?v=lcD0CDurxas&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK

Django and coding for UWAV

I am first installing Django and all the necessary things that go with it. So, it's a complex process to install Django, but go to Django.   Actually you don't reeeeally need to go there. I would recommend finding a decent video on the steps to install, here's one: https://www.youtube.com/watch?v=cdkH6iQJrO0 From there it's a matter of learning what you can do with it. 

Python 3.4 - Global and Local Functions

https://www.youtube.com/watch?v=r9LtArXOYjk

Python 3.4 - Coding Practice

from collections import defaultdict my_dict = { 'name' : 'Jeff' , 'job' : 'teacher' , 'age' : 49 , 'salary' : 50000 } print (my_dict.get( 'job' )) print (my_dict[ 'name' ]) print (my_dict.get( 'rank' , 'not found' )) ##this will print the second value if the first is not found print ( sorted (my_dict.items())) print ( sorted (my_dict.keys())) my_dict[ 'last_name' ] = 'Johnson' my_dict[ 'middle name' ] = 'Bozo' # notice that the key doesn't have to be connected print (my_dict) del my_dict[ 'age' ] print (my_dict) my_dict.clear() print (my_dict) print ( '------------------------------' ) my_dict2 = { 'name' : 'Jeff' , 'job' : 'teacher' , 'age' : 49 , 'salary' : 50000 } for i in my_dict2.keys(): print (i) print ( '------------------------------' ) for i in my_dict2.values(): ...

Python 3.4 - String Formatting

String formatting is super useful when working with lists, tuples, and dictionaries. It allows you to do many things like calling on information and or doing things like datetime, etc. See below: import datetime person = {'name': 'Matt', 'age': 38} list_person = ['Matt', 38] sentence = 'My name is {} and I am {} years old.'.format (person['name'], person['age']) print(sentence) sentence2 = 'My name is {0} and I am {1} years old.'.format (person['name'], person['age']) print(sentence2) tag = 'h1' text = 'This is a header' sentence3 = '<{0}>{1}<{0}>'.format(tag, text) print(sentence3) sentence4 = 'My name is {0[name]} and I am {1[age]} years old.'.format (person, person) print(sentence4) sentence5 = 'My name is {0[name]} and I am {0[age]} years old.'.format (person) print(sentence5) sentence6 = 'My name is {0[0]} and I am {...

Python 3.4 - Decorators

 You can not only run messages through other functions but you can run other functions through functions. And you can run multiple, other functions through functions. def outer_func (msg): message = msg def inner_func (): print (message) return inner_func #this is important, notcie how the inner function isn't returning anything yet hi_func = outer_func( 'hi' ) # now the variable hi_func is loaded with the return value of the inner function # and has th message stored hi_func() # this now prints or runs the functions with the () included print ( '-------------------------------' ) def decor_func (orig_function): # so now this is going to runa function instead of a message. def wrapper_function (): # this will return the orig_function within the decor_func return orig_function() return wrapper_function def display (): # this is the function begin returned within the other functions print ( 'display function i...

Python 3.4 - Closures

Closures have access to the outer functions arguments and variables.  def outer_func (): message = 'hi' def inner_func (): print (message) return inner_func my_func = outer_func() # this creates a function my_func() # this runs the functon using the out_func my_func() # three times my_func() print ( '---------------------------------' ) def outer_func (msg): #this is a bit different because it takes a message now message = msg # an message is equal to the message variable set def inner_func (): print (message) return inner_func hi_func = outer_func( 'hi sucka' ) #these need an argument to work hello_func = outer_func( 'hello' ) hi_func() hello_func() print ( '---------------------------------' )  /Users/mattfassnacht/PycharmProjects/untitled10/venv/bin/python /Users/mattfassnacht/PycharmProjects/untitled10/math.py hi hi hi --------------------------------- hi sucka hello Process finishe...

Python 3.4 - First-Class Functions

 You can assign functions to variables. And you can have functions within functions. def square (x): # this function will return the value of x times itself return x * x f = square( 5 ) # this is the variable and the value of x is determined print (square) # just printing out the position of the function print (square( 3 )) # this is a stand-alone print statement calling on the function, not creating a variable print (f) # this prints the results of the function which will take 5 and multiply it by itself h = square # this makes the variable h the equivalent of the function square. print (h) # just printing out the position of the function print (h( 4 )) # now h is being treated as the function square print ( '--------------------------------------------' ) def my_map (func , arg_list): # this sets up the function to return a result, # which will be using the function on the array result = [] for i in arg_list: result.append(func(i)) ...

Python 3.4 - Dictionaries

my_dict = { 'employee_name' : 'Jeff' , 'job' : 'Teacher' , 'rank' : 10 , 'salary' : 6000 , 'favorite things' : [ 'polo' , 'horses' , 'movies about horses' ]} # dictionaries are made of keys with values print (my_dict) print (my_dict[ 'job' ]) # this prints out the item in the dict print (my_dict[ 'favorite things' ]) # this prints out the key which is a list within the dict my_dict2 = { 1 : 'Jeff' , 'job' : 'Teacher' , 'rank' : 10 , 'salary' : 6000 , 'favorite things' : [ 'polo' , 'horses' , 'movies about horses' ]} print (my_dict2[ 1 ]) # an integer can be a key print (my_dict2.get( 'job' )) # this will get the value of the key specified. my_dict2[ 'phone' ] = '555-5555' print (my_dict2) # notice that the phone value has been added to the dictionary my_di...

Python 3.4 - Roman Numerals

This program prints out the equivalent roman numeral: roman = [ 'I' , 'II' , 'III' , 'IV' , 'V' , 'VI' , 'VII' , 'VIII' , 'IX' , 'X' ] num_input = '' while num_input != 'q' : print ( " \n [1] Enter a number (1-10) to convert into a roman numeral." ) print ( ' \n press q to exit' ) num_input = input ( " \n Enter your number: " ) if num_input == '1' : print ( ' \n That is the roman numeral: ' + roman[ 0 ]) elif num_input == '2' : print ( ' \n That is the roman numeral: ' + roman[ 1 ]) elif num_input == '3' : print ( ' \n That is the roman numeral: ' + roman[ 2 ]) elif num_input == '4' : print ( ' \n That is the roman numeral: ' + roman[ 3 ]) elif num_input == '5' : print ( ' \n That is the roman numeral: ' + r...

Python 3.4 - My first game

https://repl.it/repls/WhiteIncompleteCalculators from time import sleep print ( ' \n Welcome to the game! \n ' ) sleep( 1 ) print ( '------------------------------ \n ' ) sleep( 1 ) choice = '' straightchoice = '' leftchoice = '' rightchoice = '' while choice != 'q' : print ( ' \n You have entered the Spooky Castle. \n ' ) sleep( 1 ) print ( 'There are three ways to go. \n ' ) sleep( 1 ) print ( 'Straight (1), \n ' ) sleep( .5 ) print ( 'Left (2) or, \n ' ) sleep( .5 ) print ( 'Right (3). \n ' ) sleep( 1 ) print ( 'Choose your path by entering the number. \n ' ) sleep( 1 ) print ( 'press q to quit.' ) choice = input ( ' \n Enter the number:' ) if choice == '1' : sleep( 1 ) print ( ' \n Uh oh...you chose to go straight. \n ' ) (sleep( 1 )) print ( ...

Python 3.4 - List Comprehension Practice

## values = expression for value in collection ## squares = x * x for x in range(10) squares = [x * x for x in range ( 10 )] print (squares) ##values = [] ## for value in colleciton ##values.append(expression) squares = [] for x in range ( 10 ): squares.append(x*x) print (squares) print ( '-------------------------------' ) ## this will only do the expression if the remainder is True. even_squares = [x*x for x in range ( 10 ) if x % 2 == 0 ] print (even_squares) ##this does the same thing as the above, but in a for loop even_squares = [] for x in range ( 10 ): if x % 2 == 0 : even_squares.append(x*x) print (even_squares) print ( '-------------------------------' ) employees = [ 'jeff' , 'rick' , 'nick' , 'matt' ] new_employees = [] for x in employees: new_employees.append(x) print (new_employees) print ( '-------------------------------' ) ##notice the difference with the print statement and ...

Python 3.4 - Threading Module

 The threading module allows a program to run multiple operations at the same time in the same process space. import threading from queue import Queue import time print_lock = threading.Lock() def exampleJob (worker): time.sleep( 0.5 ) with print_lock: print (threading.current_thread().name , worker) def threader (): while True : worker = q.get() exampleJob(worker) q.task_done() q = Queue() for x in range ( 10 ): t = threading.Thread( target =threader) t.daemon = True t.start() start = time.time() for worker in range ( 20 ): q.put(worker) q.join() print ( 'entire job took:' , time.time() - start) /Users/mattfassnacht/PycharmProjects/untitled6/venv/bin/python /Users/mattfassnacht/PycharmProjects/untitled6/functions.py Thread-1 0 Thread-2 1 Thread-8 7 Thread-6 5 Thread-7 6 Thread-10 9 Thread-4 3 Thread-9 8 Thread-5 4 Thread-3 2 Thread-2 11 Thread-8 12 Thread-10 15 Thread-4 16 Thread-9 17 Thread-7 14 Th...

Python 3.4 - Array Module

Arrays are much like lists but they are confined to one type of data.  The example linked needs parentheses around the print statements, but you can see below some of the differences between lists and arrays: import array a = array.array( "B" , range ( 16 )) # unsigned char b = array.array( "h" , range ( 16 )) # signed short print (a) print ( repr (a.tostring())) print (b) print ( repr (b.tostring())) /Users/mattfassnacht/PycharmProjects/untitled6/venv/bin/python /Users/mattfassnacht/PycharmProjects/untitled6/functions.py array('B', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' array('h', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) b'\x00\x00\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00\x07\x00\x08\x00\t\x00\n\x00\x0b\x00\x0c\x00\r\x00\x0e\x00\x0f\x00' Process finished with exit code 0 http://effbot.org/librarybook/array.htm

Python 3.4 - Bisect Module

The Bisect Module "provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach." import bisect mylist = [ 1 , 3 , 4 , 4 , 4 , 6 , 7 ] print ( "the rightmost index is : " , end = "" ) print (bisect.bisect(mylist , 4 )) print ( "the rightmost index is : " , end = "" ) print (bisect.bisect_left(mylist , 4 )) mylist2 = [ 1 , 3 , 4 , 4 , 4 , 6 , 7 ] bisect.insort(mylist2 , 5 , 0 , 5 ) print ( "the list is now:" ) for i in range ( 0 , 8 ): print (mylist2[i] , end = "" ) print ( ' \r ' ) bisect.insort_left(mylist2 , 2 ) print ( "the list is now:" ) for i in range ( 0 , 9 ): print (mylist2[i] , end = "" )  /Users/mattfassnacht/PycharmProjects/untitled6/venv/bin/python /Users/mattfassnacht/PycharmProjects/...

Python - Practice

Creating classes and subclasses allows you to inherit both or override the other. By including the super.()__init__() attribute you can use both! class Contact: def __init__ ( self , first_name , last_name): self .first_name = first_name self .last_name = last_name self .full_name = first_name + "" + last_name def print_contact ( self ): print ( self .full_name) class EmailContact(Contact): def __init__ ( self , first_name , last_name , email): super (). __init__ (first_name , last_name) self .email = email self .full_name = email email_contact = EmailContact( 'test' , 'person' , "test@person.com" ) print (email_contact.print_contact()) /Users/mattfassnacht/PycharmProjects/untitled6/venv/bin/python /Users/mattfassnacht/PycharmProjects/untitled6/prac3.py test@person.com None Process finished with exit code 0

Python - Practice

This is some practice on string manipulation, for and while loops, and guess and check. s = 'abc' print ( len (s)) print (s[ 0 ]) print (s[ 1 ]) print (s[ 2 ]) print (s[- 1 ]) print (s[- 2 ]) print (s[- 3 ]) t = 'hdfjlhdjlfh' print (t[::]) print (t[ 0 : 4 ]) h = 'hello' print (h) h = 'y' + h[ 1 : len (h)] print (h) for var in range ( 5 ): print ( 'this will print 5 times, starting with 0 and ending with 4' ) for var2 in range ( 1 , 5 ): print ( 'this will print 4 times, starting with 1 and ending with 4' ) for letter in t: if letter == 'h' : print ( 'this is an h!' ) else : print ( 'this is not an h!' ) an_letters = 'abcdefghijklmnopqrstuvwxyz' word = input ( 'Enter a word:' ) times = int ( input ( 'How many times?' )) i = 0 while i < len (word): letter = word[i] if letter in an_letters: print ( 'give me an ' + letter + ...

Python 3.4 - Time Module

Time module has attributes that deal with time. You can have a program print out the time in different ways and you can use those variables as any others. One cool attribute is to have you program actually stop for a short or long amount of time. See the example and video below: import time start = time.time() (time.time()) print (time.asctime()) print (time.gmtime()) now = time.gmtime() print (now[ 1 ]) now = time.asctime(now) print (now) time.sleep( 3 ) stop = time.time() print (stop - start) Tue May  8 13:11:25 2018 time.struct_time(tm_year=2018, tm_mon=5, tm_mday=8, tm_hour=20, tm_min=11, tm_sec=25, tm_wday=1, tm_yday=128, tm_isdst=0) 5 Tue May  8 20:11:25 2018 3.0046298503875732 Process finished with exit code 0 https://www.youtube.com/watch?v=Q9qp4CVngKE

Python 3.4 - Calendar and Datetime Modules

Calendar and datetime modules deal with data that you would think they deal with, mainly functions related to the calendar dates, and the amount of days in a month or given year. You can find the date for today or any other day. You can find the amount of days in a given month. You can use this information with some other information to determine when something can begin or finish: import datetime import calendar balance = 5000 interest_rate = .13 monthly_payment = 500 today = datetime.date.today() # this sets a variable for today to today days_in_current_month = calendar.monthrange(today.year , today.month)[ 1 ] days_till_end_month = days_in_current_month - today.day start_date = today + datetime.timedelta( days =days_till_end_month + 1 ) end_date = start_date while balance > 0 : interest_charge = (interest_rate / 12 ) * balance balance = balance + interest_charge balance = balance - monthly_payment balance = round (balance , 2 ) if balance < 0 : ...

Python 3.4 - Random Module

Remember that most of these modules come pre-installed with your Python software. It is a part of the standard library of modules and functions. There are many different attributes to the random module that can work with list and generate generic data or pull from databases.  import random print (random.random()) print (random.uniform( 1 , 200 )) # this will give a random number between the two integers print (random.randint( 1 , 6 )) # this will return a whole integer greetings = [ 'hello' , 'piss off' , 'sup bro' ] name = [ 'Nick' , 'Matt' , 'Dustin' , 'Andrew' ] last_names = [ 'Fassnacht' , 'Krieger' , 'Williams' , 'Heinrich' ] state = [ 'Arizona' , 'California' , 'Utah' , 'Oregon' ] print (random.choice(greetings)) print (random.choices(greetings , k = 5 )) # this will give 5 random choices print (random.choices(greetings , weights = [ 18 , 18 , ...