COSC 145: Python Fundamentals and Applied Logic

Python Functions, Methods, and Sequence Operations

  • Functions Versus Methods:

    • Functions are independent, reusable blocks of code that operate on data passed to them as arguments and do not belong to a specific object type. Examples include sorted(), min(), sum(), and len().

    • Methods are functions that are tied directly to an object or class and are invoked using dot notation (object.method()). Different objects have different available methods; for instance, string objects provide methods such as s.title() or t.title() to manipulate text data.

  • Behavior of the Built-In sorted() Function:

    • The sorted() function creates and returns a new sorted copy of an iterable without modifying the original data structure in place.

    • Sorting a List of Strings: When invoked on a list of words, sorted() arranges the elements in ascending lexicographical (alphabetical) order:

    • Code example: x = sorted(["oozy", "rat", "in", "a", "sanitary", "zoo"])

    • Evaluated result: ['a', 'in', 'oozy', 'rat', 'sanitary', 'zoo']

    • Sorting a Single-Element List: If a list contains only one string element, sorting evaluates that list directly:

    • Code example: x = sorted(["abracadabra"])

    • Evaluated result: ['abracadabra']

    • Sorting a String Literal Directly: When passed a single string literal, sorted() treats the string as a sequence of individual characters and returns a list containing all characters sorted by ASCII/Unicode code points (spaces come first, followed by uppercase letters, then lowercase letters):

    • Code example: print(sorted("I am a camera"))

    • Characters breakdown: three spaces ' ', one uppercase 'I', three lowercase 'a', one 'c', one 'e', one 'm', and one 'r'.

    • Evaluated output: [' ', ' ', ' ', 'I', 'a', 'a', 'a', 'c', 'e', 'm', 'r']

  • Structural Differences: ["abracadabra"] Versus "abracadabra":

    • ["abracadabra"] is a list containing a single element, where that element is the string "abracadabra". Its length (len()) is equal to 11.

    • "abracadabra" is a string primitive consisting of an ordered sequence of 1111 characters. Its length (len()) is equal to 1111.

  • Iterative Accumulation and Reduction Algorithms:

    • Iterative Summation (sum()) Implementation:

    • The built-in sum() function returns the total sum of all numerical values in an iterable (e.g., sum([1.5, 6, 8]) outputs 15.515.5).

    • To implement this behavior manually using a for loop across an array or list array:

      • Initialize an accumulator variable to zero: total_sum = 0

      • Iterate over every element: for k in array:

      • Accumulate the current value: total_sum = total_sum + k

      • Output the final accumulated result: print(total_sum)

    • Iterative Minimum (min()) Implementation:

    • The built-in min() function determines the smallest item in an iterable (e.g., min([1.5, 6, 8, 0]) outputs 00).

    • To replicate min() manually with a for loop on a list of numbers named numbers:

      • Assume the first element is the initial minimum: current_min = numbers[0]

      • Iterate through the sequence: for item in numbers:

      • Compare each element: if item < current_min: current_min = item

      • Output the minimum: print(current_min)

    • Handling a List of Strings in Minimum Search:

    • To find the minimum of a list of strings, the identical algorithm is used without any syntax modifications.

    • In Python, comparison operators (<, >, <=, >=) apply lexicographical ordering based on character Unicode values. Thus, item < current_min correctly identifies the alphabetically earliest string.

