lec-06
Don't skip the "understand the problem" step.
At the very least, be able to figure out how the results in the screenshot were obtained.
Let's take a run through the rubric.
Take a look at the coding guidelines.
The big hint is a big hint, especially taken in context of lab-05....
none!
onlinequestions.org
202304170106string
type
operator
input
output
syntax
variable
f-string
Generate a reasonable sentence in your head that connects at least 2 of the terms.
Do as many sentences as you can in 1 minute.
⦾ citing stuffs
⦾ back to f-strings
⦾ constants
⦾ comments
The following content is from Patrick Perri's slides on the topic, provided with his consent.
Citing (also called referencing) is a way to acknowledge the work (ideas, images, code etc.) of others [1].
[2] “Academic Misconduct”, Office of Student Community Standards, MRU, 2022. [Online.] Available: https://www.mtroyal.ca/CampusServices/CampusResources/StudentCommunityStandards/academic-misconduct/index.htm
We cite:
[1] “Citations Styles and Resources” Mount Royal University Library, 2020, [Online.] Available: https://library.mtroyal.ca/citations
“MRU students are expected to consistently submit original work, give credit to other peoples' ideas and work and complete all submissions independently and honestly”[1].
[1] “Academic Misconduct”, Office of Student Community Standards, MRU, 2022. [Online.] Available: https://www.mtroyal.ca/CampusServices/CampusResources/StudentCommunityStandards/academic-misconduct/index.htm
What counts as misconduct?
# Finds the median of some numbers.
# Developed in conversation with S Wright (Oct 2022)
# and using ideas from:
# “Finding Mean, Median, Mode in Python without libraries”
# https://www.geeksforgeeks.org/finding-mean-median-mode-in-python-without-libraries/
theNumbers= [1, 2, 3, 4, 5]
n = len(theNumbers)
theNumbers.sort()
if n % 2 == 0:
median1 = theNumbers[n//2]
median2 = theNumbers[n//2 - 1]
median = (median1 + median2)/2
else:
median = theNumbers[n//2]
# End of S Wright and geeksforgeeks inspired code
print("My median is: " + str(median))from collections import Counter
# list of elements to calculate mode
n_num = [1, 2, 3, 4, 5, 5]
n = len(n_num)
data = Counter(n_num)
get_mode = dict(data)
mode = [k for k, v in get_mode.items() if v == max(list(data.values()))]
if len(mode) == n:
get_mode = "No mode found"
else:
get_mode = "Mode is / are: " + ', '.join(map(str, mode))
print(get_mode)
Say you were tasked to create a function to find the mode (lowest value if more than one) of a list of values, and to NOT use dictionaries, outside modules, nor list comprehensions.
Then you hand in this...
Without citation, this is 0% and a write-up.
With citation, it's "just" a 0%.
Oh look, a dictionary.
Oh look, a list comprehension.
Oh look, an outside module.
Your code must not use any Python techniques that have not yet been covered in class.
This means it cannot use:
older style string formatting (% or .format)
if/else
loops
lists, tuples, dictionaries, or other data types beyond int, float, and str
try/except
custom classes
modules aside from the math module
This is not a complete list!
|
Why not? There are many Python solutions to problems such as these out there in the wild, and if I see advanced concepts in your code, I have no way of knowing that you understand what you are writing. If you have prior Python experience, consider it a challenge to solve the problem using a limited set of tools. |
Again, without citation, doing any of these means 0% and a write-up.
With citation, it's just 0%.
This has changed - you don't need the math module.
they produce strings
this is syntactically ok, but goofy as all get-out
print(f'Why are you doing this? Stop it immediately, ya goof.')# assume we have these variables
width = 6
height = 5
area = width * heightLet's print the following 3 different ways:
The area of a 6 x 5 rectangle is 30.
print("The area of a", width, "x", height, "rectangle is", area, "\b.")🙋🏻♂️❓🙋🏻♀️How would you do it with just print()?
print("The area of a " + str(width) + " x " + str(height) + " rectangle is " + str(area) + ".")🙋🏻♂️❓🙋🏻♀️How would you do it with print() and concatenation?
print(f"The area of a {width} x {height} rectangle is {area}.")🙋🏻♂️❓🙋🏻♀️How would you do it with print() and an f-string?
JP! Show the reverse engineering method!
Yikes. Easy to make make mistakes with this mess!
So beautiful! Expressive! Life-altering!
Why? And ew.
p1_name = 'luX0R'
p1_score = 4
p2_name = 'MizKittyKitty'
p2_score = 12
print("12345678901231234567")
print(f"{'nickname':<13}{'score':>7}")
print("-" * 20)
print(f"{p1_name:<13}{p1_score:>7}")
print(f"{p2_name:<13}{p2_score:>7}")nickname score
--------------------
luX0R 4
MizKittyKitty 12
12345678901231234567
13 characters wide
7 chars wide
note everything adds up to 20
what if we remove the > here?
how about here?
Now YOU make a table that looks like this:
flight gate status -------------------------- AC203 C50 DEPARTED WS105 D75 FINAL CALL Y90153 C58 PREBOARDING
These dashes come in handy....
room_width_ft = 10
room_length_ft = 20
COST_PER_SQ_FT = 2
print(f'It will cost {room_width_ft * room_length_ft * COST_PER_SQ_FT} for that room.')In f-strings, things in { } are evaluated, then turned into strings.
Not a fan.
room_width_ft = 10
room_length_ft = 20
COST_PER_SQ_FT = 2
total_cost = room_width_ft * room_length_ft * COST_PER_SQ_FT
print(f'It will cost {total_cost} for that room.')We'll talk about this kind of CONSTANT later in the lecture.
Much better.
🙋🏻♂️❓🙋🏻♀️How could we improve the readability?
This is convenient, but can lead to hard-to-read code.
Insert Fascinating Demo Here
This one seems pretty good:
https://cheatography.com/brianallan/cheat-sheets/python-f-strings-basics/
# need to do this, or things explode
safety_valve_reading = 0
# legal department says we must do this
list_of_guarantees = ""
# uses Triangle Numbers
# https://en.wikipedia.org/wiki/Triangular_number
score = (n * (n + 1)) / 2Pro Tip
use ctrl+/ to comment and uncomment lines quickly in VS Code
num_gems_as_text = input("Enter the number of gems: ")
num_gems = int(num_gems_as_text)
num_players_as_text = input("Enter the number of players: ")
num_players = int(num_players_as_text)Another Pro Tip
Use "comments" to temporarily disable lines of code
num_gems_as_text = "23" # input("Enter the number of gems: ")
num_gems = int(num_gems_as_text)
num_players_as_text = "3" # input("Enter the number of players: ")
num_players = int(num_players_as_text)Do you REALLY like to type THAT MUCH?!?
🙋🏻♂️❓🙋🏻♀️Why did I put in the quotes ("23")?
🙋🏻♂️❓🙋🏻♀️What happens when I run this?
# get first name
# get last name
# get weight in kg
# calculate weight on Jupiter
# display results# get first name
first_name = input("What's your first name? ")
# get last name
last_name = input("What's your last name? ")
# get weight in kg on Earth
earth_weight_in_kg = float(input("How much do you weigh, in kg? "))
# calculate weight on Jupiter
# use gravity multiplier
# https://nssdc.gsfc.nasa.gov/planetary/factsheet/planet_table_ratio.html
jup_weight_in_kg = earth_weight_in_kg * 2.36
# display results
print("Hi,", first_name, last_name, "!")
print("You would weigh", jup_weight_in_kg, "kg on Jupiter!")...but delete unneeded comments when you're done!
# sets sum to 0
sum = 0
# print message
print("Hello - welcome to the jungle.")
# add 2 numbers to get sum
sum = first_num + second_num
# I was SOOOO drunk when I wrote this
arglebargle = fart_factor ** 3
# -----------------------------------
# -----------------------------------
# we don't use this any more
# flight = ""
# crew = 0
What's wrong with these?
What's wrong with this?
What's wrong with this?
What's wrong with this?
// JS - try this in a browser console
const PI = 3.14;
PI = -1; // say WHAAAAT?!?!🙋🏻♂️❓🙋🏻♀️What does this look like in memory?
# in Python SCREAMING_SNAKE_CASE means
# this variable should be considered
# a constant
PI = 3.14
diameter = 12
circumference = PI * diameter
# buuuuuuuuut...
PI = -1
# so much for followin' the rules
# madness!
circumference = PI * diameter Instead, we rely on convention to visually indicate that a variable shouldn't be changed - but folks can totally ignore that convention and do the unthinkable.
balance = 1.04 * balancebalance = (ANNUAL_INTEREST_RATE) * balancesips_available = 4.3 * 17sips_available = AVG_SIPS_PER_ML * ML_PER_CUP🙋🏻♂️❓🙋🏻♀️What memorable term did we use for THIS_KIND_OF_CASE?
triangle_base = 5
triangle_height = 7
ONE = 1
TWO = 2
area = (ONE / TWO) * (triangle_base * triangle_height)If you cannot provide a MEANINGFUL name to a magic number, do NOT make it a constant. Please. I beg of you.
Spot the magic numbers - and give them names, if you feel they should be turned into a constant
base = 12
height = 3
area = (1/2) * base * heightplaylist_duration_in_minutes = 14.3
playlist_duration_in_seconds = 60 * playlist_duration_in_minutes
num_songs_on_playlist = 5
avg_duration_per_song_in_seconds = playlist_duration_in_seconds / num_songs_on_playlistnum_full_cartons = 4
num_loose_eggs = 2
total_num_eggs = (12 * num_full_cartons) + 2weighted_avg_earth_radius = (1/3) * (2 * 1378137) + 6356752print(f"{'nickname':<13}{'score':>7}")
print("-" * 20)If you want to use constants in an f-string, you can...but you have to wrap them in curly braces, so that the constants are evaluated!
COL_1_WIDTH = 14
print(f'''{'Name':COL_1_WIDTH} ''')COL_1_WIDTH = 14
print(f'''{'Name':{COL_1_WIDTH}} ''')What did we talk about?