SSG, a Static Site Generator uses a two-phase build, a read-only stage to detect all errors and compute outputs, followed by a commit stage that atomically writes all changes. It focuses on speed using an incremental build that trusts a hash-based cache for fast updates, but also includes a full validation mode for maximum safety.
"""
Parse and evaluate simple math word problems returning the answer as an integer.
"""defanswer(question:str)->int:replacements={"What is":"","plus":"+","minus":"-","multiplied by":"*","divided by":"/","?":""}forword,symbolinreplacements.items():question=question.replace(word,symbol)tokens=question.split()tokens.insert(0,"(")tokens.insert(4,")")iflen(tokens)<3:raiseValueError("syntax error")ifany(token.isalpha()andtokennotinlist(replacements.keys())fortokenintokens):raiseValueError("unknown operation")try:returneval("".join(tokens))except:raiseValueError("syntax error")
"""
Determine the RNA complement of a given DNA sequence.
"""defto_rna(dna_strand:str)->str:result=[]forstrandindna_strand:matchstrand:case"G":result.append("C")case"C":result.append("G")case"T":result.append("A")case"A":result.append("U")return"".join(result)
defrebase(input_base:int,digits:list[int],output_base:int)->list[int]:"""
Convert a number from one base to another.
input_base - The base of the input number (must be >= 2)
digits - A list of integers representing the number in the input base
Each digit must satisfy 0 <= digit < input_base
output_base - The base to convert the number into (must be >= 2)
returns - A list of integers representing the number in the output base.
The most significant digit comes first
raises - ValueError
if input_base or output_base < 2
if any digit is out of range
"""ifinput_base<2:raiseValueError("input base must be >= 2")ifoutput_base<2:raiseValueError("output base must be >= 2")ifnotdigitsorall(d==0fordindigits):return[0]ifany(d<0ord>=input_basefordindigits):raiseValueError("all digits must satisfy 0 <= d < input base")# Convert digits to integer value
value=0fordindigits:value=value*input_base+d# Convert integer value to output_base
result=[]whilevalue:value,rem=divmod(value,output_base)result.append(rem)returnresult[::-1]
"""
Determine if a number is perfect, abundant, or deficient
"""importmathdefclassify(number:int)->str:""" A perfect number equals the sum of its positive divisors.
:param number: int a positive integer
:return: str the classification of the input integer
"""ifnumber<=0:raiseValueError("Classification is only possible for positive integers.")elifnumberis1:return"deficient"divisors=[]foriinrange(1,math.isqrt(number)+1):ifnumber%i==0:divisors.append(i)ifi!=1andi!=number//i:divisors.append(number//i)sum_divisors=sum(divisors)ifsum_divisors==number:return"perfect"elifsum_divisors>number:return"abundant"else:return"deficient"
"""
This exercise stub and the test suite contain several enumerated constants.
Enumerated constants can be done with a NAME assigned to an arbitrary,
but unique value. An integer is traditionally used because it’s memory
efficient.
It is a common practice to export both constants and functions that work with
those constants (ex. the constants in the os, subprocess and re modules).
https://en.wikipedia.org/wiki/Enumerated_type
"""# Possible sublist categories.
# Change the values as you see fit.
SUBLIST=1SUPERLIST=2EQUAL=3UNEQUAL=0defis_sublist(A:list,B:list)->bool:"""True if list_one is a contiguous slice in list_two"""lenA,lenB=len(A),len(B)iflenA==0:returnTrueiflenA>lenB:returnFalsereturnany(B[i:i+lenA]==Aforiinrange(lenB-lenA+1))defsublist(A:list,B:list):"""
return - relationship between lists A and B
relation is one of 'equal', 'sublist', 'superlist', 'unequal'.
"""ifA==B:returnEQUALelifis_sublist(A,B):returnSUBLISTelifis_sublist(B,A):returnSUPERLISTreturnUNEQUAL
"""
Calculate the points scored in a single toss of a Darts game.
"""importmathdefscore(x:float,y:float)->int:distance=math.sqrt(x**2+y**2)ifdistance<=1:return10elifdistance<=5:return5elifdistance<=10:return1else:return0
"""
check an ISBN-10 number is valid by computing a checksum, as per the ISBN-10 validation formula.
"""defis_valid(isbn:str)->bool:digits=[10ifc=='X'andi==9elseint(c)ifc.isdigit()elseNonefori,cinenumerate(cforcinisbnifc.isalnum())]iflen(digits)!=10orany(disNonefordindigits):returnFalseresult=sum(d*(10-i)fori,dinenumerate(digits))returnresult%11==0
"""
A pangram is a sentence using every letter of the alphabet at least once.
It is case insensitive, so it doesn't matter if a letter is lower-case (e.g. `k`) or upper-case (e.g. `K`).
Is a sentence a pangram ?
"""defis_pangram(sentence:str)->bool:alphabets=list("abcdefghijklmnopqrstuvwxyz")forcharinalphabets:ifcharnotinsentence.lower():returnFalsereturnTrue
"""
Implement of the rotational cipher, also sometimes called the Caesar cipher.
"""defrotate(text:str,key:int)->str:chars="abcdefghijklmnopqrstuvwxyz"new_chars=chars[key:]+chars[:key]trans_table=str.maketrans(chars+chars.upper(),new_chars+new_chars.upper())returntext.translate(trans_table)
"""
Determine if a word or phrase is an isogram.
An isogram (also known as a "non-pattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times.
Examples of isograms:
- lumberjacks
- background
- downstream
- six-year-old
The word _isograms_, however, is not an isogram, because the s repeats.
"""defis_isogram(text:str)->bool:chars=''.join(filter(str.isalnum,text)).lower()returnlen(chars)==len(set(chars))
"""
Given a string containing brackets `[]`, braces `{}`, parentheses `()`, or any combination thereof, verify that any and all pairs are matched and nested correctly
"""defis_paired(text:str)->bool:pairs={'}':'{',']':'[',')':'('}brackets=[]forchrintext:ifchrin'{[(':brackets.append(chr)elifchrin'}])':ifnotbracketsorbrackets.pop()!=pairs[chr]:returnFalsereturnnotbrackets
"""
note: `pytest -s | --capture=no` shows print() output
start with a vowel, append "ay" at the end.
starts with consonants, move to the end one by one until a vowel is found.
words beginning with "x" or "y" followed by a consonant, no further transformation.
keep the “u” attached to “q” when moving characters around
my -> ym -> ymay
square -> quares -> aresqu -> aresquay
yellow -> ellowy -> ellowyay
rhythm -> hythmr -> ythmrh -> ythmrhay
"""vowels=('a','e','i','o','u')defpig_latin(word):# stages list stores intermediate transforms of the word
stages=[word]whilenotword[0]invowels:ifword[0]in'xy'andnotword[1]invowels:breakword=word[1:]+word[0]ifword[-1]=='q'andword[0]=='u':word=word[1:]+'u'stages.append(word)stages.append(word+"ay")print(" -> ".join(stages))returnword+'ay'deftranslate(sentence):return''.join([pig_latin(word)forwordinsentence.split()])
"""
Calculate the number of grains of wheat on a chessboard.
"""defsquare(number):ifnumber>0andnumber<=64:return2**(number-1)else:raiseValueError("square must be between 1 and 64")deftotal():total_grains=0forgrainsinrange(1,65):total_grains+=square(grains)returntotal_grains
"""
Given a positive integer, return the number of steps it takes to reach 1 according to the rules of the Collatz Conjecture.
"""defsteps(number):step=0ifnumber>0:whilenumber>1:step+=1ifnumber%2==0:number=number/2else:number=(number*3)+1else:raiseValueError("Only positive integers are allowed")returnstep
"""
Determine whether a number is an Armstrong number
"""defis_armstrong_number(number):digits=[int(d)fordinstr(number)]length=len(digits)total=0fornumindigits:total+=(num**length)returnnumber==total
defsquare_root(n):"""
Calculates the square root of a number using the Babylonian method.
Args:
n: The number to find the square root of (must be non-negative).
Returns:
The approximate square root of n.
"""ifn<0:return"Square root is not defined for negative numbers."ifn==0:return0guess=n/2.0tolerance=0.00001whileabs(guess*guess-n)>tolerance:guess=(guess+n/guess)/2.0returnint(guess)
"""
what will Bob reply to someone when they say something to him or ask him a question?
"""defresponse(hey_bob:str):hey_bob=hey_bob.rstrip()ifhey_bob.endswith("?"):ifhey_bob.isupper():return"Calm down, I know what I'm doing!"else:return"Sure."elifhey_bob.isupper():return"Whoa, chill out!"elifhey_bob.isspace()ornothey_bob:return"Fine. Be that way!"else:return"Whatever."
"""Solution to Ellen's Alien Game exercise."""classAlien:"""Create an Alien object with location x_coordinate and y_coordinate.
Attributes
----------
(class)total_aliens_created: int
x_coordinate: int - Position on the x-axis.
y_coordinate: int - Position on the y-axis.
health: int - Number of health points.
Methods
-------
hit(): Decrement Alien health by one point.
is_alive(): Return a boolean for if Alien is alive (if health is > 0).
teleport(new_x_coordinate, new_y_coordinate): Move Alien object to new coordinates.
collision_detection(other): Implementation TBD.
"""total_aliens_created=0def__init__(self,x_coordinate,y_coordinate):self.x_coordinate=x_coordinateself.y_coordinate=y_coordinateself.health=3Alien.total_aliens_created+=1defhit(self):self.health-=1ifself.health==0:self.health=0defis_alive(self):returnself.health>0defteleport(self,new_x,new_y):self.x_coordinate=new_xself.y_coordinate=new_ydefcollision_detection(self,other):pass#TODO: create the new_aliens_collection() function below to call your Alien class with a list of coordinates.
defnew_aliens_collection(alien_start_positions:list):aliens=[]foralieninalien_start_positions:new_alien=Alien(alien[0],alien[1])aliens.append(new_alien)returnaliens
"""Functions for compiling dishes and ingredients for a catering company."""fromsets_categories_dataimport(VEGAN,VEGETARIAN,KETO,PALEO,OMNIVORE,ALCOHOLS,SPECIAL_INGREDIENTS)defclean_ingredients(dish_name,dish_ingredients):"""Remove duplicates from `dish_ingredients`.
:param dish_name: str - containing the dish name.
:param dish_ingredients: list - dish ingredients.
:return: tuple - containing (dish_name, ingredient set).
This function should return a `tuple` with the name of the dish as the first item,
followed by the de-duped `set` of ingredients as the second item.
"""return (dish_name,set(dish_ingredients))defcheck_drinks(drink_name,drink_ingredients):"""Append "Cocktail" (alcohol) or "Mocktail" (no alcohol) to `drink_name`, based on `drink_ingredients`.
:param drink_name: str - name of the drink.
:param drink_ingredients: list - ingredients in the drink.
:return: str - drink_name appended with "Mocktail" or "Cocktail".
The function should return the name of the drink followed by "Mocktail" (non-alcoholic) and drink
name followed by "Cocktail" (includes alcohol).
"""returnf"{drink_name} Mocktail"ifset(drink_ingredients).isdisjoint(ALCOHOLS)elsef"{drink_name} Cocktail"defcategorize_dish(dish_name,dish_ingredients):"""Categorize `dish_name` based on `dish_ingredients`.
:param dish_name: str - dish to be categorized.
:param dish_ingredients: set - ingredients for the dish.
:return: str - the dish name appended with ": <CATEGORY>".
This function should return a string with the `dish name: <CATEGORY>` (which meal category the dish belongs to).
`<CATEGORY>` can be any one of (VEGAN, VEGETARIAN, PALEO, KETO, or OMNIVORE).
All dishes will "fit" into one of the categories imported from `sets_categories_data.py`
"""categories=[(VEGAN,"VEGAN"),(VEGETARIAN,"VEGETARIAN"),(PALEO,"PALEO"),(KETO,"KETO"),(OMNIVORE,"OMNIVORE")]forcategory,nameincategories:ifdish_ingredients<=category:returnf"{dish_name}: {name}"returnf"{dish_name}: UNCLASSIFIED"deftag_special_ingredients(dish):"""Compare `dish` ingredients to `SPECIAL_INGREDIENTS`.
:param dish: tuple - of (dish name, list of dish ingredients).
:return: tuple - containing (dish name, dish special ingredients).
Return the dish name followed by the `set` of ingredients that require a special note on the dish description.
For the purposes of this exercise, all allergens or special ingredients that need to be tracked are in the
SPECIAL_INGREDIENTS constant imported from `sets_categories_data.py`.
"""return (dish[0],set(dish[1]).intersection(SPECIAL_INGREDIENTS))defcompile_ingredients(dishes):"""Create a master list of ingredients.
:param dishes: list - of dish ingredient sets.
:return: set - of ingredients compiled from `dishes`.
This function should return a `set` of all ingredients from all listed dishes.
"""masterlist=set()foringrediantsindishes:masterlist=masterlist.union(ingrediants)returnmasterlistdefseparate_appetizers(dishes,appetizers):"""Determine which `dishes` are designated `appetizers` and remove them.
:param dishes: list - of dish names.
:param appetizers: list - of appetizer names.
:return: list - of dish names that do not appear on appetizer list.
The function should return the list of dish names with appetizer names removed.
Either list could contain duplicates and may require de-duping.
"""returnlist(set(dishes).difference(set(appetizers)))defsingleton_ingredients(dishes,intersection):"""Determine which `dishes` have a singleton ingredient (an ingredient that only appears once across dishes).
:param dishes: list - of ingredient sets.
:param intersection: constant - can be one of `<CATEGORY>_INTERSECTIONS` constants imported from `sets_categories_data.py`.
:return: set - containing singleton ingredients.
Each dish is represented by a `set` of its ingredients.
Each `<CATEGORY>_INTERSECTIONS` is an `intersection` of all dishes in the category. `<CATEGORY>` can be any one of:
(VEGAN, VEGETARIAN, PALEO, KETO, or OMNIVORE).
The function should return a `set` of ingredients that only appear in a single dish.
"""singleton=set()foringrediantsindishes:singleton=singleton.symmetric_difference(set(ingrediants))returnsingleton-intersection
"""Functions to keep track and alter inventory."""fromcollectionsimportCounterdefcreate_inventory(items):"""Create a dict that tracks the amount (count) of each element on the `items` list.
:param items: list - list of items to create an inventory from.
:return: dict - the inventory dictionary.
"""returndict(Counter(items))defadd_items(inventory,items):"""Add or increment items in inventory using elements from the items `list`.
:param inventory: dict - dictionary of existing inventory.
:param items: list - list of items to update the inventory with.
:return: dict - the inventory updated with the new items.
"""foriteminitems:ifitemininventory:inventory[item]+=1else:inventory[item]=1returninventorydefdecrement_items(inventory,items):"""Decrement items in inventory using elements from the `items` list.
:param inventory: dict - inventory dictionary.
:param items: list - list of items to decrement from the inventory.
:return: dict - updated inventory with items decremented.
"""foriteminitems:ifitemininventory:ifinventory[item]<=1:inventory[item]=0else:inventory[item]-=1returninventorydefremove_item(inventory,item):"""Remove item from inventory if it matches `item` string.
:param inventory: dict - inventory dictionary.
:param item: str - item to remove from the inventory.
:return: dict - updated inventory with item removed. Current inventory if item does not match.
"""ifitemininventory:inventory.pop(item)returninventorydeflist_inventory(inventory):"""Create a list containing only available (item_name, item_count > 0) pairs in inventory.
:param inventory: dict - an inventory dictionary.
:return: list of tuples - list of key, value pairs from the inventory dictionary.
"""item_list=[]forkey,valueininventory.items():ifvalue>0:item_list.append((key,value))returnitem_list
"""Functions to help Azara and Rui locate pirate treasure."""defget_coordinate(record):"""Return coordinate value from a tuple containing the treasure name, and treasure coordinate.
:param record: tuple - with a (treasure, coordinate) pair.
:return: str - the extracted map coordinate.
"""coordinate=record[1]returncoordinatedefconvert_coordinate(coordinate):"""Split the given coordinate into tuple containing its individual components.
:param coordinate: str - a string map coordinate
:return: tuple - the string coordinate split into its individual components.
"""returntuple((coordinate))defcompare_records(azara_record,rui_record):"""Compare two record types and determine if their coordinates match.
:param azara_record: tuple - a (treasure, coordinate) pair.
:param rui_record: tuple - a (location, tuple(coordinate_1, coordinate_2), quadrant) trio.
:return: bool - do the coordinates match?
"""returntuple(azara_record[1])==rui_record[1]defcreate_record(azara_record,rui_record):"""Combine the two record types (if possible) and create a combined record group.
:param azara_record: tuple - a (treasure, coordinate) pair.
:param rui_record: tuple - a (location, coordinate, quadrant) trio.
:return: tuple or str - the combined record (if compatible), or the string "not a match" (if incompatible).
"""returnazara_record+rui_recordifcompare_records(azara_record,rui_record)else"not a match"defclean_up(combined_record_group):"""Clean up a combined record group into a multi-line string of single records.
:param combined_record_group: tuple - everything from both participants.
:return: str - everything "cleaned", excess coordinates and information are removed.
The return statement should be a multi-lined string with items separated by newlines.
(see HINTS.md for an example).
"""report=""foritemincombined_record_group:iftuple(item[1])==item[3]:report+=f"""('{item[0]}', '{item[2]}', {item[3]}, '{item[4]}')\n"""returnreport
"""Functions for organizing and calculating student exam scores."""defround_scores(student_scores):"""Round all provided student scores.
:param student_scores: list - float or int of student exam scores.
:return: list - student scores *rounded* to nearest integer value.
"""student_scores_rounded=[]forscoreinstudent_scores:student_scores_rounded.append(round(score))returnstudent_scores_roundeddefcount_failed_students(student_scores):"""Count the number of failing students out of the group provided.
:param student_scores: list - containing int student scores.
:return: int - count of student scores at or below 40.
"""failed_students:int=0forscoreinstudent_scores:ifscore<=40:failed_students+=1returnfailed_studentsdefabove_threshold(student_scores,threshold):"""Determine how many of the provided student scores were 'the best' based on the provided threshold.
:param student_scores: list - of integer scores.
:param threshold: int - threshold to cross to be the "best" score.
:return: list - of integer scores that are at or above the "best" threshold.
"""scores_above_threshold=[]forscoreinstudent_scores:ifscore>=threshold:scores_above_threshold.append(score)returnscores_above_thresholddefletter_grades(highest):"""Create a list of grade thresholds based on the provided highest grade.
:param highest: int - value of highest exam score.
:return: list - of lower threshold scores for each D-A letter grade interval.
For example, where the highest score is 100, and failing is <= 40,
The result would be [41, 56, 71, 86]:
41 <= "D" <= 55
56 <= "C" <= 70
71 <= "B" <= 85
86 <= "A" <= 100
"""low_score=41no_grades=4# A B C D
threshold_increment=round((highest-low_score)/no_grades)lower_threshold=[]forindexinrange(no_grades):lower_threshold.append(low_score+(threshold_increment*index))returnlower_thresholddefstudent_ranking(student_scores,student_names):"""Organize the student's rank, name, and grade information in descending order.
:param student_scores: list - of scores in descending order.
:param student_names: list - of string names by exam score in descending order.
:return: list - of strings in format ["<rank>. <student name>: <score>"].
"""rank_list=[]forindex,(name,score)inenumerate(zip(student_names,student_scores)):rank_list.append(f"{index+1}. {name}: {score}")returnrank_listdefperfect_score(student_info):"""Create a list that contains the name and grade of the first student to make a perfect score on the exam.
:param student_info: list - of [<student name>, <score>] lists.
:return: list - first `[<student name>, 100]` or `[]` if no student score of 100 is found.
"""forinfoinstudent_info:ifinfo[1]==100:returninforeturn[]
"""Functions to manage and organize queues at Chaitana's roller coaster."""defadd_me_to_the_queue(express_queue,normal_queue,ticket_type,person_name):"""Add a person to the 'express' or 'normal' queue depending on the ticket number.
:param express_queue: list - names in the Fast-track queue.
:param normal_queue: list - names in the normal queue.
:param ticket_type: int - type of ticket. 1 = express, 0 = normal.
:param person_name: str - name of person to add to a queue.
:return: list - the (updated) queue the name was added to.
"""queue=express_queueifticket_type==1elsenormal_queuequeue.append(person_name)returnqueuedeffind_my_friend(queue,friend_name):"""Search the queue for a name and return their queue position (index).
:param queue: list - names in the queue.
:param friend_name: str - name of friend to find.
:return: int - index at which the friends name was found.
"""returnqueue.index(friend_name)defadd_me_with_my_friends(queue,index,person_name):"""Insert the late arrival's name at a specific index of the queue.
:param queue: list - names in the queue.
:param index: int - the index at which to add the new name.
:param person_name: str - the name to add.
:return: list - queue updated with new name.
"""queue.insert(index,person_name)returnqueuedefremove_the_mean_person(queue,person_name):"""Remove the mean person from the queue by the provided name.
:param queue: list - names in the queue.
:param person_name: str - name of mean person.
:return: list - queue update with the mean persons name removed.
"""queue.remove(person_name)returnqueuedefhow_many_namefellows(queue,person_name):"""Count how many times the provided name appears in the queue.
:param queue: list - names in the queue.
:param person_name: str - name you wish to count or track.
:return: int - the number of times the name appears in the queue.
"""returnqueue.count(person_name)defremove_the_last_person(queue):"""Remove the person in the last index from the queue and return their name.
:param queue: list - names in the queue.
:return: str - name that has been removed from the end of the queue.
"""returnqueue.pop()defsorted_names(queue):"""Sort the names in the queue in alphabetical order and return the result.
:param queue: list - names in the queue.
:return: list - copy of the queue in alphabetical order.
"""returnsorted(queue)
# Let a, b, and c be sides of the triangle. Then all three of the following expressions must be true:
#
# a + b ≥ c
# b + c ≥ a
# a + c ≥ b
defvalid_triangle(sides):a,b,c=sidesif (a+b>=c)and(b+c>=a)and(a+c>=b):returnTrueelse:returnFalsedefequilateral(sides):a,b,c=sidesifsum(sides)>0andvalid_triangle(sides)anda==b==c:returnTrueelse:returnFalsedefisosceles(sides):a,b,c=sidesifsum(sides)>0andvalid_triangle(sides)and(a==bora==corb==corequilateral(sides)):returnTrueelse:returnFalsedefscalene(sides):a,b,c=sidesifsum(sides)>0andvalid_triangle(sides)and(a!=banda!=candb!=c):returnTrueelse:returnFalse
defleap_year(year):# if year % 4 == 0 and year % 100 == 0 and year % 400 == 0:
# return True
# elif year % 4 == 0 and not year % 100 == 0:
# return True
# else:
# return False
# year - 4 - 100 - 400
# 1974 F F F not
# 1996 T F F leap
# 1960 T F F leap
# 1900 T T F not
# 2000 T T T leap
returnyear%4==0and(year%100!=0oryear%400==0)
importmath"""Functions for tracking poker hands and assorted card tasks.
Python list documentation: https://docs.python.org/3/tutorial/datastructures.html
"""defget_rounds(number):"""Create a list containing the current and next two round numbers.
:return: list - current round and the two that follow.
"""return[number,number+1,number+2]defconcatenate_rounds(rounds_1,rounds_2):"""Concatenate two lists of round numbers.
:param rounds_1: list - first rounds played.
:param rounds_2: list - second set of rounds played.
:return: list - all rounds played.
"""returnrounds_1+rounds_2deflist_contains_round(rounds,number):"""Check if the list of rounds contains the specified number.
:param rounds: list - rounds played.
:param number: int - round number.
:return: bool - was the round played?
"""returnnumberinroundsdefcard_average(hand):"""Calculate and returns the average card value from the list.
:param hand: list - cards in hand.
:return: float - average value of the cards in the hand.
"""returnfloat(sum(hand)/len(hand))defapprox_average_is_average(hand):"""Return if the (average of first and last card values) OR ('middle' card) == calculated average.
:param hand: list - cards in hand.
:return: bool - does one of the approximate averages equal the `true average`?
"""estimate=float((hand[0]+hand[-1])/2)average=float(sum(hand)/len(hand))middle=hand[math.floor(len(hand)/2)]ifestimate==averageormiddle==average:returnTrueelse:returnFalsedefaverage_even_is_average_odd(hand):"""Return if the (average of even indexed card values) == (average of odd indexed card values).
:param hand: list - cards in hand.
:return: bool - are even and odd averages equal?
"""evens=hand[::2]odds=hand[1::2]returnsum(evens)/len(evens)==sum(odds)/len(odds)defmaybe_double_last(hand):"""Multiply a Jack card value in the last index position by 2.
:param hand: list - cards in hand.
:return: list - hand with Jacks (if present) value doubled.
"""ifhand[-1]==11:hand[-1]=22returnhand
"""Functions to help edit essay homework using string manipulation."""defcapitalize_title(title):"""Convert the first letter of each word in the title to uppercase if needed.
:param title: str - title string that needs title casing.
:return: str - title string in title case (first letters capitalized).
"""returntitle.title()defcheck_sentence_ending(sentence):"""Check the ending of the sentence to verify that a period is present.
:param sentence: str - a sentence to check.
:return: bool - return True if punctuated correctly with period, False otherwise.
"""returnsentence.endswith('.')defclean_up_spacing(sentence):"""Verify that there isn't any whitespace at the start and end of the sentence.
:param sentence: str - a sentence to clean of leading and trailing space characters.
:return: str - a sentence that has been cleaned of leading and trailing space characters.
"""returnsentence.strip()defreplace_word_choice(sentence,old_word,new_word):"""Replace a word in the provided sentence with a new one.
:param sentence: str - a sentence to replace words in.
:param old_word: str - word to replace.
:param new_word: str - replacement word.
:return: str - input sentence with new words in place of old words.
"""returnsentence.replace(old_word,new_word)
"""Functions for creating, transforming, and adding prefixes to strings."""defadd_prefix_un(word):"""Take the given word and add the 'un' prefix.
:param word: str - containing the root word.
:return: str - of root word prepended with 'un'.
"""return'un'+worddefmake_word_groups(vocab_words):"""Transform a list containing a prefix and words into a string with the prefix followed by the words with prefix prepended.
:param vocab_words: list - of vocabulary words with prefix in first index.
:return: str - of prefix followed by vocabulary words with
prefix applied.
This function takes a `vocab_words` list and returns a string
with the prefix and the words with prefix applied, separated
by ' :: '.
For example: list('en', 'close', 'joy', 'lighten'),
produces the following string: 'en :: enclose :: enjoy :: enlighten'.
"""#prefix = vocab_words[0]
#
# create a list with prefix as first item,
# append prefix to each work in list and add to list
# words_with_prefix = [prefix + word for word in vocab_words[1:]]
#
# '[prefix]' is a list with only one item
# return a string by joining '[prefix]' with list words_with_prefix
# return ' :: '.join([prefix] + words_with_prefix)
# above turned into a one-liner
return' :: '.join([vocab_words[0]]+[vocab_words[0]+wordforwordinvocab_words[1:]])defremove_suffix_ness(word):"""Remove the suffix from the word while keeping spelling in mind.
:param word: str - of word to remove suffix from.
:return: str - of word with suffix removed & spelling adjusted.
For example: "heaviness" becomes "heavy", but "sadness" becomes "sad".
"""# word_root = word.split('ness')[0]
word_root=word.removesuffix('ness')# if word_root[-1] == 'i':
returnword_root[:-1]+'y'ifword_root.endswith('i')elseword_rootdefadjective_to_verb(sentence,index):"""Change the adjective within the sentence to a verb.
:param sentence: str - that uses the word in sentence.
:param index: int - index of the word to remove and transform.
:return: str - word that changes the extracted adjective to a verb.
For example, ("It got dark as the sun set.", 2) becomes "darken".
"""returnsentence.strip('.').split()[index]+'en'
"""Functions to help play and score a game of blackjack.
How to play blackjack: https://bicyclecards.com/how-to-play/blackjack/
"Standard" playing cards: https://en.wikipedia.org/wiki/Standard_52-card_deck
"""defvalue_of_card(card):"""Determine the scoring value of a card.
:param card: str - given card.
:return: int - value of a given card. See below for values.
1. 'J', 'Q', or 'K' (otherwise known as "face cards") = 10
2. 'A' (ace card) = 1
3. '2' - '10' = numerical value.
"""ifcardin['J','Q','K']:return10elifcard=='A':return1elifint(card)>=2orint(card)<=10:returnint(card)defhigher_card(card_one,card_two):"""Determine which card has a higher value in the hand.
:param card_one, card_two: str - cards dealt in hand. See below for values.
:return: str or tuple - resulting Tuple contains both cards if they are of equal value.
1. 'J', 'Q', or 'K' (otherwise known as "face cards") = 10
2. 'A' (ace card) = 1
3. '2' - '10' = numerical value.
"""ifcard_oneiscard_two:returncard_one,card_twoelifvalue_of_card(card_one)==value_of_card(card_two):returncard_one,card_twoelifvalue_of_card(card_one)>value_of_card(card_two):returncard_oneelse:returncard_twodefvalue_of_ace(card_one,card_two):"""Calculate the most advantageous value for the ace card.
:param card_one, card_two: str - card dealt. See below for values.
:return: int - either 1 or 11 value of the upcoming ace card.
1. 'J', 'Q', or 'K' (otherwise known as "face cards") = 10
2. 'A' (ace card) = 11 (if already in hand)
3. '2' - '10' = numerical value.
"""ifcard_one=='A'orcard_two=='A':return1points=value_of_card(card_one)+value_of_card(card_two)ifpoints<=10:return11else:return1defis_blackjack(card_one,card_two):"""Determine if the hand is a 'natural' or 'blackjack'.
:param card_one, card_two: str - card dealt. See below for values.
:return: bool - is the hand is a blackjack (two cards worth 21).
1. 'J', 'Q', or 'K' (otherwise known as "face cards") = 10
2. 'A' (ace card) = 11 (if already in hand)
3. '2' - '10' = numerical value.
"""hand=card_one,card_two# any(iterable)
# Return True if any element of the iterable is true. If the iterable is empty, return False.
# https://docs.python.org/3/library/functions.html#any
return'A'inhandandany(cardinhandforcardin('10','J','Q','K'))defcan_split_pairs(card_one,card_two):"""Determine if a player can split their hand into two hands.
:param card_one, card_two: str - cards dealt.
:return: bool - can the hand be split into two pairs? (i.e. cards are of the same value).
"""returnvalue_of_card(card_one)==value_of_card(card_two)defcan_double_down(card_one,card_two):"""Determine if a blackjack player can place a double down bet.
:param card_one, card_two: str - first and second cards in hand.
:return: bool - can the hand can be doubled down? (i.e. totals 9, 10 or 11 points).
"""points=value_of_card(card_one)+value_of_card(card_two)return9<=points<=11
"""Functions to prevent a nuclear meltdown."""defis_criticality_balanced(temperature,neutrons_emitted):"""Verify criticality is balanced.
:param temperature: int or float - temperature value in kelvin.
:param neutrons_emitted: int or float - number of neutrons emitted per second.
:return: bool - is criticality balanced?
A reactor is said to be critical if it satisfies the following conditions:
- The temperature is less than 800 K.
- The number of neutrons emitted per second is greater than 500.
- The product of temperature and neutrons emitted per second is less than 500000.
"""iftemperature<800andneutrons_emitted>500andtemperature*neutrons_emitted<500000:returnTrueelse:returnFalsedefreactor_efficiency(voltage,current,theoretical_max_power):"""Assess reactor efficiency zone.
:param voltage: int or float - voltage value.
:param current: int or float - current value.
:param theoretical_max_power: int or float - power that corresponds to a 100% efficiency.
:return: str - one of ('green', 'orange', 'red', or 'black').
Efficiency can be grouped into 4 bands:
1. green -> efficiency of 80% or more,
2. orange -> efficiency of less than 80% but at least 60%,
3. red -> efficiency below 60%, but still 30% or more,
4. black -> less than 30% efficient.
The percentage value is calculated as
(generated power/ theoretical max power)*100
where generated power = voltage * current
"""generated_power=voltage*currentpower_efficiency=(generated_power/theoretical_max_power)*100ifpower_efficiency>=80:return'green'elifpower_efficiency<80andpower_efficiency>=60:return'orange'elifpower_efficiency<60andpower_efficiency>=30:return'red'else:return'black'deffail_safe(temperature,neutrons_produced_per_second,threshold):"""Assess and return status code for the reactor.
:param temperature: int or float - value of the temperature in kelvin.
:param neutrons_produced_per_second: int or float - neutron flux.
:param threshold: int or float - threshold for category.
:return: str - one of ('LOW', 'NORMAL', 'DANGER').
1. 'LOW' -> `temperature * neutrons per second` < 90% of `threshold`
2. 'NORMAL' -> `temperature * neutrons per second` +/- 10% of `threshold`
3. 'DANGER' -> `temperature * neutrons per second` is not in the above-stated ranges
"""assessment=temperature*neutrons_produced_per_secondifassessment<threshold*90/100:return'LOW'# lies within 90% to 110% of threshold
elifassessment>=threshold*90/100andassessment<=threshold*110/100:return'NORMAL'else:return'DANGER'
""" demonstrate f-strings using an example"""deftwo_fer(name="you"):"""
A bakery that has a holiday offer where you can buy two cookies
for the price of one ("two-fer one!").
Determine what you will say as you give away the extra cookie to a friend
"""answer=f"One for {name}, one for me."returnanswer
"""Functions for implementing the rules of the classic arcade game Pac-Man."""defeat_ghost(power_pellet_active:bool,touching_ghost:bool):"""Verify that Pac-Man can eat a ghost if he is empowered by a power pellet.
:param power_pellet_active: bool - does the player have an active power pellet?
:param touching_ghost: bool - is the player touching a ghost?
:return: bool - can the ghost be eaten?
"""returnpower_pellet_activeandtouching_ghostdefscore(touching_power_pellet,touching_dot):"""Verify that Pac-Man has scored when a power pellet or dot has been eaten.
:param touching_power_pellet: bool - is the player touching a power pellet?
:param touching_dot: bool - is the player touching a dot?
:return: bool - has the player scored or not?
"""returntouching_dotortouching_power_pelletdeflose(power_pellet_active,touching_ghost):"""Trigger the game loop to end (GAME OVER) when Pac-Man touches a ghost without his power pellet.
:param power_pellet_active: bool - does the player have an active power pellet?
:param touching_ghost: bool - is the player touching a ghost?
:return: bool - has the player lost the game?
"""returntouching_ghostandnotpower_pellet_activedefwin(has_eaten_all_dots,power_pellet_active,touching_ghost):"""Trigger the victory event when all dots have been eaten.
:param has_eaten_all_dots: bool - has the player "eaten" all the dots?
:param power_pellet_active: bool - does the player have an active power pellet?
:param touching_ghost: bool - is the player touching a ghost?
:return: bool - has the player won the game?
"""returnhas_eaten_all_dotsandnotlose(power_pellet_active,touching_ghost)
''' A currency exchange calculator '''defexchange_money(budget:float,exchange_rate:float):"""
calculate the value of exchanged curreny
:param budget: float - amount of money you are planning to exchange.
:param exchange_rate: float - unit value of the foreign currency.
:return: float - exchanged value of the foreign currency you can receive.
"""returnbudget/exchange_ratedefget_change(budget,exchanging_value):"""
:param budget: float - amount of money you own.
:param exchanging_value: float - amount of your money you want to exchange now.
:return: float - amount left of your starting currency after exchanging.
"""returnbudget-exchanging_valuedefget_value_of_bills(denomination,number_of_bills):"""
:param denomination: int - the value of a bill.
:param number_of_bills: int - amount of bills you received.
:return: int - total value of bills you now have.
"""returndenomination*number_of_billsdefget_number_of_bills(budget,denomination):"""
:param budget: float - the amount of money you are planning to exchange.
:param denomination: int - the value of a single bill.
:return: int - number of bills after exchanging all your money.
"""returnbudget//denominationdefget_leftover_of_bills(budget,denomination):"""
:param budget: float - the amount of money you are planning to exchange.
:param denomination: int - the value of a single bill.
:return: float - the leftover amount that cannot be exchanged given the current denomination.
"""returnbudget%denominationdefexchangeable_value(budget,exchange_rate,spread,denomination):"""
:param budget: float - the amount of your money you are planning to exchange.
:param exchange_rate: float - the unit value of the foreign currency.
:param spread: int - percentage that is taken as an exchange fee.
:param denomination: int - the value of a single bill.
:return: int - maximum value you can get.
"""actual_rate=exchange_rate*(1+spread/100)value_after_exchange=exchange_money(budget,actual_rate)returnget_value_of_bills(denomination,get_number_of_bills(value_after_exchange,denomination))
"""
return the highest score from the list, the last added score and the three highest scores
"""deflatest(scores):returnscores.pop()defpersonal_best(scores):returnmax(scores)defpersonal_top_three(scores):returnsorted(scores,reverse=True)[:3]
"""
from a matrix of numbers, return the rows and columns of that matrix
"""classMatrix:def__init__(self,matrix_string):rowStrings=[r.split()forrinmatrix_string.splitlines()]self.matrix=[[int(num)fornuminrow]forrowinrowStrings]defrow(self,index):returnself.matrix[index-1]defcolumn(self,index):return[column[index-1]forcolumninself.matrix]
"""
Functions used in preparing Guido's gorgeous lasagna.
Learn about Guido, the creator of the Python language: https://en.wikipedia.org/wiki/Guido_van_Rossum
"""EXPECTED_BAKE_TIME=40defbake_time_remaining(elapsed_bake_time):"""Calculate the bake time remaining.
:param elapsed_bake_time: int - baking time already elapsed.
:return: int - remaining bake time (in minutes) derived from 'EXPECTED_BAKE_TIME'.
Function that takes the actual minutes the lasagna has been in the oven as
an argument and returns how many minutes the lasagna still needs to bake
based on the `EXPECTED_BAKE_TIME`.
"""returnEXPECTED_BAKE_TIME-elapsed_bake_timedefpreparation_time_in_minutes(number_of_layers):"""
Return minutes spent making the recipe
This function takes a number representing the number of layers added to the lasagne
"""preparation_time=2returnpreparation_time*number_of_layersdefelapsed_time_in_minutes(number_of_layers,elapsed_bake_time):"""
Return elapsed cooking time.
This function takes two numbers representing the number of layers & the time already spent
baking and calculates the total elapsed minutes spent cooking the lasagna.
"""returnpreparation_time_in_minutes(number_of_layers)+elapsed_bake_time
"""
Raindrops is a slightly more complex version of the FizzBuzz challenge, a classic interview question.
Convert a number into its corresponding raindrop sounds.
"""defconvert(number):answer=[]raindrops={3:"Pling",5:"Plang",7:"Plong"}ifnumber%3==0:answer+=raindrops[3]ifnumber%5==0:answer+=raindrops[5]ifnumber%7==0:answer+=raindrops[7]return''.join(answer)orstr(number)
For BSD (and MacOS) versions of find, you can use -perm with + and an octal mask:
find .-type f -perm +111 -print
In this context “+” means “any of these bits are set” and 111 is the execute bits. Note that this is not identical to the -executable predicate in GNU find. In particular, -executable tests that the file can be executed by the current user, while -perm +111 just tests if any execute permissions are set.
There is something meditative about watching Piranesi live, the purity of his life and the kindness of it. And Piranesi’s kindness is possible in part because he lives in such communion with the House, which is his world. He respects the House and knows how to live within it, and in turn the House blesses him with its bounties.
In the end we found it impossible to ignore the impassioned pleas of the Lost City of White Male Privilege, a controversial municipality whose very existence is often denied by many (mostly privileged white males). Others state categorically that the walls of the locale have been irreparably breached by hip-hop and Roberto Bolaño’s prose …
At the fulcrum of Roberto Bolaño’s kaleidoscopic epic Savage Detectives, are the poets Ulises Lima and Arturo Belano, the author’s alter ego. The mysterious leaders of the Visceral Realists, drift through Spain, Israel, North Africa, and Mexico sharing an unspoken and often inscrutable bond as they phase in and out of contact
You are wary of other people’s questions. What questions do you ask yourself?
I don’t ask myself big questions. I’ve a friend who was struggling, saying: “I don’t know why I am here… what is the purpose?” I said: “There is no purpose.” If there were a purpose, then I would be frozen.
Environmental despoliation, economic regression, and enthroned sexism and bigotry are already on the cards. For all the turmoil on our streets and abroad, literary historians may look back at the Obama years as a time of tranquility …
I am disinclined to find endearing a chronicler of the 1960s who is beset by migraines that can be triggered by her decorator’s having pleated instead of gathered her new diningroom curtains. These, and other assorted facts – such as the fact that Didion chose to buy the dress Linda Kasabian wore at the Manson trial at I. Magnin in Beverly Hills – put me more in mind of a neurasthenic Cher than of a writer who has been called America’s finest woman prose stylist.
His claim is that we’ve had this narrow cone of progress around the world of bits—around software & IT — but not atoms. The iPhones that distract us from our environment also distract us from how strangely old & unchanged our current environment is. If you were to be in any room in 1973, everything would look the same except for our phones. This explains his old Founders Fund tagline: “We wanted flying cars, instead we got 140 characters.”
Zooming out, people don’t understand how important economic growth is. It’s the only thing sustaining the planet. Without it, we go into a malthusian war. Indeed: The only way our societies have worked for at least 250 years is by economic growth. Parliamentary democracies are built on an ever-expanding pie that they can continue subdividing. Once the pie is no longer expanding, everything turns zero-sum.
The term “Cyberdeck” was first coined in Gibson’s 1984 literary masterpiece, Neuromancer. He rewrote parts of Neuromancer several times after the release of Ridley Scott’s Blade Runner. Blade Runner was based on Philip K. Dick’s 1968 novel Do Androids Dream of Electric Sheep. Scott, Dick, Brunner’s The Shockwave Rider, Goddard’s Alphaville and work by futurists such as Syd Mead and Moebius make the title of “father of Cyberpunk” hard to hang on Gibson alone. But he’s clearly a very important character in the development of Cyberpunk culture.
Just as Shakespeare brought in new words to describe new worlds, 1980s Gibson is Cyberpunk’s Great Bard. The Cyberdeck is just one of Gibson’s literary gifts. It’s the tool that lets Console Cowboys jack into the Matrix of Cyberspace and start hacking.
Anthropology starts from the recognition that a person - in the first instance at least - cannot exist apart from a group. Put differently, anthropology assumes that a human network always precedes its individual members, and that care and reproduction precede any form of solo heroics. Human babies don’t survive long if they are left to fend for themselves, and - even if they miraculously survived without others - they would not be able to speak language, which would make all future social interaction, relationships and trade near-impossible.
Let’s say that any weapon will have a component for damage, range, and projectiles (optional). Using Unity’s UI, you could create a weapon by dragging these components onto any GameObject and customizing the values of each one. Then, if the way projectiles are handled changes further into development, all you need to do is change one script, and all your weapons’ functionalities will be updated instead of just those defined at one level of a tree.
His claim is that we’ve had this narrow cone of progress around the world of bits—around software & IT — but not atoms. The iPhones that distract us from our environment also distract us from how strangely old & unchanged our current environment is. If you were to be in any room in 1973, everything would look the same except for our phones. This explains his old Founders Fund tagline: “We wanted flying cars, instead we got 140 characters.”
Zooming out, people don’t understand how important economic growth is. It’s the only thing sustaining the planet. Without it, we go into a malthusian war. Indeed: The only way our societies have worked for at least 250 years is by economic growth. Parliamentary democracies are built on an ever-expanding pie that they can continue subdividing. Once the pie is no longer expanding, everything turns zero-sum.
The term “Cyberdeck” was first coined in Gibson’s 1984 literary masterpiece, Neuromancer. He rewrote parts of Neuromancer several times after the release of Ridley Scott’s Blade Runner. Blade Runner was based on Philip K. Dick’s 1968 novel Do Androids Dream of Electric Sheep. Scott, Dick, Brunner’s The Shockwave Rider, Goddard’s Alphaville and work by futurists such as Syd Mead and Moebius make the title of “father of Cyberpunk” hard to hang on Gibson alone. But he’s clearly a very important character in the development of Cyberpunk culture.
Just as Shakespeare brought in new words to describe new worlds, 1980s Gibson is Cyberpunk’s Great Bard. The Cyberdeck is just one of Gibson’s literary gifts. It’s the tool that lets Console Cowboys jack into the Matrix of Cyberspace and start hacking.
Anthropology starts from the recognition that a person - in the first instance at least - cannot exist apart from a group. Put differently, anthropology assumes that a human network always precedes its individual members, and that care and reproduction precede any form of solo heroics. Human babies don’t survive long if they are left to fend for themselves, and - even if they miraculously survived without others - they would not be able to speak language, which would make all future social interaction, relationships and trade near-impossible.
Let’s say that any weapon will have a component for damage, range, and projectiles (optional). Using Unity’s UI, you could create a weapon by dragging these components onto any GameObject and customizing the values of each one. Then, if the way projectiles are handled changes further into development, all you need to do is change one script, and all your weapons’ functionalities will be updated instead of just those defined at one level of a tree.
Fast inverse square root, sometimes referred to as Fast InvSqrt() or by the hexadecimal constant 0x5F3759DF, is an algorithm that estimates 1/sqrt(x), the reciprocal (or multiplicative inverse) of the square root of a 32-bit floating-point number x floating-point
floatQ_rsqrt(floatnumber){longi;floatx2,y;constfloatthreehalfs=1.5F;x2=number*0.5F;y=number;i=*(long*)&y;// evil floating point bit level hackingi=0x5f3759df-(i>>1);// what the fuck?y=*(float*)&i;y=y*(threehalfs-(x2*y*y));// 1st iteration// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removedreturny;}