Iteration and Algorithmic Logic Patterns

  • Perfect Square Detection:

    • A number is a perfect square if its square root is an integer. To evaluate whether a user-entered number is a perfect square:

    • Prompt the user for an integer: n = int(input("Enter a number: "))

    • Calculate the square root: root = n ** 0.5

    • Check if the square of the integer conversion matches the original number:

      • If int(root) ** 2 == n and n >= 0, display "yes" (e.g., inputs of 11 or 2525).

      • Otherwise, display "no".

  • Character Counting via String Traversal:

    • To count occurrences of a specific character (such as whitespace) within a string:

    • Read the string from user input: text = input("Enter a string: ")

    • Initialize a counter: space_count = 0

    • Traverse each character using a for loop: for ch in text:

    • Check equality with a space literal: if ch == " ": space_count = space_count + 1

    • Print the counter: print(space_count) (e.g., evaluating "I am a camera" results in 33 spaces).

  • Input Validation Loops:

    • Input validation protects program logic by repeatedly requesting input until the value satisfies specified domain constraints.

    • To validate that a number is strictly positive and strictly less than 10001000 (0<number<10000 < \text{number} < 1000):

    • Read the initial value: num = float(input("Enter a positive number less than 1000: "))

    • Construct a while loop that continues while the input is invalid (\text{num} \ngle 0 or \text{num} \nge 1000):

      • while num <= 0 or num >= 1000:

      • Prompt again: num = float(input("Invalid entry. Re-enter number: "))

    • Once the loop terminates, the program proceeds with the valid number.

  • Discrete Step Accumulation (Treadmill Calorie Calculation):

    • When running on a treadmill, an individual burns 4.2 calories per minute4.2\,\text{calories per minute}.

    • To display total calories burned after intervals of 1010, 1515, 2020, 2525, and 30 minutes30\,\text{minutes}:

    • Pseudocode implementation using a for loop with a step size of 55:

      • for minutes in range(10, 35, 5):

      • Calculate calories burned: calories = minutes * 4.2

      • Display results: print(f"{minutes} minutes: {calories} calories burned")

    • Calculated values:

      • 10 minutes×4.2 cal/min=42.0 calories10\,\text{minutes} \times 4.2\,\text{cal/min} = 42.0\,\text{calories}

      • 15 minutes×4.2 cal/min=63.0 calories15\,\text{minutes} \times 4.2\,\text{cal/min} = 63.0\,\text{calories}

      • 20 minutes×4.2 cal/min=84.0 calories20\,\text{minutes} \times 4.2\,\text{cal/min} = 84.0\,\text{calories}

      • 25 minutes×4.2 cal/min=105.0 calories25\,\text{minutes} \times 4.2\,\text{cal/min} = 105.0\,\text{calories}

      • 30 minutes×4.2 cal/min=126.0 calories30\,\text{minutes} \times 4.2\,\text{cal/min} = 126.0\,\text{calories}

