Skip to main content

Return Letter Combinations

Nov 18, 2022AustinLeath
Loading...

More Python Posts

Find Coin

Oct 4, 2023AustinLeath

0 likes • 10 views

weigh = lambda a,b: sum(b)-sum(a)
FindCoin = lambda A: 0 if (n := len(A)) == 1 else (m := n//3) * (w := 1 + weigh(A[:m], A[2*m:])) + FindCoin(A[m*w:m*(w+1)])
print(FindCoin([1,1,1,1,1,1,1,2,1]))

Goobla Academy Flask API

Nov 18, 2022AustinLeath

0 likes • 0 views

import os, json, boto3, requests
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
from random import shuffle
app = Flask(__name__)
cors = CORS(app)
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
app.url_map.strict_slashes = False
SECRET_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.json
assessment_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 = 0
for 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 += 1
score = 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 = None
if 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 question
def 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 student
def 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)

Sherlock Holmes Curious Lockbox Solver

Mar 12, 2021LeifMessinger

0 likes • 0 views

import copy
begining = [False,False,False,False,False,None,True,True,True,True,True]
#False = black True = white
its = [0]
def swap(layout, step):
layoutCopy = copy.deepcopy(layout)
layoutCopy[(step[0]+step[1])], layoutCopy[step[1]] = layoutCopy[step[1]], layoutCopy[(step[0]+step[1])]
return layoutCopy
def isSolved(layout):
for i in range(len(layout)):
if(layout[i] == False):
return (i >= (len(layout)/2))
def recurse(layout, its, steps = []):
if isSolved(layout):
its[0] += 1
print(layout,list(x[0] for x in steps))
return
step = None
for i in range(len(layout)):
if(layout[i] == None):
if(i >= 1): #If the empty space could have something to the left
if(layout[i - 1] == False):
step = [-1,i]
recurse(swap(layout,step), its, (steps+[step]))
if(i > 1): #If the empty space could have something 2 to the left
if(layout[i - 2] == False):
step = [-2,i]
recurse(swap(layout,step), its, (steps+[step]))
if(i < (len(layout)-1)): #If the empty space could have something to the right
if(layout[i + 1] == True):
step = [1,i]
recurse(swap(layout,step), its, (steps+[step]))
if(i < (len(layout)-2)): #If the empty space could have something to the right
if(layout[i + 2] == True):
step = [2,i]
recurse(swap(layout,step), its, (steps+[step]))
its[0] += 1
#return None
recurse(begining,its,[])
print(its[0])

Currency Converter

Nov 19, 2022CodeCatch

0 likes • 0 views

""" Currency Converter
----------------------------------------
"""
import urllib.request
import json
def currency_converter(currency_from, currency_to, currency_input):
yql_base_url = "https://query.yahooapis.com/v1/public/yql"
yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair' \
'%20in%20("'+currency_from+currency_to+'")'
yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
try:
yql_response = urllib.request.urlopen(yql_query_url)
try:
json_string = str(yql_response.read())
json_string = json_string[2:
json_string = json_string[:-1]
print(json_string)
yql_json = json.loads(json_string)
last_rate = yql_json['query']['results']['rate']['Rate']
currency_output = currency_input * float(last_rate)
return currency_output
except (ValueError, KeyError, TypeError):
print(yql_query_url)
return "JSON format error"
except IOError as e:
print(str(e))
currency_input = 1
#currency codes : http://en.wikipedia.org/wiki/ISO_4217
currency_from = "USD"
currency_to = "TRY"
rate = currency_converter(currency_from, currency_to, currency_input)
print(rate)

Using logic with sets

Nov 18, 2022AustinLeath

0 likes • 0 views

#Sets
U = {0,1,2,3,4,5,6,7,8,9}
P = {1,2,3,4}
Q = {4,5,6}
R = {3,4,6,8,9}
def set2bits(xs,us) :
bs=[]
for x in us :
if x in xs :
bs.append(1)
else:
bs.append(0)
assert len(us) == len(bs)
return bs
def union(set1,set2) :
finalSet = set()
bitList1 = set2bits(set1, U)
bitList2 = set2bits(set2, U)
for i in range(len(U)) :
if(bitList1[i] or bitList2[i]) :
finalSet.add(i)
return finalSet
def intersection(set1,set2) :
finalSet = set()
bitList1 = set2bits(set1, U)
bitList2 = set2bits(set2, U)
for i in range(len(U)) :
if(bitList1[i] and bitList2[i]) :
finalSet.add(i)
return finalSet
def compliment(set1) :
finalSet = set()
bitList = set2bits(set1, U)
for i in range(len(U)) :
if(not bitList[i]) :
finalSet.add(i)
return finalSet
def implication(a,b):
return union(compliment(a), b)
###########################################################################################
###################### Problems 1-6 #######################################
###########################################################################################
#p \/ (q /\ r) = (p \/ q) /\ (p \/ r)
def prob1():
return union(P, intersection(Q,R)) == intersection(union(P,Q), union(P,R))
#p /\ (q \/ r) = (p /\ q) \/ (p /\ r)
def prob2():
return intersection(P, union(Q,R)) == union(intersection(P,Q), intersection(P,R))
#~(p /\ q) = ~p \/ ~q
def prob3():
return compliment(intersection(P,R)) == union(compliment(P), compliment(R))
#~(p \/ q) = ~p /\ ~q
def prob4():
return compliment(union(P,Q)) == intersection(compliment(P), compliment(Q))
#(p=>q) = (~q => ~p)
def prob5():
return implication(P,Q) == implication(compliment(Q), compliment(P))
#(p => q) /\ (q => r) => (p => r)
def prob6():
return implication(intersection(implication(P,Q), implication(Q,R)), implication(P,R))
print("Problem 1: ", prob1())
print("Problem 2: ", prob2())
print("Problem 3: ", prob3())
print("Problem 4: ", prob4())
print("Problem 5: ", prob5())
print("Problem 6: ", prob6())
'''
Problem 1: True
Problem 2: True
Problem 3: True
Problem 4: True
Problem 5: True
Problem 6: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
'''

Untitled

Jun 16, 2024lagiath

0 likes • 1 view

print('hello, world')