Loading...
More Python Posts
from functools import partialdef curry(fn, *args):return partial(fn, *args)add = lambda x, y: x + yadd10 = curry(add, 10)add10(20) # 30
# Python program for Bitonic Sort. Note that this program# works only when size of input is a power of 2.# The parameter dir indicates the sorting direction, ASCENDING# or DESCENDING; if (a[i] > a[j]) agrees with the direction,# then a[i] and a[j] are interchanged.*/def compAndSwap(a, i, j, dire):if (dire==1 and a[i] > a[j]) or (dire==0 and a[i] > a[j]):a[i],a[j] = a[j],a[i]# It recursively sorts a bitonic sequence in ascending order,# if dir = 1, and in descending order otherwise (means dir=0).# The sequence to be sorted starts at index position low,# the parameter cnt is the number of elements to be sorted.def bitonicMerge(a, low, cnt, dire):if cnt > 1:k = cnt/2for i in range(low , low+k):compAndSwap(a, i, i+k, dire)bitonicMerge(a, low, k, dire)bitonicMerge(a, low+k, k, dire)# This funcion first produces a bitonic sequence by recursively# sorting its two halves in opposite sorting orders, and then# calls bitonicMerge to make them in the same orderdef bitonicSort(a, low, cnt,dire):if cnt > 1:k = cnt/2bitonicSort(a, low, k, 1)bitonicSort(a, low+k, k, 0)bitonicMerge(a, low, cnt, dire)# Caller of bitonicSort for sorting the entire array of length N# in ASCENDING orderdef sort(a,N, up):bitonicSort(a,0, N, up)# Driver code to test abovea = [3, 7, 4, 8, 6, 2, 1, 5]n = len(a)up = 1sort(a, n, up)print ("\n\nSorted array is")for i in range(n):print("%d" %a[i]),
# Python code to demonstrate# method to remove i'th character# Naive Method# Initializing Stringtest_str = "CodeCatch"# Printing original stringprint ("The original string is : " + test_str)# Removing char at pos 3# using loopnew_str = ""for i in range(len(test_str)):if i != 2:new_str = new_str + test_str[i]# Printing string after removalprint ("The string after removal of i'th character : " + new_str)
import stringdef caesar(text, shift, alphabets):def shift_alphabet(alphabet):return alphabet[shift:] + alphabet[:shift]shifted_alphabets = tuple(map(shift_alphabet, alphabets))final_alphabet = "".join(alphabets)final_shifted_alphabet = "".join(shifted_alphabets)table = str.maketrans(final_alphabet, final_shifted_alphabet)return text.translate(table)plain_text = "Hey Skrome, welcome to CodeCatch"print(caesar(plain_text, 8, [string.ascii_lowercase, string.ascii_uppercase, string.punctuation]))
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)
from collections import defaultdictdef combine_values(*dicts):res = defaultdict(list)for d in dicts:for key in d:res[key].append(d[key])return dict(res)d1 = {'a': 1, 'b': 'foo', 'c': 400}d2 = {'a': 3, 'b': 200, 'd': 400}combine_values(d1, d2) # {'a': [1, 3], 'b': ['foo', 200], 'c': [400], 'd': [400]}