## return multiple values from a function

0 likes • Jun 1, 2023 • 0 views
Python

## More Python Posts

#### when predicate lambda

0 likes • Nov 19, 2022 • 0 views
Python
```def when(predicate, when_true):  return lambda x: when_true(x) if predicate(x) else x
double_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)print(double_even_numbers(2)) # 4print(double_even_numbers(1)) # 1```

0 likes • Nov 19, 2022 • 0 views
Python
`#Loop back to this point once code finishesloop = 1while (loop < 10):#All the questions that the program asks the user    noun = input("Choose a noun: ")    p_noun = input("Choose a plural noun: ")    noun2 = input("Choose a noun: ")    place = input("Name a place: ")    adjective = input("Choose an adjective (Describing word): ")    noun3 = input("Choose a noun: ")#Displays the story based on the users input    print ("------------------------------------------")    print ("Be kind to your",noun,"- footed", p_noun)    print ("For a duck may be somebody's", noun2,",")    print ("Be kind to your",p_noun,"in",place)    print ("Where the weather is always",adjective,".")    print ()    print ("You may think that is this the",noun3,",")    print ("Well it is.")    print ("------------------------------------------")#Loop back to "loop = 1"    loop = loop + 1`

#### two-digit integer

0 likes • Feb 26, 2023 • 0 views
Python
`#You are given a two-digit integer n. Return the sum of its digits.#Example#For n = 29 the output should be solution (n) = 11def solution(n):    return (n//10 + n%10)`

#### Create a Pascal’s Triangle

0 likes • May 31, 2023 • 0 views
Python
```def generate_pascals_triangle(num_rows):    triangle = []    for row in range(num_rows):        # Initialize the row with 1        current_row = [1]
# Calculate the values for the current row        if row > 0:            previous_row = triangle[row - 1]            for i in range(len(previous_row) - 1):                current_row.append(previous_row[i] + previous_row[i + 1])
# Append 1 at the end of the row        current_row.append(1)
# Add the current row to the triangle        triangle.append(current_row)
return triangle

def display_pascals_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 Pascal's Triangle: "))
# Generate Pascal's Trianglepascals_triangle = generate_pascals_triangle(num_rows)
# Display Pascal's Triangledisplay_pascals_triangle(pascals_triangle)```

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)
```def hex_to_rgb(hex):  return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))