## Compute all the Permutation of a String

0 likes • May 31, 2023 • 0 views
Python

## More Python Posts

#### Find Coin

0 likes • Oct 4, 2023 • 9 views
Python
`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]))`

#### primes numbers finder

0 likes • Mar 12, 2021 • 1 view
Python
```prime_lists=[] # a list to store the prime numbers
def prime(n): # define prime numbers    if n <= 1:        return False    # divide n by 2... up to n-1    for i in range(2, n):        if n % i == 0:  # the remainder should'nt be a 0            return False    else:        prime_lists.append(n)        return True

for n in range(30,1000):  # calling function and passing starting point =30 coz we need primes >30    prime(n)
check=0 # a var to limit the output  to 10 onlyfor n in prime_lists:    for x in prime_lists:        val=  n *x        if (val > 1000 ):            check=check +1        if (check <10) :            print("the num is:", val , "=",n , "* ", x )        break```

#### UNT CSCE 2100 Assignment 6

0 likes • Nov 18, 2022 • 0 views
Python
```"""Assignment 6
The goal is to make a graph ofwho bit who and who was bitten.There should be 10 nodes and 15 edges.3 arrows of biting each other and3 arrows of someone biting themselves.Networkx can not do self bitingarrows, but it is in the code."""
from graphviz import Digraph as DDotGraphfrom graphviz import Graph as UDotGraphimport networkx as nxfrom networkx.algorithms.dag import transitive_closureimport graphviz as gvimport matplotlib.pyplot as pltimport numpy as npfrom numpy.linalg import matrix_power
"""class DGraph:    def __init__(self):        self.d = dict()
def clear(self):        self.d = dict()
def add_node(self,n):        if not self.d.get(n):            self.d[n] = set()
def edges(self):        for f in self.d:            for t in self.d[f]:                yield (f,t)
def number_of_nodes(self):        return len(self.d)
def __repr__(self):        return self.d.__repr__()
def show(self):        dot = gv.Digraph()        for e in self.edges():            #print(e)            f, t = e            dot.edge(str(f), str(t), label='')        #print(dot.source)        show(dot)
# displays graph with graphvizdef show(dot, show=True, file_name='graph.gv'):    dot.render(file_name, view=show)

def showGraph(g,label="",directed=True):    if directed:        dot = gv.Digraph()    else:        dot = gv.Graph()
for e in g.edges():        print(e)        f, t = e        dot.edge(str(f), str(t), label=label)    print(dot.source)    show(dot)

bit()
#bitten()
T = transitive_closure(D)
for e in D.edges(): print(e)for n in D.nodes(): print(n)
# M = nx.adjacency_matrix(D)# MT = nx.adjacency_matrix(T)M = nx.to_numpy_matrix(D)MT = nx.to_numpy_matrix(T)M2 = M@M
def mPower(M, k): #M is numpy matrix    assert k >= 1    P = M    for _ in range(k):       P = P @ M    return P
def tc(M):    #compute transitive closure    pass
D1 = nx.DiGraph(M)D2 = nx.DiGraph(M2)
print('Matrix for Original\n', M)N = nx.to_numpy_array(D,dtype=int)print('np_array for Original\n', N)print('\nMatrix for Transitive Closure\n', MT)N2 = nx.to_numpy_array(T,dtype=int)print('np_array for Transitive Closure\n', N2)
show(D) #can use D, T, and numpy matrix power operationshow(T)show(T)```

0 likes • Nov 18, 2022 • 0 views
Python
```import os, json, boto3, requestsfrom flask import Flask, request, jsonifyfrom flask_cors import CORS, cross_originfrom random import shuffle
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.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("/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")    }
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"):
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)
@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)```
```class Rectangle:    pass
class Square(Rectangle):    pass
rectangle = Rectangle()square = Square()
print(isinstance(rectangle, Rectangle))  # Trueprint(isinstance(square, Rectangle))     # Trueprint(isinstance(square, Square))        # Trueprint(isinstance(rectangle, Square))     # False```

#### hex to rgb

0 likes • Nov 19, 2022 • 2 views
Python
```def hex_to_rgb(hex):  return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))
hex_to_rgb('FFA501') # (255, 165, 1)```