Code Debugging, Syntax Rules, and Error Corrections

  • Hundreds Digit Extraction:

    • Problem: Extract and print the hundreds digit of a number with at least three digits (e.g., the digit 44 in 14921492, or the digit 33 in 86753098675309).

    • Buggy Code Snippet: python # Read the number from the user the_number = float(input("Enter a number with at least three digits: ")) # Get last three digits last_three_digits = the_number % 1000 # Drop last two digits answer = (last_three_digits / 100) print(f"answer: {answer}") &nbsp;&nbsp;&nbsp;&nbsp;

  • Identified Errors & Analysis:

    • Type Error: Reading the number with float() introduces fractional representations when working with discrete integer digits. Input should be converted with int().

    • Division Error: Floating-point true division (/) yields a float with decimals rather than an isolated integer digit. For example, 492/100=4.92492 / 100 = 4.92 instead of the integer 44.

    • Truncation/Division Operator: Integer floor division (//) must be utilized to discard the remaining two digits.

  • Corrected Implementation: python the_number = int(input("Enter a number with at least three digits: ")) last_three_digits = the_number % 1000 answer = last_three_digits // 100 print(f"answer: {answer}") &nbsp;&nbsp;&nbsp;&nbsp;

  • Centimeters to Inches Conversion:

    • Problem: Convert a user-provided length in centimeters into inches, given the constant 2.54 centimeters per inch2.54\,\text{centimeters per inch}.

    • Buggy Code Snippet: python # Read the number from the user inches = float(input('Inches = ' # Remember that there are 2.54 centimeters/inch centimeters = inches * 2.54 print(f"{inches} inches is {centimeters} centimeters") &nbsp;&nbsp;&nbsp;&nbsp;

  • Identified Errors & Analysis:

    • Syntax Error: The input line is unclosed; it is missing closing parentheses )) to match float( and input(.

    • Logical Reversal: The problem mandates reading centimeters and converting to inches (inches=cm2.54\text{inches} = \frac{\text{cm}}{2.54}), but the code reads inches and multiplies by 2.542.54.

  • Corrected Implementation: python cm = float(input("Centimeters is: ")) inch = cm / 2.54 print(f"{cm} centimeters is {inch} inches.") &nbsp;&nbsp;&nbsp;&nbsp;

  • Weekend Classification and Operator Syntax:

    • Problem: Read a day number where Sunday is 11 through Saturday as 77, and output whether the day falls on a weekend (11 or 77) or weekday (22 through 66).

    • Buggy Code Snippet: python daynum = int(input('What day is it? ')) If (daynum = 1 or daynum = 7): print("Weekend!") else: print("Weekday.") &nbsp;&nbsp;&nbsp;&nbsp;

  • Identified Errors & Analysis:

    • Syntax Error (Casing): Python keywords are case-sensitive; If is capitalized and causes a syntax error. It must be lowercase if.

    • Operator Error: A single equals sign = denotes variable assignment. Equality comparisons must use the double equals operator ==.

  • Corrected Implementation: python daynum = int(input("What day is it? ")) if (daynum == 1 or daynum == 7): print("Weekend!") else: print("Weekday.") &nbsp;&nbsp;&nbsp;&nbsp;

  • Absolute Value Calculation and Colon Requirements:

    • Problem: Compute the absolute value ∣x∣|x| of an input number without using built-in abs() (if x<0x < 0, output −x-x; otherwise output xx).

    • Buggy Code Snippet: python x = float(input("Please give me a number")) if x < 0 x = x * -1 print(f"|x| is : {x}") &nbsp;&nbsp;&nbsp;&nbsp;

  • Identified Errors & Analysis:

    • Syntax Error: A colon : is mandatory following conditional statement headers (if, elif, else). Omitting the colon after if x < 0 prevents the Python interpreter from reading the block.

  • Corrected Implementation: python x = float(input("Please give me a number: ")) if x < 0: x = x * -1 print(f"|x| is : {x}") &nbsp;&nbsp;&nbsp;&nbsp;

Applied Algorithmic Decision Problems

  • Body Mass Index (BMI) Health Classification:

    • Mathematical Formula:     BMI=weight (in kg)(height (in m))2\text{BMI} = \frac{\text{weight (in kg)}}{(\text{height (in m)})^2}

    • Classification Thresholds:

    • Underweight: BMI<18.5\text{BMI} < 18.5

    • Optimum Range: 18.5≤BMI≤24.918.5 \le \text{BMI} \le 24.9

    • Overweight: BMI>24.9\text{BMI} > 24.9

    • Implementation Logic: python weight = float(input("Please enter your weight: ")) height = float(input("Please enter your height: ")) BMI = weight / (height * height) if BMI < 18.5: print("You are underweight.") elif BMI >= 18.5 and BMI <= 24.9: print("You are in the optimum range.") else: print("You are overweight.") &nbsp;&nbsp;&nbsp;&nbsp;

  • Recipe Ingredient Scaling and Batch Ceiling Rounding:

    • Base Recipe Quantities (Yield: 12 Cookies):

    • Flour: 2122\frac{1}{2} cups (2.5 cups2.5\,\text{cups}

    • Butter: 1 cup1\,\text{cup}

    • Sugar: 12\frac{1}{2} cup (0.5 cups0.5\,\text{cups}

    • Batch Logic:

    • Ingredients cannot be prepared in fractions of a batch; the total number of cookies must be rounded up to the nearest multiple of 1212.

    • If the requested quantity ncookies is cleanly divisible by 1212 (ncookies % 12 == 0), total batches equal ncookies // 12.

    • If there is any remainder (ncookies % 12 != 0), an additional full batch is required: nbatches = (ncookies // 12) + 1.

    • Implementation Logic: python ncookies = int(input("How many cookies? ")) if ncookies % 12 == 0: nbatches = ncookies // 12 else: nbatches = ncookies // 12 + 1 flour = 2.5 * nbatches butter = nbatches sugar = 0.5 * nbatches print(f"{flour} cups of flour") print(f"{butter} cups of butter") print(f"{sugar} cups of sugar") &nbsp;&nbsp;&nbsp;&nbsp;

  • Temperature Conversion and Environmental Regulation:

    • Formula:     ∘C=∘F−3295=(∘F−32)×59^\circ\text{C} = \frac{^\circ\text{F} - 32}{\frac{9}{5}} = (^\circ\text{F} - 32) \times \frac{5}{9}

    • Classification Thresholds:

    • Too Cold: ∘C<18^\circ\text{C} < 18

    • Too Hot: ∘C>23^\circ\text{C} > 23

    • Just Right: 18≤∘C≤2318 \le ^\circ\text{C} \le 23

    • Implementation Logic: python ftemp = float(input("Enter temperature: ")) ctemp = (ftemp - 32) / (9 / 5) if ctemp < 18: print("Too cold") elif ctemp > 23: print("Too hot") else: print("Just right") &nbsp;&nbsp;&nbsp;&nbsp;

  • Demographic Workforce Percentage Analysis:

    • Problem: Accept employee counts across five distinct racial classifications and calculate their exact percentage contribution to the total workforce:

    • White (w)

    • Black or African American (b)

    • American Indian or Alaska Native (ai)

    • Asian (as_emp)

    • Native Hawaiian or Other Pacific Islander (h)

    • Mathematical Formula:     Total=w+b+ai+as_emp+h\text{Total} = w + b + ai + as\_emp + h     Percentagegroup=Group CountTotal×100.0\text{Percentage}_{\text{group}} = \frac{\text{Group Count}}{\text{Total}} \times 100.0

    • Implementation Logic: python w = int(input("Enter number of White employees: ")) b = int(input("Enter number of Black/AA employees: ")) ai = int(input("Enter number of American Indian/AN employees: ")) as_emp = int(input("Enter number of Asian employees: ")) h = int(input("Enter number of Native Hawaiian/OPI employees: ")) total = w + b + ai + as_emp + h wpercent = (w / total) * 100.0 bpercent = (b / total) * 100.0 aipercent = (ai / total) * 100.0 aspercent = (as_emp / total) * 100.0 hpercent = (h / total) * 100.0 print(f"White: {wpercent}%") print(f"Black/AA: {bpercent}%") print(f"American Indian/AN: {aipercent}%") print(f"Asian: {aspercent}%") print(f"NH/OPI: {hpercent}%") &nbsp;&nbsp;&nbsp;&nbsp;

  • Weekly Schedule Multi-Condition Mapping:

    • Activity Rules:

    • Martial arts class: Monday, Tuesday, Thursday, Saturday

    • Day classes: Monday, Wednesday, Friday

    • Night class: Wednesday

    • Game playing: Monday, Thursday

    • Home maintenance: Saturday, Sunday (weekends)

    • Control Flow Architecture:

    • Because a single day can involve multiple non-exclusive tasks (for example, Wednesday involves both day and night classes), independent if statements must be evaluated sequentially rather than using mutual exclusion (elif/else).

    • Implementation Logic: python day = input("Enter the day: ") if day == "Monday" or day == "Tuesday" or day == "Thursday" or day == "Saturday": print("Martial arts class") if day == "Monday" or day == "Wednesday" or day == "Friday": print("Day classes") if day == "Wednesday": print("Night class") if day == "Monday" or day == "Thursday": print("Game playing") if day == "Saturday" or day == "Sunday": print("Home maintenance") &nbsp;&nbsp;&nbsp;&nbsp;

  • Integer Divisibility Testing:

    • Divisibility Definition: An integer nn is evenly divisible by a divisor dd if the remainder after division is zero (n(modd)==0n \pmod d == 0).

    • Testing for Divisibility by 55, 1111, or Both:

    • Method 1 (Independent Evaluations): python n = int(input("Enter the number: ")) if n % 5 == 0: print("Divisible by 5") if n % 11 == 0: print("Divisible by 11") &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Method 2 (Mutually Exclusive Hierarchy with Joint Condition First): python n = int(input("Enter the number: ")) if n % 5 == 0 and n % 11 == 0: print("Divisible by both 5 and 11") elif n % 11 == 0: print("Divisible by 11") elif n % 5 == 0: print("Divisible by 5") &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;