Python Coding Practice
0 of 44 passed
Continue practiceFundamentals
- Add a Delivery ChargePython Variables and Data TypesWrite calculate_order_total(price_text, delivery_charge). Convert the valid numeric price text to a number, add the delivery charge, and return the total.
- Check Free DeliveryPython OperatorsWrite is_free_delivery(order_total, is_member). Return True when the order total is at least Rs. 75 or the customer is a member; otherwise return False.
- Normalize a UsernamePython Strings and String MethodsWrite normalize_username(username). Remove whitespace from both ends and return the username in lowercase. Keep internal spaces and punctuation unchanged.
- Format a Purchase MessagePython Input, Output & CommentsWrite format_purchase_message(name, item, price). Return a sentence in this exact format: Name bought a item for Rs. 10.56. Show price with exactly two digits after the decimal point.
- Describe JSON Value TypesPython Variables and Data TypesDifficulty: beginnerReturn the Python type name of each value in values, preserving order. Inputs are JSON values: integers, non-integral floats, booleans, strings, lists, dictionaries and None. Use type(value).__name__; booleans must remain bool rather than int.
- Split Signed Time OffsetsPython OperatorsDifficulty: beginnerConvert a signed integer number of minutes relative to a schedule into [whole_hours, remaining_minutes]. Use floor division and modulo by 60, so the remainder is always between 0 and 59. For example, -1 minute is [-1, 59].
- Redact a Contact NumberPython Strings and String MethodsDifficulty: beginnerKeep only decimal digits from the phone string using str.isdecimal(), then mask every digit except the final four with *. Preserve the final digits exactly, including Unicode decimal digits. Numbers with four or fewer digits are unchanged; text with no digits returns an empty string.
Data Structures
- Find the Top-Scoring SubjectPython Lists and List MethodsWrite top_scoring_subject(subjects, scores). The lists have the same non-zero length. Return the subject at the highest score; if scores tie, return the first matching subject.
- Average a List of MarksPython Lists and List MethodsWrite average_marks(marks). The list contains at least one numeric mark. Return the arithmetic average without rounding it.
- Find the Highest-Paid EmployeePython Tuples and Tuple MethodsWrite highest_paid_employee(names, salaries). The lists have the same non-zero length, and matching indexes belong to the same employee. Return [name, salary] for the highest-paid employee; use the first employee when salaries tie.
- List Unique Shop ItemsPython Sets and Set MethodsWrite sorted_unique_items(items). The input contains lowercase item names. Return each distinct name once, sorted in ascending alphabetical order.
- Read a Student GradePython Dictionaries and Dictionary MethodsWrite read_student_grade(student, default_grade). Return the value for the grade key when it exists; otherwise return default_grade.
- Rotate a Reading ListPython Lists and List MethodsDifficulty: beginnerReturn a new list rotated left by steps positions without changing item order within each part. Negative steps rotate right. Wrap steps modulo the list length, preserve duplicates and return [] for an empty list.
- Merge Student Record UpdatesPython Dictionaries and Dictionary MethodsDifficulty: intermediateMerge two lists of student dictionaries by their string id. Process earlier before newer; later fields override only fields supplied, including explicit None values. Retain other fields, merge repeated ids within either list, and return records sorted by id. Every record has an id.
- Compare Two Study Topic SetsPython Sets and Set MethodsDifficulty: beginnerReturn a dictionary with common, only_left and only_right topic lists. Use set intersection and differences; ignore duplicate topics and sort each output list alphabetically. Topic names are case-sensitive strings.
- Find a Delivery Window OverlapPython Tuples and Tuple MethodsDifficulty: beginnerEach delivery window is a two-item list [start, end] of integer minutes, treated as an inclusive interval. Unpack each pair and return the overlapping [start, end], or None if the windows do not overlap or either has start greater than end. Touching endpoints count as an overlap.
Control Flow
- Set an Event Ticket PricePython Conditional StatementsWrite get_ticket_price(age, is_student). Ages under 5 are free; ages 5 through 17 cost Rs. 6; adults who are students pay Rs. 8; other adults pay Rs. 12. Age is a non-negative integer.
- Sum Two NumbersPython Function BasicsWrite a Python function named sum_numbers(a, b) that returns the sum of two numbers. Check your function with positive, negative, and mixed values.
- Fahrenheit to CelsiusPython Function BasicsWrite a Python function named to_celsius(fahrenheit) that converts Fahrenheit to Celsius using (F - 32) / 1.8 and returns the result. Try freezing, room, and boiling temperatures.
- Greet a StudentPython Function BasicsWrite greet_student(name, course='Python'). Return 'Hello, {name}, Welcome to {course} class'. Use Python's default argument when no course is provided.
- Count Passing ScoresPython LoopsWrite count_passing_scores(scores, pass_mark). Return how many scores are greater than or equal to pass_mark. Return 0 for an empty list.
- Summarize Shop OrdersPython LoopsWrite summarize_orders(orders). Each order has quantity and unit_price. Return a dictionary with total_units and revenue; an empty list returns zero for both values.
- Filter Words by LengthAdvanced Python FunctionsWrite filter_words_by_length(words, minimum_length). Use filter() to return words whose length is at least minimum_length, keeping their original order.
- Check Gregorian Leap YearsPython Conditional StatementsDifficulty: beginnerReturn whether an integer year is a Gregorian leap year. Positive years divisible by 4 qualify, except century years must also be divisible by 400. Return False for year 0 or negative years.
- Build Running Account BalancesPython LoopsDifficulty: beginnerStart with an integer balance in cents and apply each signed transaction in order. Return the balance after each transaction, excluding the initial balance. Negative balances are allowed; an empty transaction list returns [].
- Compress Consecutive Sensor StatesPython LoopsDifficulty: intermediateCompress a list of sensor-state strings into [state, count] pairs for consecutive runs. Preserve run order: equal states separated by a different state must stay in separate runs. Empty input returns []. Empty strings are valid states.
- Compose Score Transformation FunctionsAdvanced Python FunctionsDifficulty: intermediateApply named transformations to each numeric score in the given order: double multiplies by 2, negate changes its sign, and square multiplies it by itself. Use functions with map/reduce or equivalent composition. Return None for any unknown step; no steps returns the original values as a list. Use only small scores whose results remain finite JSON numbers.
- Consume a Record Batch GeneratorPython Iterators and GeneratorDifficulty: intermediateUse a generator to yield consecutive batches of at most size records, and return its batches as a list of lists. Preserve order and include a final short batch. An empty record list returns []; a non-positive integer size returns None.
- Read a Fibonacci Generator PrefixPython Iterators and GeneratorDifficulty: intermediateBuild a Fibonacci generator starting with 0, 1 and return its first count values as a list. Non-positive counts return []. Inputs are integers no greater than 40 so every result fits the browser engine JSON number range. Consume only the requested prefix, for example with itertools.islice.
File, Error, OOP
- Convert Phone Records to RowsPython File HandlingWrite phone_records_to_rows(contacts). Each dictionary key is a phone number and each value has name, age, and course. Return a list of records with those fields plus phone, preserving input order.
- Handle Invalid Density InputsError HandlingWrite safe_density(mass, volume). Return mass divided by volume; use try/except to return None when the input types cannot be divided or volume is zero.
- Build a Car ClassObject Oriented ProgrammingDefine Car with brand, model, and a color that defaults to blue. Its display_info(), start_engine(), and stop_engine() methods return the specified car details. car_messages(brand, model, color='blue') must return those three messages in that order.
- Override Animal SoundsObject Oriented ProgrammingDefine Animal.speak() to return 'Animal speaks'. Dog and Cat must inherit from Animal and override speak() to return 'Dog barks' and 'Cat meows'. make_animal_sounds(types) returns each sound in input order; accepted types are animal, dog, and cat.
- Read UTF-8 Note File StatisticsPython File HandlingDifficulty: intermediateWrite text into a UTF-8 file inside a temporary directory, then open and read it with a context manager. Return lines, words and characters counts. Lines follow str.splitlines() (a final newline adds no extra empty line); words follow str.split(); characters count Unicode code points. Preserve newline characters by opening with newline="". Do not leave files behind.
- Aggregate a CSV Stock ManifestPython File HandlingDifficulty: intermediateUse csv.DictReader on the supplied CSV text with required product and quantity headers. Return total integer quantities by trimmed product name. Combine repeated products, support quoted commas, and skip rows with blank products, invalid integer quantities or negative quantities. Zero is valid. Missing required headers returns None; headers with no data returns {}.
- Parse a Bounded Integer SettingError HandlingDifficulty: beginnerConvert value into an integer using int(). Return it only when minimum <= number <= maximum; otherwise return None. Catch TypeError and ValueError for invalid values. Return None if minimum exceeds maximum. Values are strings or None and bounds are integers.
- Operate an Encapsulated Savings AccountObject Oriented ProgrammingDifficulty: intermediateComplete SavingsAccount deposit and withdraw methods in the starter class. Initial balance is non-negative integer cents. Accept only positive deposits and withdrawals no greater than the balance; rejected operations leave it unchanged. Unknown operation names are rejected. Return balance and an accepted boolean for each [operation, amount] pair through the provided wrapper.
- Read Validated JSON PreferencesPython File HandlingDifficulty: intermediateParse JSON preferences and return exactly theme and notifications. Defaults are {"theme":"light","notifications":True}. Accept only theme strings light/dark and actual boolean notifications; invalid fields keep their defaults. Ignore unknown keys. Invalid JSON or a non-object root returns both defaults.
Library, SQL, Git
- Find HCF and LCMPython LibrariesWrite hcf_and_lcm(numbers) for a non-empty list of positive integers. Return a two-item list containing the HCF first and LCM second, using Python's math library.
- Find Days Between DatesPython LibrariesWrite days_between_dates(start_date, end_date). Both strings use YYYY-MM-DD. Return the signed number of days from start_date to end_date; an earlier end date gives a negative result.
- Calculate Boxes NeededPython LibrariesWrite boxes_needed(item_count, box_capacity). Return the number of boxes needed when items are packed into boxes of the given positive capacity. Zero items need zero boxes.
- Group Valid Event Dates by MonthPython LibrariesDifficulty: intermediateCount valid event dates by YYYY-MM and return a dictionary of month counts. Each valid date must be an exact ASCII YYYY-MM-DD string representing a real Gregorian date. Use datetime parsing; skip invalid dates, non-string entries and other formats. Count duplicates as separate events.
- Rank Frequent Error CodesPython LibrariesDifficulty: intermediateCount error-code strings with collections.Counter or equivalent counting. Return up to limit [code, count] pairs ordered by descending count, then alphabetically by code when counts tie. Empty input or a non-positive integer limit returns []. Codes are case-sensitive.
- Plan Ordered Study SessionsProjectsDifficulty: advancedBuild study sessions from ordered {name, minutes} tasks and a positive integer session budget. Fill each session before starting the next; split long tasks across sessions while preserving task order and names. Return a list of sessions, each a list of {name, minutes} portions. Ignore zero/negative task durations. Empty tasks returns []; non-positive budget returns None.