No title

 def get_unique_reasons(students):

    # Extract all reasons (comma-separated), strip spaces, and flatten

    all_reasons = map(

        lambda r: [reason.strip() for reason in r['Reason'].split(',')],

        students

    )

    

    # Flatten the list of lists

    flat_reasons = [reason for sublist in all_reasons for reason in sublist]

    

    # Get unique values using set, then return sorted list

    return sorted(set(flat_reasons))


15

def get_students_with_total_scores(students):

    def add_total_score(student):

        total = student['math_score'] + student['reading_score'] + student['writing_score']

        # create a copy so original list is not modified

        student_with_total = dict(student)

        student_with_total['total_score'] = total

        return student_with_total


    # Apply map to compute totals

    students_with_total = list(map(add_total_score, students))

    

    # Sort by total_score in descending order

    return sorted(students_with_total, key=lambda x: x['total_score'], reverse=True


ails)))


26

def get_mobile_details(mobile_details):

    def cleanup_keys(mobile):

        # Remove "mobile_" from the beginning of each key

        return {key.replace("mobile_", ""): value for key, value in mobile.items()}

    

    # Apply cleanup_keys to each dict using map

    return list(map(cleanup_keys, mobile_details))


def get_companies_per_sector(companies):

    companies_per_sector = {}

    for company, sector in companies.items():

        if sector not in companies_per_sector:

            companies_per_sector[sector] = []

        companies_per_sector[sector].append(company)

    return companies_per_sector

15

def get_companies_with_attrs(companies, fields):

    # Split the fields string into a list

    field_list = fields.split(",")

    

    companies_with_attrs = []

    

    for company in companies:

        values = company.split(",")

        # Convert numeric values to float if possible

        converted_values = [

            float(v) if i >= 2 else v # from 3rd field onwards: numeric

            for i, v in enumerate(values)

        ]

        # Pair fields with values using zip

        company_dict = dict(zip(field_list, converted_values))

        companies_with_attrs.append(company_dict)

    

    return companies_with_attrs


28

import csv

from datetime import datetime


def get_aspirants_by_scheduled_date(file_path, scheduled_date):

    # Parse the input date in YYYY-MM-DD format

    scheduled_dt = datetime.strptime(scheduled_date, "%Y-%m-%d").date()


    with open(file_path, "r", encoding="utf-8") as f:

        reader = csv.DictReader(f, delimiter="\t")

        

        # Extract only relevant fields and filter by date

        filtered = []

        for row in reader:

            # Convert date in file to date object (supports mm/dd/YYYY or m/d/YYYY)

            row_date = datetime.strptime(row["Schedule Date"].strip(), "%m/%d/%Y").date()

            

            if row_date == scheduled_dt:

                name = row["Name"].strip()

                rating = int(row["Rating"].strip())

                country = row["Country"].strip()

                schedule_date = row["Schedule Date"].strip() # keep original format like 8/1/2021

                filtered.append((name, rating, country, schedule_date))

        

        # Sort by country, then by name

        filtered_sorted = sorted(filtered, key=lambda x: (x[2], x[0]))

        

        return filtered_sorted


29.

def write_bike_details(attributes, bike_details, target_file, delimiter='\t'):

    # Sort bike details by year first, then by name

    sorted_bikes = sorted(bike_details, key=lambda x: (x[2], x[0]))

    

    with open(target_file, "w", encoding="utf-8") as f:

        # Write header

        f.write(delimiter.join(attributes) + "\n")

        

        # Write bike details

        for bike in sorted_bikes:

            f.write(delimiter.join(map(str, bike)) + "\n")


30. import csv

from datetime import datetime


def get_aspirants_by_reason(file_path, reason):

    aspirants = []

    

    with open(file_path, "r", encoding="utf-8") as f:

        reader = csv.DictReader(f, delimiter="\t")

        

        for row in reader:

            # Check if reason is present in the "Reason" field (comma-separated)

            reasons = [r.strip() for r in row["Reason"].split(",")]

            if reason in reasons:

                aspirants.append({

                    "Name": row["Name"].strip(),

                    "Scheduled Date": row["Schedule Date"].strip()

                })

    

    # Sort by Scheduled Date (as date) then by Name

    aspirants_sorted = sorted(

        aspirants,

        key=lambda x: (

            datetime.strptime(x["Scheduled Date"], "%m/%d/%Y"),

            x["Name"]

        )

    )

    

    return aspirants_sorted

20

import csv

from datetime import datetime


def get_unique_dates(file_path):

    dates = set()

    

    with open(file_path, "r", encoding="utf-8") as f:

        reader = csv.DictReader(f, delimiter="\t")

        for row in reader:

            dates.add(row["Scheduled Date"].strip())

    

    # Sort chronologically but keep original string format

    sorted_dates = sorted(

        dates,

        key=lambda d: datetime.strptime(d, "%m/%d/%Y")

    )

    

    return sorted_dates


22. def get_companies_by_dividend_payout(companies):

    # Separate companies into dividend paying and non-dividend paying

    non_dividend = list(filter(lambda c: c["Dividend"] == 0, companies))

    dividend = list(filter(lambda c: c["Dividend"] > 0, companies))

    

    # Sort non-dividend paying by share price

    non_dividend_sorted = sorted(non_dividend, key=lambda c: c["Price"])

    

    # Sort dividend paying by dividend first, then share price

    dividend_sorted = sorted(dividend, key=lambda c: (c["Dividend"], c["Price"]))

    

    # Return dictionary as required

    companies_by_dividend_payout = {

        "Non Dividend Paying": non_dividend_sorted,

        "Dividend Paying": dividend_sorted

    }

    

    return companies_by_dividend_payout


23

import csv


def get_company_with_no_dividends(path):

    with open(path, 'r') as f:

        reader = csv.reader(f)

        next(reader) # skip header


        # Convert each row into a tuple with correct types

        companies = map(

            lambda r: (r[0], r[1], float(r[2]), float(r[3]), float(r[4])),

            reader

        )


        # Filter companies where dividend == 0

        zero_dividend_companies = filter(lambda c: c[3] == 0.0, companies)


        # Sort by company name (case sensitive)

        companies_with_zero_dividend = sorted(zero_dividend_companies, key=lambda c: c[0])


        return companies_with_zero_dividend


24

import csv


def get_name_and_category(path):

    with open(path, 'r') as f:

        reader = csv.DictReader(f)

        

        # Pick only Name and Sector into dicts

        companies = map(lambda r: {"Name": r["Name"], "Sector": r["Sector"]}, reader)

        

        # Sort by Sector first, then case-insensitive Name

        companies_sorted = sorted(companies, key=lambda c: (c["Sector"], c["Name"].lower()))

        

        return companies_sorted

Previous Post Next Post