Loading...
More Python Posts
def check_prop(fn, prop):return lambda obj: fn(obj[prop])check_age = check_prop(lambda x: x >= 18, 'age')user = {'name': 'Mark', 'age': 18}check_age(user) # True
def generate_floyds_triangle(num_rows):triangle = []number = 1for row in range(num_rows):current_row = []for _ in range(row + 1):current_row.append(number)number += 1triangle.append(current_row)return triangledef display_floyds_triangle(triangle):for row in triangle:for number in row:print(number, end=" ")print()# Prompt the user for the number of rowsnum_rows = int(input("Enter the number of rows for Floyd's Triangle: "))# Generate Floyd's Trianglefloyds_triangle = generate_floyds_triangle(num_rows)# Display Floyd's Triangledisplay_floyds_triangle(floyds_triangle)
import os, json, boto3, requestsfrom flask import Flask, request, jsonifyfrom flask_cors import CORS, cross_originfrom random import shuffleapp = Flask(__name__)cors = CORS(app)dynamodb = boto3.resource("dynamodb", region_name="us-east-1")app.url_map.strict_slashes = FalseSECRET_KEY = os.environ.get("SECRET_KEY")@app.route("/teks")def teks_request():teks_file = open("teks.json", "r")data = json.load(teks_file)return jsonify(data)@app.route("/teks/find/113.41.<int:teks_id>.<string:section_id>")def teks_find_request(teks_id, section_id):teks_file = open("teks.json", "r")data = json.load(teks_file)for item in data:if item["id"] == teks_id:for child in item["children"]:if child["id"] == section_id:return {"tek": item, "content": child["content"]}return jsonify([f"Something went wrong. TEKS section id of {section_id} cannot be found within TEKS section {teks_id}."])@app.route("/lessonplan/read/<id>")def read_lesson_plan(id):lesson_table = dynamodb.Table("Lesson_Plans")items = lesson_table.scan()['Items']for lesson in items:if (lesson["uuid"] == id):return jsonify(lesson)return {"error": "id does not exist", "section": id}@app.route("/teks/<int:teks_id>")def teks_id_request(teks_id):teks_file = open("teks.json", "r")data = json.load(teks_file)for item in data:if item["id"] == teks_id:return jsonify(item)return jsonify([f"Something went wrong. TEKS id of {teks_id} cannot be found."])@app.route("/assessment/write", methods=["GET", "POST"])def assessment_write():assessment_json = request.jsonassessment_data = dict(assessment_json)assessment_table = dynamodb.Table("Assessments")assessment_table.put_item(Item=assessment_data)if assessment_data == get_assessment(assessment_data["id"]):return "Success"else:return "Failure"@app.route("/students/read/<id>")def students_read(id):return jsonify(get_students(id))@app.route("/students/read")def all_students_read():student_table = dynamodb.Table("Students")items = student_table.scan()['Items']return jsonify(items)@app.route("/assessment/read/<id>")def assessment_read(id):return jsonify(get_assessment(id))@app.route("/assessment/submit/<id>", methods=["POST"])def submit_assessment(id):assessments_table = dynamodb.Table("Assessments")assessment = assessments_table.get_item(Key={"id": id})if not assessment.get("Item"):return {"error": "id does not exist", "section": id}responses = {question["id"]: question["response"]for question in request.json.get("questions")}correct_answers = 0for response in responses:# print(# (# responses[response],# find_question(assessment.get("Item").get("questions"), response).get(# "correctAnswer"# ),# )# )if responses[response] == find_question(assessment.get("Item").get("questions"), response).get("correctAnswer"):correct_answers += 1score = correct_answers / len(request.json.get("questions"))users_table = dynamodb.Table("Students")users_table.update_item(Key={"uuid": request.json.get("student_id")},UpdateExpression="SET completedAssessments = list_append(completedAssessments, :i)",ExpressionAttributeValues={":i": [{"id": id,"score": round(score * 100),}]},)message = Noneif round(score * 100) > 70:message = f"Congratulations! You passed your assessment with a {round(score * 100)}%."else:message = f"You failed your assessment with a {round(score * 100)}%."sns = boto3.client("sns", region_name="us-east-1")number = "+15125967383"sns.publish(PhoneNumber=number, Message=message)return {"score": score, "message": message}def find_question(all, id):#print("id to find: ", id)for question in all:if question["id"] == id:#print(question)return questiondef get_assessment(id):assessment_table = dynamodb.Table("Assessments")results = assessment_table.get_item(Key={"id": id})if results.get("Item") is None:return {"error": "id does not exist", "section": id}else:quiz = results.get("Item")return {"title": quiz.get("title"),"id": quiz.get("id"),"questions": [{"id": question.get("id"),"title": question.get("title"),"options": random_answers(question.get("incorrectAnswers")+ [question.get("correctAnswer")]),}for question in quiz.get("questions")],}def get_students(id):students_table = dynamodb.Table('Students')results = students_table.get_item(Key = {"uuid": id})if(results.get("Item") is None):return {'error': 'id does not exist', 'section': id}else:student = results.get("Item")return studentdef lesson_plans_read():student_table = dynamodb.Table("Lesson_Plans")items = student_table.scan()['Items']return jsonify(items)def random_answers(answers):shuffle(answers)return answers@app.route("/recommendations/<uuid>")def get_recommendation(uuid):student_info_table = dynamodb.Table('Students')lesson_plans_table = dynamodb.Table('Lesson_Plans')student = get_students(uuid)tek = student.get("struggleTeks")[0]lesson_plans = lesson_plans_table.scan( Select='ALL_ATTRIBUTES', FilterExpression='tek = :s', ExpressionAttributeValues={ ":s": tek })#print(lesson_plans)return jsonify({"student": student, "lesson_plans": lesson_plans.get("Items")})if __name__ == "__main__":app.run(host="0.0.0.0", debug=True)
import randomclass Node:def __init__(self, c):self.left = Noneself.right = Noneself.color = cdef SetColor(self,c) :self.color = cdef PrintNode(self) :print(self.color)def insert(s, root, i, n):if i < n:temp = Node(s[i])root = temproot.left = insert(s, root.left,2 * i + 1, n)root.right = insert(s, root.right,2 * i + 2, n)return rootdef MakeTree(s) :list = insert(s,None,0,len(s))return listdef MakeSet() :s = []count = random.randint(7,12)for _ in range(count) :color = random.randint(0,1) == 0 and "Red" or "White"s.append(color)return sdef ChangeColor(root) :if (root != None) :if (root.color == "White") :root.SetColor("Red")ChangeColor(root.left)ChangeColor(root.right)def PrintList(root) :if root.left != None :PrintList(root.left)else :root.PrintNode()if root.right != None :PrintList(root.right)else :root.PrintNode()t1 = MakeTree(MakeSet())print("Original Colors For Tree 1:\n")PrintList(t1)ChangeColor(t1)print("New Colors For Tree 1:\n")PrintList(t1)t2 = MakeTree(MakeSet())print("Original Colors For Tree 2:\n")PrintList(t2)ChangeColor(t2)print("New Colors For Tree 2:\n")PrintList(t2)t3 = MakeTree(MakeSet())print("Original Colors For Tree 3:\n")PrintList(t3)ChangeColor(t3)print("New Colors For Tree 3:\n")PrintList(t3)
# Python program for implementation of Radix Sort# A function to do counting sort of arr[] according to# the digit represented by exp.def countingSort(arr, exp1):n = len(arr)# The output array elements that will have sorted arroutput = [0] * (n)# initialize count array as 0count = [0] * (10)# Store count of occurrences in count[]for i in range(0, n):index = (arr[i]/exp1)count[int((index)%10)] += 1# Change count[i] so that count[i] now contains actual# position of this digit in output arrayfor i in range(1,10):count[i] += count[i-1]# Build the output arrayi = n-1while i>=0:index = (arr[i]/exp1)output[ count[ int((index)%10) ] - 1] = arr[i]count[int((index)%10)] -= 1i -= 1# Copying the output array to arr[],# so that arr now contains sorted numbersi = 0for i in range(0,len(arr)):arr[i] = output[i]# Method to do Radix Sortdef radixSort(arr):# Find the maximum number to know number of digitsmax1 = max(arr)# Do counting sort for every digit. Note that instead# of passing digit number, exp is passed. exp is 10^i# where i is current digit numberexp = 1while max1/exp > 0:countingSort(arr,exp)exp *= 10# Driver code to test abovearr = [ 170, 45, 75, 90, 802, 24, 2, 66]radixSort(arr)for i in range(len(arr)):print(arr[i]),
# Python program to reverse a linked list# Time Complexity : O(n)# Space Complexity : O(n) as 'next'#variable is getting created in each loop.# Node classclass Node:# Constructor to initialize the node objectdef __init__(self, data):self.data = dataself.next = Noneclass LinkedList:# Function to initialize headdef __init__(self):self.head = None# Function to reverse the linked listdef reverse(self):prev = Nonecurrent = self.headwhile(current is not None):next = current.nextcurrent.next = prevprev = currentcurrent = nextself.head = prev# Function to insert a new node at the beginningdef push(self, new_data):new_node = Node(new_data)new_node.next = self.headself.head = new_node# Utility function to print the linked LinkedListdef printList(self):temp = self.headwhile(temp):print temp.data,temp = temp.next# Driver program to test above functionsllist = LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(85)print "Given Linked List"llist.printList()llist.reverse()print "\nReversed Linked List"llist.printList()