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(), andlen().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 ass.title()ort.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 ."abracadabra"is a string primitive consisting of an ordered sequence of characters. Its length (len()) is equal to .
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 ).To implement this behavior manually using a
forloop across an array or listarray:Initialize an accumulator variable to zero:
total_sum = 0Iterate over every element:
for k in array:Accumulate the current value:
total_sum = total_sum + kOutput 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 ).To replicate
min()manually with aforloop on a list of numbers namednumbers: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 = itemOutput 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_mincorrectly 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.5Check if the square of the integer conversion matches the original number:
If
int(root) ** 2 == nandn >= 0, display"yes"(e.g., inputs of or ).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 = 0Traverse each character using a
forloop:for ch in text:Check equality with a space literal:
if ch == " ": space_count = space_count + 1Print the counter:
print(space_count)(e.g., evaluating"I am a camera"results in 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 ():
Read the initial value:
num = float(input("Enter a positive number less than 1000: "))Construct a
whileloop 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 .
To display total calories burned after intervals of , , , , and :
Pseudocode implementation using a
forloop with a step size of :for minutes in range(10, 35, 5):Calculate calories burned:
calories = minutes * 4.2Display results:
print(f"{minutes} minutes: {calories} calories burned")
Calculated values:
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 in , or the digit in ).
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}")
Identified Errors & Analysis:
Type Error: Reading the number with
float()introduces fractional representations when working with discrete integer digits. Input should be converted withint().Division Error: Floating-point true division (
/) yields a float with decimals rather than an isolated integer digit. For example, instead of the integer .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}") Centimeters to Inches Conversion:
Problem: Convert a user-provided length in centimeters into inches, given the constant .
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")
Identified Errors & Analysis:
Syntax Error: The input line is unclosed; it is missing closing parentheses
))to matchfloat(andinput(.Logical Reversal: The problem mandates reading centimeters and converting to inches (), but the code reads inches and multiplies by .
Corrected Implementation:
python cm = float(input("Centimeters is: ")) inch = cm / 2.54 print(f"{cm} centimeters is {inch} inches.") Weekend Classification and Operator Syntax:
Problem: Read a day number where Sunday is through Saturday as , and output whether the day falls on a weekend ( or ) or weekday ( through ).
Buggy Code Snippet:
python daynum = int(input('What day is it? ')) If (daynum = 1 or daynum = 7): print("Weekend!") else: print("Weekday.")
Identified Errors & Analysis:
Syntax Error (Casing): Python keywords are case-sensitive;
Ifis capitalized and causes a syntax error. It must be lowercaseif.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.") Absolute Value Calculation and Colon Requirements:
Problem: Compute the absolute value of an input number without using built-in
abs()(if , output ; otherwise output ).Buggy Code Snippet:
python x = float(input("Please give me a number")) if x < 0 x = x * -1 print(f"|x| is : {x}")
Identified Errors & Analysis:
Syntax Error: A colon
:is mandatory following conditional statement headers (if,elif,else). Omitting the colon afterif x < 0prevents 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}")
Applied Algorithmic Decision Problems
Body Mass Index (BMI) Health Classification:
Mathematical Formula:
Classification Thresholds:
Underweight:
Optimum Range:
Overweight:
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.")
Recipe Ingredient Scaling and Batch Ceiling Rounding:
Base Recipe Quantities (Yield: 12 Cookies):
Flour: cups (
Butter:
Sugar: cup (
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 .
If the requested quantity
ncookiesis cleanly divisible by (ncookies % 12 == 0), total batches equalncookies // 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")
Temperature Conversion and Environmental Regulation:
Formula:
Classification Thresholds:
Too Cold:
Too Hot:
Just Right:
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")
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:
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}%")
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
ifstatements 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")
Integer Divisibility Testing:
Divisibility Definition: An integer is evenly divisible by a divisor if the remainder after division is zero ().
Testing for Divisibility by , , 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")
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")