Unsorted 1
Asynchronous_programming.py
#Asynchronous programming: a means of parallel programming in which #a unit of work runs separately from the main application thread and #notifies the calling thread of its completion, failure or progress. #Benefits: improved application performance and responsiveness. import asyncio #pip3 install asyncio async def my_coroutine(n): print('starting:',n) await asyncio.sleep(1) #'await' a task, such as fileread, #getting something from web, #writing to disk, query a db, etc. print('finishing:',n) loop = asyncio.get_event_loop() tasks = list() for i in range(5): task = loop.create_task(my_coroutine(i)) tasks.append(task) loop.run_until_complete(asyncio.wait(tasks)) loop.close()
colours in IDLE.py
import sys import time colour = sys.stdout.shell colour.write("strings are green ..... \n","STRING") time.sleep(1) colour.write("comments are red...\n","COMMENT") time.sleep(1) colour.write("builtins are purple...\n","BUILTIN") #--------Colours to choose from: #SYNC, stdin, BUILTIN, STRING, #console, COMMENT, stdout, TODO, #stderr, hit, DEFINITION, KEYWORD, #ERROR, sel
discus_dictionary.py
##STEP 1: SET UP VARIABLES## pool = {"You": [], "Player 2": []} number_of_throws = 2 ##STEP 2: CREATE DICTIONARY OF THROWS## import random for each_player in pool: for throw in range(number_of_throws): pool[each_player].append(random.randint(10,50)) print(pool) print("\n") ##STEP 3: CALCULATE MAXIMUM THROW DICTIONARY## max_throws = {key:max(pool[key]) for key in pool} print(max_throws) print("\n") ##STEP 4: PRINT SORTED BY DISTANCE## for position, each in enumerate(sorted(max_throws, key = lambda key: max_throws[key], reverse = True)): print(each, "scored", max_throws[each], "metres, position", position+1) #0 is 1st place
flask_client.py
import http.client httpServ = http.client.HTTPConnection("127.0.0.1", 5001) httpServ.connect() def sendData(data): httpServ.request("GET", "/console?message=" + data) response = httpServ.getresponse() print(response.read()) httpServ.close() sendData("blah%20blah")
flask_server.py
from flask import Flask from flask import request from flask import render_template app = Flask(__name__) @app.route("/console", methods=["GET"]) def console(): return "thanks m8 for " + request.args.get("message") @app.route("/listen", methods=["GET"]) def connectionWithClient(): incoming = request.args.get("message") return render_template("message.html", message=incoming) @app.route("/") def urlTriggerThis(): return render_template("standard.html", colour="salmon") app.run(host="127.0.0.1", port=5001)
paper scissors rock.py
import random weaknesses = { "Scissors":"Rock", "Rock":"Paper", "Paper":"Scissors", } myChoice = input("Scissors Rock Paper >> ") cpuChoice = random.choice(["Scissors","Rock","Paper"]) print("CPU chooses", cpuChoice) #if myChoice is the weakness of cpuChoice, i WIN: if myChoice == weaknesses[cpuChoice]: print(myChoice, "beats", cpuChoice, "you WIN") #elif cpuChoice is the weakness of myChoice, I LOSE: elif cpuChoice == weaknesses[myChoice]: print(cpuChoice, "beats", myChoice, "you LOSE") #else DRAW: else: print("Draw")
sorts and shuffles.py
SIZE_OF_ARRAY = 9999 import timeit import random #-------BUBBLE SORT------- def BubbleSort(array): for index in range(len(array)): for cursor in range(index,len(array)): if array[index] > array[cursor]: swap = array[index]; array[index] = array[cursor]; array[cursor] = swap; return array #-------INSERTION SORT------- def InsertionSort(array): for index in range(1,len(array)): cursor = index swap = array[cursor] while cursor > 0 and swap < array[cursor-1]: array[cursor] = array[cursor-1] cursor=cursor-1 array[cursor] = swap return array #-------QUICK SORT------- def QuickSort(array): if not array: return [] pivots = [x for x in array if x == array[0]] lesser = QuickSort([x for x in array if x < array[0]]) greater = QuickSort([x for x in array if x > array[0]]) return lesser + pivots + greater #-------SHUFFLE (alternative to random.shuffle(list))------- def Shuffle(array): length = len(array) while length > 1: length = length - 1 cursor = random.randint(0, length+1) swap = array[cursor] array[cursor] = array[length] array[length] = swap return array #-------HELPER FUNCTIONS: def Call(task): calls = { "Shuffle": Shuffle, "QuickSort": QuickSort, "InsertionSort": InsertionSort, "BubbleSort": BubbleSort, } return calls.get(task) def Do(task): global array print("Starting " + task + " of " + str(SIZE_OF_ARRAY) + " elements.") timeStarted = timeit.default_timer() if task != "random.shuffle": function = Call(task) array = function(array) else: random.shuffle(array) elapsed = timeit.default_timer() - timeStarted print(task + " took " + "{0:.2f}".format(round(elapsed,2)) + " seconds.") #-------MAIN: array = list(range(SIZE_OF_ARRAY)) #set at top, default 5000 Do("Shuffle") Do("QuickSort") Do("random.shuffle") Do("InsertionSort") Do("Shuffle") Do("BubbleSort")
sqlite and json.py
import sqlite3 import json #----JSON: jsonData = '{"name": "Michael", "age": 21}' pythonData = json.loads(jsonData) backTojson = json.dumps(pythonData) #----SQLite: conn = sqlite3.connect('chinook.db') c = conn.cursor() c.execute("SELECT * FROM artists") all_rows = c.fetchall() print(all_rows)