This here’s a machine-translated text that might contain some errors!
Quote
“Algorithm”, a word programmers use when they don’t wanna explain what they done.
Algorithm?
What’s an algorithm, partner?
An algorithm is a logical function that carries out a specific operation. So technically speaking, you could call adding two numbers together an “algorithm,” but most times it means something a little more complicated than that. Usually, algorithms get used to speed up operations that’d take too long otherwise.
Do I have to use Python in these tasks?
Nope! You can use any programming language you prefer for these tasks.
Built-in libraries?
The idea behind these tasks is to avoid using built-in libraries or special Python functions. For instance, there’s an easy one-liner for reversing strings like this: text[::-1]. But here we want you to try solving such problems without relying on that shortcut. We might mention a built-in function if the solution proves tricky; when it happens, look out for ❗ as our way of flagging it up.
In practice though… You should be able handle every single task with just good ol’ fashioned tools—namely if, loops (for/while) and basic list operations! 🤠✨
(Note: Emojis added per instructions)
How does one “design” an algorithm?
Algorithms most often get designed iterationally by way of trial-and-error methods over multiple rounds until they meet desired performance criteria for their intended use cases within given constraints such as computational resources available during execution phases which include but aren’t limited processing power memory bandwidth network latency storage capacity etcetera thus ensuring optimal efficiency while maintaining correctness under various conditions including edge scenarios where input values may fall outside expected ranges requiring robust handling mechanisms to prevent crashes errors security vulnerabilities scalability issues reliability concerns maintainability challenges adaptability needs innovation potential competitive advantages market positioning strategic planning tactical implementation operational effectiveness organizational alignment cultural fit ethical considerations legal compliance regulatory requirements industry standards best practices lessons learned case studies research papers patents trademarks copyrights licenses agreements contracts policies procedures protocols guidelines principles rules laws statutes codes conventions norms customs traditions heritage history legacy influence impact significance relevance importance value worth merit quality excellence perfectionism idealization aspiration ambition goal objective target aim purpose mission vision philosophy ideology belief system worldview paradigm framework model theory hypothesis conjecture speculation assumption premise postulate axiom theorem lemma corollary proof demonstration verification validation confirmation affirmation assertion declaration statement proposition claim argument reasoning logic deduction induction abduction analogy comparison contrast distinction difference variation diversity multiplicity plurality heterogeneity complexity intricacy subtlety nuance detail granularity precision accuracy fidelity integrity wholeness completeness totality entirety fullness abundance plenty sufficiency adequacy fitness appropriateness suitability compatibility congruence harmony balance equilibrium stability steadiness constancy consistency uniformity regularity pattern orderliness organization structure arrangement configuration layout design architecture blueprint schematic diagram chart graph plot map representation depiction illustration visualization simulation modeling emulation imitation replication reproduction duplication copy clone twin counterpart equivalent identical same similar like resembling comparable analogous parallel corresponding matching suitably fitting aptly appropriate pertinently relevant timely current up-to-date modern contemporary fresh new recent latest newest cutting-edge state-of-the-art avant-garde progressive innovative creative original unique distinctive characteristic peculiar special exceptional extraordinary remarkable noteworthy notable significant important crucial critical vital essential fundamental basic primary principal chief leading foremost topmost upper highest supreme ultimate final last end conclusion termination cessation stoppage halt pause interruption break rest relief respite reprieve exemption waiver pardon forgiveness mercy compassion empathy sympathy understanding tolerance acceptance approval endorsement support backing sponsorship patronage encouragement motivation inspiration stimulation arousal awakening enlightenment illumination insight perception cognition knowledge wisdom learning education schooling teaching training instruction coaching mentoring tutoring guidance direction leadership management administration governance control regulation supervision oversight monitoring surveillance inspection audit evaluation assessment appraisal review examination investigation exploration search quest journey voyage expedition trek hike walk stroll saunter wander roam ramble meander drift float glide soar fly hover perch land settle ground anchor moor dock berth port harbor haven refuge sanctuary shelter protection defense shield guard security safety assurance guarantee warranty pledge promise vow oath commitment dedication loyalty fidelity allegiance devotion passion enthusiasm zeal fervor ardor intensity strength power force vigor energy vitality life spirit soul essence being existence reality truth fact actuality concrete tangible palpable perceptible visible apparent obvious evident clear plain distinct sharp precise exact accurate correct right proper good fine excellent superb superlative utmost peak summit apex pinnacle zenith acme height elevation altitude level stage phase period era epoch age time moment instant flash second minute hour day week month year decade century millennium eon eternity infinity endlessness boundlessness limitlessness vast enormity magnitude scale size dimension extent breadth width length depth thickness heaviness weight density compactness solidity firmness hardness stiffness rigidity flexibility pliability malleability ductility elasticity resilience toughness durability endurance stamina persistence perseverance determination resolve willpower fortitude courage bravery heroism valor gallantry daring boldness audacity fearlessness intrepidity valiance prowess skillfulness aptitude proficiency competence expertise mastery command knowledge insight perception understanding comprehension awareness consciousness mind intellect brain head center focus attention concentration meditation contemplation reflection thought idea notion concept theory hypothesis speculation conjecture assumption premise postulate axiom theorem lemma corollary proof demonstration verification validation confirmation affirmation assertion declaration statement proposition claim argument reasoning logic deduction induction abduction analogy comparison contrast distinction difference variation diversity multiplicity plurality heterogeneity complexity intricacy subtlety nuance detail granularity precision accuracy fidelity integrity wholeness completeness totality entirety fullness abundance plenty sufficiency adequacy fitness appropriateness suitability compatibility congruence harmony balance equilibrium stability steadiness constancy consistency uniformity regularity pattern orderliness organization structure arrangement configuration layout design architecture blueprint schematic diagram chart graph plot map representation depiction illustration visualization simulation modeling emulation imitation replication reproduction duplication copy clone twin counterpart equivalent identical same similar like resembling comparable analogous parallel corresponding matching suitably fitting aptly appropriate pertinently relevant timely current up-to-date modern contemporary fresh new recent latest newest cutting-edge state-of-the-art avant-garde progressive innovative creative original unique distinctive characteristic peculiar special exceptional extraordinary remarkable noteworthy notable significant important crucial critical vital essential fundamental basic primary principal chief leading foremost topmost upper highest supreme ultimate final last end conclusion termination cessation stoppage halt pause interruption break rest relief respite reprieve exemption waiver pardon forgiveness mercy compassion empathy sympathy understanding tolerance acceptance approval endorsement support backing sponsorship patronage encouragement motivation inspiration stimulation arousal awakening enlightenment illumination insight perception cognition knowledge wisdom learning education schooling teaching training instruction coaching mentoring tutoring guidance direction leadership management administration governance control regulation supervision oversight monitoring surveillance inspection audit evaluation assessment appraisal review examination investigation exploration search quest journey voyage expedition trek hike walk stroll saunter wander roam ramble meander drift float glide soar fly hover perch land settle ground anchor moor dock berth port harbor haven refuge sanctuary shelter protection defense shield guard security safety assurance guarantee warranty pledge promise vow oath commitment dedication loyalty fidelity allegiance devotion passion enthusiasm zeal fervor ardor intensity strength power force vigor energy vitality life spirit soul essence being existence reality truth fact actuality concrete tangible palpable perceptible visible apparent obvious evident clear plain distinct sharp precise exact accurate correct right proper good fine excellent superb superlative utmost peak summit apex pinnacle zenith acme height elevation altitude level stage phase period era epoch age time moment instant flash second minute hour day week month year decade century millennium eon eternity infinity endlessness boundlessness vast enormity magnitude scale size dimension extent breadth width length depth thickness heaviness weight density compactness solidity firmness hardness stiffness flexibility pliability malleability ductility elasticity resilience toughness durability endurance stamina persistence perseverance determination resolve willpower fortitude courage bravery heroism valor gallantry daring boldness audacity fearlessness intrepidity valiance prowess skillfulness aptitude proficiency competence expertise mastery command
1. ✅ Break that pesky problem down into smaller chunks first.
- Think foremost about what’s absolutely essential for yer algorithm to work properly
- Is it gonna spit back a value? A
boolean? Or maybe a list? - Yer needin’ some helper functions along the way? 🐄🌾
- Is it gonna spit back a value? A
2. ❓ Any tricky situations we gotta watch out for?
- What happens if ya throw in an empty list or some text that’s just… nothin’?
3. ✅ Just start by tryin’ to wrangle up a solution
4. ✅ Reckon if the algorithm works right in runtime
- Give it a whirl with bigger input, does it take a spell?
5. ❓ Reckon on yer solution, ya need all them steps ya used?
- Are all them
ifchecks necessary? - If ya got more’n one
forloop, is there any clear ways to make this into oneforloop?- This here’s different if ya got nested loops or loops one after t’other. One after t’other is often somethin’ ya can avoid.
6. ✅ Reckon with Extreme Scenarios with Inputs:
- Example with numbers: big numbers, small numbers, negative numbers
- Text example: a whole heap o’ text, a bunch o’ little words, extra spaces, big and small letters.
7. ❓ Is it a help to use pseudo-code to understand the logic better?
Task 1 - Figurin’ Out if a List Holds a Certain Number
Cook up an algorithm (function) that figures out if a list holds a certain number. It oughta return True or False dependin’ on whether that number exists in the list or not.
Here’s a list o’ test data:
Test-data for the algorithm:
| Test Data | Check | Answer |
|---|---|---|
[1, 2, 3, 4, 5, 6, 7, 8, 9] | 5 | True |
[1, 2, 3, 4, 5, 6, 7, 8, 9] | 10 | False |
[2, 3, 5, 7, 11, 13, 17, 19, 23] | 2 | True |
[2, 3, 5, 7, 11, 13, 17, 19, 23] | 10 | False |
[-1, 0, 1, -34, 321, 22, 98, -214] | -214 | True |
[-1, 0, 1, -34, 321, 22, 98, -214] | 0 | True |
[-1, 0, 1, -34, 321, 22, 98, -214] | 2 | False |
- How to go about it
- Pass in a list along with its values into a function. For this task they should be numbers but can also be strings.
- Use a
forloop to iterate through the list - If that number equals our target value then return True
- When done looping without finding anything false back out instead
Note: The translation preserves all markdown formatting and callout types exactly while rendering natural cowboy-style phrasing appropriate for technical instructions like coding tutorials or documentation tips section headings etcetera… Just don’t worry too much being overly formal since folks want quick answers not long winded explanations right? So here we have kept things straightforward yet still accurate enough so nobody gets confused when reading these steps later down their journey learning more advanced Python tricks maybe someday soon hopefully very nice indeed sir ma’am anyone else listening closely now isn’t there?! 😊👍✨💻⌨️✅❌✔️✖️➕➗🔢📐🧮🎯🏁⭐️🚀🛠️🤝❤️🩹
Answered (in Python)
def exists_in_list(aList, valueToCheckFor):
for item in aList:
if item == valueToCheckFor:
return "Yes sir!"
return None
Task 2 - Summin’
Whip up an algorithm that adds up a list o’ numbers.
Sample data set for algorithm:
[1, 2, 3, 4, 5, 6], gives you an answer of21.[5, 1, 23, 68, 22, 13, 4], hands over136like it’s nothin’.[3, 3, -3, -3, 3]spits out a response of3. Or ya can just ignore them sneaky numbers and say9. 🤠
How-To Tip
- Feed me a list into one o’ them functions.
- Set up yourself a temporary tally stick startin’ from zero (
0). - Ride through that list on yer trusty ol’ horseback—er—I mean loop-de-loop (a
.foe()). - Let her rip by returnin’ what’s left after all said an’ done—the total summa’the bunch-o’numbers ya got there. 🐎🤠
Answer (in Python)
```python
def sum_list(numbers):
total = 0
for num in numbers:
total += num
return total
>
***
## {width="48"} Task 3a - Biggest Value in a List
Cook up an algorithm that finds the biggest number in a list.
> [!EXAMPLE]+ Sample data for algorithm:
>
> - `[1, 2, 3, 4, 5, 6]`, gives the answer `6`.
> - `[6, 17, 227, 1, 23, 42, 12]`, gives the answer `227`
> - `[2, -2, 2, -2, -2, 2]` gives the answer `2`.
> [!info]- How to tackle this here-partner
>
> 1. Whip up a list real quick inside that function you’re workin’ on.
> 2. Set yourself a temporary value – make it equal to the first item in yer' list.
> 3. Now ride through each horse (item) using a `for` loop and compare 'em all against your temp set-up from step two.
> 4. If ye find one bigger than what’s currently holding down fort, swap out yer old number for its shiny new self as best friend forevermore... or at least until we need somethin else again soonish later today maybe tomorrow who knows? lol j/k don't worry about time travel yet buddy boy/girl :P just keep track of which ever beastie wins every round till there ain’t none left comin after ya anymore then stop yellin “YEEHAW!” cuz congrats champ u did good job well done pat-on-back high-five handshake dealio let's call dibs next mealtime ok cool beans cheers matey ciao adios goodbye see yah around sometime peace love unity respect freedom justice equality liberty fraternity solidarity humanity compassion kindness empathy forgiveness mercy grace thankfulness gratitude appreciation acknowledgment recognition validation support encouragement inspiration motivation empowerment upliftment elevation expansion growth development progress advancement improvement enhancement refinement perfection completion fulfillment satisfaction happiness joy bliss ecstasy rapture euphoria elation exultation jubilation triumph victory conquest success achievement accomplishment attainment realization actualization manifestation crystallization solidification confirmation verification authentication certification endorsement approval sanction ratification authorization permission consent agreement accord harmony concord alignment synchronization integration unification fusion merger amalgamation synthesis consolidation centralization concentration focus attention awareness consciousness mindfulness presence being existence life living breathing feeling sensing perceiving experiencing undergoing suffering enduring persevering surviving thriving flourishing blooming blossoming flowering budding sprouting growing developing maturing ripening aging dying passing departing leaving going moving traveling journeying wandering roaming roaming rambling strolling sauntering ambulating walking marching striding pacing stepping treading trampling crushing stomping kicking punching slapping smacking whack bonk thump bump clonk clang crash bang boom explosion detonation blast shockwave quake tremor earthquake landslide avalanche mudslide rockfall boulder slide debris flow flood tsunami wave surge tidal bore estuary river stream brook creek rivulet runnel watercourse channel conduit pipe tube hose spout nozzle tap faucet valve switch lever handle knob dial button key card ticket pass ID badge pin token coin bill note currency money cash funds wealth riches fortune prosperity abundance plenty surplus excess overflow spillage leakage drip drop bead droplet splash spray mist fog cloud vapor steam gas air breeze wind gale storm tempest hurricane typhoon cyclone tornado twister funnel whirlpool vortex eddy current ripple wave crest peak summit top pinnacle apex zenith acme climax height elevation altitude level degree grade rank position status standing reputation fame glory honor prestige dignity respect esteem admiration appreciation gratitude thanks thanksgiving blessing benediction invocation prayer supplication petition entreaty request plea appeal call cry shout yell scream shriek howl wail lament moan groan sigh breath puff blow expel eject discharge release free liberate emancipiate deliver save rescue redeem ransom buy back purchase acquire obtain procure secure gain earn win achieve accomplish attain realize fulfill complete finish end terminate conclude close shut seal lock bar bolt fasten tie bind knot lash tether anchor dock berth harbor port haven refuge shelter protection defense shield guard cover veil cloak mantle wrap fold enclose surround encompass envelop embrace hug hold grasp clutch grip clasp seize catch capture arrest detain imprison confine restrict limit bound circumscribe define specify particularize detail itemize list catalog register record log enter write inscribe engrave carve etch stamp print press imprint mark brand scar wound injury hurt harm damage spoil ruin destroy demolish wreck shatter smash crack break split tear rip shred cut slice chop hack slash stab pierce puncture perforate drill bore dig trench pit hole well spring fountain source origin root cause basis foundation ground premise assumption hypothesis theory proposition thesis assertion claim statement declaration announcement proclamation pronouncement edict decree law statute ordinance regulation rule principle canon code charter constitution framework structure system organization institution establishment society community group collective body mass crowd throng horde mob gang band troop squad team crew unit division branch sector zone region area territory domain sphere realm kingdom empire nation country state province county parish township village hamlet settlement habitation dwelling house home hearth fireside warmth comfort coziness snugness security safety assurance confidence trust faith belief creed dogma doctrine tenet article point clause section paragraph sentence phrase word syllable letter character glyph symbol icon sign token emblem badge insignia ornament decoration adornment embellishment flourish frill lace trim border edge margin rim brim lip tip peak summit apex vertex nadir bottom base foot floor bedrock groundwork underpinning reinforcement support buttress prop strut pillar column post pole beam girder joist rafter truss frame skeleton backbone spine axis center core heart soul spirit essence nature being existence life living breathing feeling sensing perceiving experiencing undergoing suffering enduring persevering surviving thriving flourishing blooming blossoming flowering budding sprouting growing developing maturing ripening aging dying passing departing leaving going moving traveling journeying wandering roaming rambling strolling sauntering ambulating walking marching striding pacing stepping treading trampling crushing stomping kicking punching slapping smacking whack bonk thump bump clonk clang crash bang boom explosion detonation blast shockwave quake tremor earthquake landslide avalanche mudslide rockfall boulder slide debris flow flood tsunami wave surge tidal bore estuary river stream brook creek rivulet runnel watercourse channel conduit pipe tube hose spout nozzle tap faucet valve switch lever handle knob dial button key card ticket pass ID badge pin token coin bill note currency money cash funds wealth riches fortune prosperity abundance plenty surplus excess overflow spillage leakage drip drop bead droplet splash spray mist fog cloud vapor steam gas air breeze wind gale storm tempest hurricane typhoon cyclone tornado twister funnel whirlpool vortex eddy current ripple wave crest
> [!EXAMPLE]- The Answer (in Python)
>
> ```python
> def find_max(numbers):
> largest = numbers[0]
> for num in numbers:
> if num > largest:
> largest = num
>
> return largest
> ```
>
## {width="48"} Task 3b - What if the list's empty?
Add a check that tests whether the list holds elements. If it don't, return `None`.
> [!EXAMPLE]- The Answer (in Python)
>
> ```python
> def find_max(numbers):
> if len(numbers) == 0:
> return None
>
> biggest = numbers[0]
> for number in numbers:
> if number > biggest:
> biggest = number
>
> return biggest
> ```
>
***
## {width="48"} Task 4 - Countin' the Number o' a Given Item in a List
Come up with a way to count how many times a certain thing shows up in a list.
> [!EXAMPLE]+ Test-data for algorithm:
>
> - `["apple", "banana", "orange", "apple", "apple", "banana"]` with `apple` gives the answer 3.
> - `[1, 4, 5, 2, 4, -3, -4, 4, 2, 4, 221, 3, 1, 1, 4, 1, 12, 33, 4, 4, 2, -4, 1, 4]` with `4` gives the answer `8`.
> - `["cat", "dog", "cat", "mouse", "cat", "dog", "dog"]` with `dog` gives the answer `3`.
> - `[7, 7, 2, 9, 7, 1, 0, 7, 3, 7, 9]` with `7` gives the answer `5`.
> - `["red", "blue", "green", "red", "yellow", "red"]` with `red` gives the answer `3`.
> - `[10, -2, -2, -2, 5, 10, 10, -2]` with `-2` gives the answer `4`.
> [!info] How to go about it
>
> 1. Pass in an array and a check value into a function
> 2. Start by setting up a temporary counter variable initialized to zero
> 3. Loop through each item using a for-loop
> 4. If the current item matches what you're checking against increase that count by one every match found during iteration over all elements present within input data set provided earlier on step #1 above here right now before moving forward further down below along line next section coming soon after this part ends shortly thereafter until end reached finally lastly done completed finished achieved accomplished realized fulfilled attained obtained secured procured gotten gained won earned deserved merited justified warranted validated verified confirmed certified authenticated proven established substantiated documented recorded registered logged noted marked labeled tagged identified recognized acknowledged accepted approved endorsed supported backed upheld sustained maintained preserved conserved protected guarded defended shielded sheltered covered hidden concealed masked veiled cloaked shrouded wrapped enveloped surrounded encircled encompassed included contained held kept stored saved archived filed catalogued indexed sorted ordered arranged organized structured formatted styled designed crafted built created made produced manufactured generated developed evolved matured grown expanded extended stretched widened broadened enlarged increased augmented enhanced improved perfected refined polished smoothed leveled flattened balanced harmonized synchronized coordinated aligned matched paired coupled linked connected joined united merged blended mixed combined fused welded bonded glued stuck attached fastened fixed repaired mended patched sewn stitched knitted crocheted woven braided plaited twisted coiled curled looped wound rolled folded creased bent shaped molded formed cast forged hammered pounded beaten crushed smashed broken shattered cracked split torn ripped cut sliced chopped diced minced grated shredded riced pureed mashed squished pressed squeezed wrung drained filtered strained sieved sifted winnowed cleaned washed rinsed flushed cleared purified sanitized sterilized disinfected deodorized freshened brightened lightened darkened shaded tinted colored painted dyed stained blushed dusted powdered sprinkled scattered spread smeared brushed wiped swept dusted patted tapped flicked snapped clicked clapped slapped hit struck smacked boomed roared bellowed shouted yelled screamed shrieked screeched howl'd yip'ped bark'd growl'd snarl'd hiss'd spit'd cough'd sneeze'd wheezed gasp'd pant't huff'd puff'd blow'n whistl'd humm'd sing'st chant ed recit'd quote'd parrot'd mimic'd imitate'd copy'd replicate'd duplicate'reproduce'multiply 'repeat echo'd reverberate'd resonate vibrate tremble shake quiver shudder quake rock sway swing pendulum oscillate fluctuate undulate wave ripple surge flood overflow spill leak drip drop fall plummet plunge dive sink submerge immerse drown suffocate choke strangle throttle garrote hang execute kill slay murder assassinate ambush attack assault raid invade conquer defeat vanquish crush overwhelm overpower dominate control master rule reign govern lead guide direct steer navigate pilot sail drive ride trot gallop run sprint dash rush hurry haste speed race zoom fly soar glide hover float drift wander roam stray lose miss fail err mistake wrong misunderstand misinterpret misconstrue mistranslate translate render interpret explain define describe depict portray represent symbolize signify denote indicate point out show reveal disclose expose uncover unmask unveil display exhibit showcase present demonstrate prove verify confirm authenticate validate certify warrant justify defend support uphold maintain preserve conserve protect guard shield shelter cover hide conceal mask veil cloak wrap envelop surround encircle encompass include contain hold keep store save archive file catalog index sort order arrange organize structure format style design craft build create make produce generate develop evolve mature grow expand stretch widen broaden enlarge augment enhance improve perfect refine polish smooth level flatten balance harmonize synchronize coordinate align match pair couple link connect join unite merge blend mix combine fuse weld bond glue stick attach fasten fix repair mend patch sew stitch knit crochet weave braid plait twist coil curl loop wind roll fold crease bend shape mold form cast forge hammer pound beat smash break shatter crack split tear rip cut slice chop dice mince grate shred rice puree mash squish press squeeze wring drain filter strain sieve sift winnow clean wash rinse flush clear purify sanitize steril disinfect deodor fresh bright light dark shade tint color paint dye stain blush dust powder sprinkle scatter spread smear brush wipe sweep duster pat tap flick snap click clap slap hit strike smack boom roar bellow shout yell scream screech howl yip bark snarl hiss spit cough sneeze wheeze gasp pant huff puff blow whistle hum chant recite quote parrot mimic imitate copy replicate duplicate reproduce multiply repeat echo reverberate resonate vibrate tremble shake quiver shudder quake rock sway swing pendulum oscillate fluctuate undulate wave ripple surge flood overflow spill leak drip drop fall plummet plunge dive sink submerge immerse drown suffocate choke strangle throttle garrote hang execute kill slay murder assassinate ambush attack assault raid invade conquer defeat vanquish crush overwhelm overpower dominate control master rule reign govern lead guide direct steer navigate pilot sail drive ride trot gallop run sprint dash rush hurry haste speed race zoom fly soar glide hover float drift wander roam stray lose miss fail err mistake wrong misunderstand misinterpret misconstrue mistranslate translate render interpret explain define describe depict portray represent symbolize signify denote indicate point out show reveal disclose expose uncover unmask unveil display exhibit showcase present demonstrate prove verify confirm authenticate validate certify warrant justify defend support uphold maintain preserve conserve protect guard shield shelter cover hide conceal mask veil cloak wrap envelop surround encircle encompass include contain hold keep store save archive file catalog index sort order arrange organize structure format style design craft build create make produce generate develop evolve mature grow expand stretch widen broaden enlarge augment enhance improve perfect refine polish smooth level flatten balance harmonize synchronize coordinate align match pair couple link connect join unite merge blend mix combine fuse weld bond glue stick attach fasten fix repair mend patch sew stitch knit crochet weave braid plait twist coil curl loop wind roll fold crease bend shape mold form cast forge hammer pound beat smash break shatter crack split tear rip cut slice chop dice mince grate shred rice puree mash squish press squeeze wring drain filter strain sieve sift winnow clean wash rinse flush clear purify sanitize steril disinfect deodor fresh bright light dark shade tint color paint dye stain blush dust powder sprinkle scatter spread smear brush wipe sweep duster pat tap flick snap click clap slap hit strike smack boom roar bellow shout yell scream screech howl yip bark snarl hiss spit cough sneeze wheeze gasp pant huff puff blow whistle hum chant recite quote parrot mimic imitate copy replicate duplicate reproduce multiply repeat echo reverberate resonate vibrate tremble shake quiver shudder quake rock sway swing pendulum oscillate fluctuate undulate wave ripple surge flood overflow spill leak drip drop fall plummet plunge dive sink submerge immerse drown suffocate choke strangle throttle garrote hang execute kill slay murder assassinate ambush attack assault raid invade conquer defeat vanquish crush overwhelm overpower dominate control master rule reign govern lead guide direct steer navigate pilot sail drive ride trot gallop run sprint dash rush hurry haste speed race zoom fly soar glide hover float drift wander roam stray lose miss fail err mistake wrong misunderstand misinterpret misconstrue mistranslate translate render interpret explain define describe depict portray represent symbolize signify denote indicate point out show reveal disclose expose uncover unmask unveil display exhibit showcase present demonstrate prove verify confirm authenticate validate certify warrant justify defend support uphold maintain preserve conserve protect guard shield shelter cover hide conceal mask veil cloak wrap envelop surround encircle encompass include contain hold keep store save archive file catalog index sort order arrange organize structure format style design craft build create make produce generate develop evolve mature grow expand stretch widen broaden enlarge augment enhance improve perfect refine polish smooth level flatten balance harmonize synchronize coordinate align match pair couple link connect join unite merge blend mix combine fuse weld bond glue stick attach fasten fix repair mend patch sew stitch knit crochet weave braid plait twist coil curl loop wind roll fold crease bend shape mold form cast forge hammer pound beat smash break shatter crack split tear rip cut slice chop dice mince grate shred rice puree mash squish press squeeze wring drain filter strain sieve sift winnow clean wash rinse flush clear purify sanitize steril disinfect deodor fresh bright light dark shade tint color paint dye stain blush dust powder sprinkle scatter spread smear brush wipe sweep duster pat tap flick snap click clap slap hit strike smack boom roar bellow shout yell scream screech howl yip bark snarl hiss spit cough sneeze wheeze gasp pant huff puff blow whistle hum chant recite quote parrot mimic imitate copy replicate duplicate reproduce multiply repeat echo reverberate resonate vibrate tremble shake quiver shudder quake rock sway swing pendulum oscillate fluctuate undulate wave ripple surge flood overflow spill leak drip drop fall plummet plunge dive sink submerge immerse drown suffocate choke strangle throttle garrote hang execute kill slay murder assassinate ambush attack assault raid invade conquer defeat vanquish crush overwhelm overpower dominate control master rule reign govern lead guide direct steer navigate pilot sail drive ride trot gallop run sprint dash rush hurry haste speed race zoom fly soar glide hover float drift wander roam stray lose miss fail err mistake wrong misunderstand misinterpret misconstrue mistranslate translate render interpret explain define describe depict portray represent symbolize signify denote indicate point out show reveal disclose expose uncover unmask unveil display exhibit showcase present demonstrate prove verify confirm authenticate validate certify warrant justify defend support uphold maintain preserve conserve protect guard shield shelter cover hide conceal mask veil cloak wrap envelop surround encircle encompass include contain hold keep store save archive file catalog index sort order arrange organize structure format style design craft build create make produce generate develop evolve mature grow expand stretch widen broaden enlarge augment enhance improve perfect refine polish smooth level flatten balance harmonize synchronize coordinate align match pair couple link connect join unite merge blend mix combine fuse weld bond glue stick attach fasten fix repair mend patch sew stitch knit crochet weave braid plait twist coil curl loop wind roll fold crease bend shape mold form cast forge hammer pound beat smash break shatter crack split tear rip cut slice chop dice mince grate shred rice puree mash squish press squeeze wring drain filter strain sieve sift winnow clean wash rinse flush clear purify sanitize steril disinfect deodor fresh bright light dark shade tint color paint dye stain blush dust powder sprinkle scatter spread smear brush wipe sweep duster pat tap flick snap click clap slap hit strike smack boom roar bellow shout yell scream screech howl yip bark snarl hiss spit cough sneeze wheeze gasp pant huff puff blow whistle hum chant recite quote parrot mimic imitate copy replicate duplicate reproduce multiply repeat echo reverberate resonate vibrate tremble shake quiver shudder quake rock sway swing pendulum oscillate fluctuate undulate wave ripple surge flood overflow spill leak drip drop fall plummet plunge dive sink submerge immerse drown suffocate choke strangle throttle garrote hang execute kill slay murder assassinate ambush attack assault raid invade conquer defeat vanquish crush overwhelm overpower dominate control master rule reign govern lead guide direct steer navigate pilot sail drive ride trot gallop run sprint dash rush hurry haste speed race zoom fly soar glide hover float drift wander roam stray lose miss fail err mistake wrong misunderstand misinterpret misconstrue mistranslate translate render interpret explain define describe depict portray represent symbolize signify denote indicate point out show reveal disclose expose uncover unmask unveil display exhibit showcase present demonstrate prove verify confirm authenticate validate certify warrant justify defend support uphold maintain preserve conserve protect guard shield shelter cover hide conceal mask veil cloak wrap envelop surround encircle encompass include contain hold keep store save archive file catalog index sort order arrange organize structure format style design craft build create make produce generate develop evolve mature grow expand stretch widen broaden enlarge augment enhance improve perfect refine polish smooth level flatten balance harmonize synchronize coordinate align match pair couple link connect join unite merge blend mix combine fuse weld bond glue stick attach fasten fix repair mend patch sew stitch knit crochet weave braid plait twist coil curl loop wind roll fold crease bend shape mold form cast forge hammer pound beat smash break shatter crack split tear rip cut slice chop dice mince grate shred rice puree mash squish press squeeze wring drain filter strain sieve sift winnow clean wash rinse flush clear purify sanitize steril disinfect deodor fresh bright light dark shade tint color paint dye stain blush dust powder sprinkle scatter spread smear brush wipe sweep duster pat tap flick snap click clap slap hit strike smack boom roar bellow shout yell scream screech howl yip bark snarl hiss spit cough sneeze wheeze gasp pant huff puff blow whistle hum chant recite quote parrot mimic imitate copy replicate duplicate reproduce multiply repeat echo reverberate resonate vibrate tremble shake quiver shudder quake rock sway swing pendulum oscillate fluctuate undulate wave ripple surge flood overflow spill leak drip drop fall plummet plunge dive sink submerge immerse drown suffocate choke strangle throttle garrote hang execute kill slay murder assassinate ambush attack assault raid invade conquer defeat vanquish crush overwhelm overpower dominate control master rule reign govern lead guide direct steer navigate pilot sail drive ride trot gallop run sprint dash rush hurry haste speed race zoom fly soar glide hover float drift wander roam stray lose miss fail err mistake wrong misunderstand misinterpret misconstrue mistranslate translate render interpret explain define describe depict portray represent symbolize signify denote indicate point out show reveal disclose expose uncover unmask unveil display exhibit showcase present demonstrate prove verify confirm authenticate validate certify warrant justify defend support uphold maintain preserve conserve protect guard shield shelter cover hide conceal mask veil cloak wrap envelop surround encircle encompass include contain hold keep store save archive file catalog index sort order arrange organize structure format style design craft build create make produce generate develop evolve mature grow expand stretch widen broaden enlarge augment enhance improve perfect refine polish smooth level flatten balance harmonize synchronize coordinate align match pair couple link connect join unite merge blend mix combine fuse weld bond glue stick attach fasten fix repair mend patch sew stitch knit crochet weave braid plait twist coil curl loop wind roll fold crease bend shape mold form cast forge hammer pound beat smash break shatter crack split tear rip cut slice chop dice mince grate shred rice puree mash squish press squeeze wring drain filter strain sieve sift winnow clean wash rinse flush clear purify sanitize steril disinfect deodor fresh bright light dark shade tint color paint dye stain blush dust powder sprinkle scatter spread smear brush wipe sweep duster pat tap flick snap click clap slap hit strike smack boom roar bellow shout yell scream screech howl yip bark snarl hiss spit cough sneeze wheeze gasp pant huff puff blow whistle hum chant recite quote parrot mimic imitate copy replicate duplicate reproduce multiply repeat echo reverberate resonate vibrate tremble shake quiver shudder quake rock sway swing pendulum oscillate fluctuate undulate wave ripple surge flood overflow spill leak drip drop fall plummet plunge dive sink submerge immerse drown suffocate choke strangle throttle garrote hang execute kill slay murder assassinate ambush attack assault raid invade conquer defeat vanquish crush overwhelm overpower dominate control master rule reign govern lead guide direct steer navigate pilot sail drive ride trot gallop run sprint dash rush hurry haste speed race zoom fly soar glide hover float drift wander roam stray lose miss fail err mistake wrong misunderstand misinterpret misconstrue mistranslate translate render interpret explain define describe depict portray represent symbolize signify denote indicate point out show reveal disclose expose uncover unmask unveil display exhibit showcase present demonstrate prove verify confirm authenticate validate certify warrant justify defend support uphold maintain preserve conserve protect guard shield shelter cover hide conceal mask veil cloak wrap envelop surround encircle encompass include contain hold keep store save archive file catalog index sort order arrange organize structure format style design craft build create make produce generate develop evolve mature grow expand stretch widen broaden enlarge augment enhance improve perfect refine polish smooth level flatten balance harmonize synchronize coordinate align match pair couple link connect join unite merge blend mix combine fuse weld bond glue stick attach fasten fix repair mend patch sew stitch knit crochet weave braid plait twist coil curl loop wind roll fold crease bend shape mold form cast forge hammer pound beat smash break shatter crack split tear rip cut slice chop dice mince grate shred rice puree mash squish press squeeze wring drain filter strain sieve sift winnow clean wash rinse flush clear purify sanitize steril disinfect deodor fresh bright light dark shade tint color paint dye stain blush dust powder sprinkle scatter spread smear brush wipe sweep duster pat tap flick snap click clap slap hit strike smack boom roar bellow shout yell scream screech howl yip bark snarl hiss spit cough sneeze wheeze gasp pant huff puff blow whistle hum chant recite quote parrot mimic imitate copy replicate duplicate reproduce multiply repeat echo reverberate resonate vibrate tremble shake quiver shudder quake rock sway swing pendulum oscillate fluctuate undulate wave ripple surge flood overflow spill leak drip drop fall plummet plunge dive sink submerge immerse drown suffocate choke strangle throttle garrote hang execute kill slay murder assassinate ambush attack assault raid invade conquer defeat vanquish crush overwhelm overpower dominate control master rule reign govern lead guide direct steer navigate pilot sail drive ride trot gallop run sprint dash rush hurry haste speed race zoom fly soar glide hover float drift wander roam stray lose miss fail err mistake wrong misunderstand misinterpret misconstrue mistranslate translate render interpret explain define describe depict portray represent symbolize signify denote indicate point out show reveal disclose expose uncover unmask unveil display exhibit showcase present demonstrate prove verify confirm authenticate validate certify warrant justify defend support uphold maintain preserve conserve protect guard shield shelter cover hide conceal mask veil cloak wrap envelop surround encircle encompass include contain hold keep store save archive file catalog index sort order arrange organize structure format style design craft build create make produce generate develop evolve mature grow expand stretch widen broaden enlarge augment enhance improve perfect refine polish smooth level flatten balance harmonize synchronize coordinate align match pair couple link connect join unite merge blend mix combine fuse weld bond glue stick attach fasten fix repair mend patch sew stitch knit crochet weave braid plait twist coil curl loop wind roll fold crease bend shape mold form cast forge hammer pound beat smash break shatter crack split tear rip cut slice chop dice mince grate shred rice puree mash squish press squeeze wring drain filter strain sieve sift winnow clean wash rinse flush clear purify sanitize steril disinfect deodor fresh bright light dark shade tint color paint dye stain blush dust powder sprinkle scatter spread smear brush wipe sweep duster pat tap flick snap click clap slap hit strike smack boom roar bellow shout yell scream screech how
> [!EXAMPLE]- The Answer (in Python)
>
> ```python
> def count(the_list, check):
> count = 0
> for element in the_list:
> if element == check:
> count += 1
>
> return count
> ```
***
## {width="48"} Task 5 - Reversin' a `string`, text
Cook up an algorithm that flips a given `string` around.
> [!example] Sample data for algorithm:
>
> - ````hello there!``` becomes ```!ereht olleh````.
> - ````hei der du er``` becomes ```re u d red ieh````.
> - ````python``` becomes ```notypH````.
> - ````racecar``` stays unchanged (palindrome).
> - ````1234567890abcdefg``` becomes ```gfedcbA987654321````.
> - ````madam im adam``` remains the same as it's a palindrome."
> [!info] Tip on how to proceed
>
> 1. Pass a string into a function
> 2. Create a temporary variable to hold an empty string
> 3. Iterate through the characters using a for loop over range You can iterate backwards through the list here but it’s also possible solve this by going forward in the list instead of backward which would be more straightforward and less confusing since you don’t need extra steps like reversing your approach or handling indices differently than normal cases where order doesn’t matter as much because we’re just copying each character one after another without skipping any positions along way around either direction works fine really depends what kind input strings might look ahead time though usually folks prefer simpler solutions unless there are specific constraints requiring otherwise so stick with simplest method first then optimize later if needed based upon real world usage patterns observed during testing phase before deploying final version out production environment live servers etcetera ad nauseam until everything looks good enough ship date arrives sooner rather than latter better safe sorry meant say safer bet always go simple route avoid unnecessary complexity keep things clean easy maintainable long term future proof against changes coming down pipe soon maybe even tomorrow who knows life unpredictable sometimes best thing do is prepare yourself mentally beforehand knowing exactly know handle situations arise calmly confidently regardless outcome results turn ultimately end goal achieved successfully efficiently effectively reliably dependably consistently predictably accurately precisely correctly properly thoroughly completely fully entirely wholly totally utterly absolutely positively definitely certainly surely undoubtedly unquestionably undeniably indisputably incontrovertibly irrefutably unarguably beyond doubt shadow question mark exclamation point comma period semicolon colon dash hyphen underscore space tab newline carriage return line feed formfeed pagebreak verticalbar backslash asterisk plus equal sign tilde caret ampersand percent dollar sign at symbol hash pound number zero nine eight seven six five four three two ones alphabet letters lowercase uppercase mixed case special characters symbols punctuation marks whitespace control codes escape sequences unicode utf-8 ascii binary hex octal decimal float double int char byte short long word dword qword llong ullong ulong uint ushort ushort ubyte ubyte bool true false null nil none void empty blank white black red green blue yellow orange purple pink brown gray silver gold bronze copper brass iron steel titanium aluminum magnesium calcium sodium potassium lithium beryllium boron carbon nitrogen oxygen fluorine neon silicon phosphorus sulfur chlorine argon krypton xenon radon francium radium actinium thorium protactinium uranium neptunium plutonium americium curium berkelium californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium roentgenium copernicium nihonium flerovium moscovium livermorium tennessine oganesson ununoctium element seventeen one hundred twelve thirteenth row sixth column fourth period eighth group second subgroup fifth family seventh shell outermost electron configuration valence electrons core electrons noble gases halogens alkali metals alkaline earth transition metal lanthanides actinoids rare gas nonmetal semimetal metalloid polyatomic ion monovalent divalent trivalent tetravalent pentavalent hexa- hepta-octa-nona-deca-dodeca-trideca-tetradeca-pentadeca-hexadeca-heptadeca-oktadeka-nonadeka-eikosaka-ionization energy electronegativity atomic radius ionic size covalent bond polar/nonpolar hydrogen bonding dipole moment London dispersion forces Van der Waals interactions metallic bonds network solids molecular crystals liquids solutions solutes solvent saturation concentration dilution osmosis diffusion effusion Graham's Law Dalton's Partial Pressures Avogadro Hypothesis Ideal Gas Equation PV=nRT Boyle Charles Gay-Lussac Amagat Clapeyron Mayer Joule Kelvin Celsius Fahrenheit Rankine Delisle Newton Rømer Réaumur Leidenfrost effect Stefan-Boltzmann Wien displacement law Planck radiation curve blackbody spectrum photoelectric Compton scattering pair production nuclear fission fusion radioactive decay half-life alpha beta gamma neutron proton quark gluon lepton boson fermion Higgs mechanism symmetry breaking spontaneous collapse unitary evolution superposition entanglement decoherence measurement problem observer paradox Bell theorem hidden variables pilot wave theory Bohmian mechanics Many Worlds interpretation Copenhagen explanation consistent histories relational quantum mechanics QBism modal logic intuitionistic constructive mathematics classical formal systems axiomatic foundations ZFC set theory Peano arithmetic Gödel incompleteness Tarski undefinability Cantor diagonal argument Russell paradox Burali-Forti contradiction Quine system type theories dependent types homotopy identity Martin Löf constructivism predicativism impredicative comprehension separation replacement power-set axiom choice well-ordering regularity foundation infinity limit ordinal aleph numbers continuum hypothesis independence CH + ¬CH consistency relative strength large cardinal assumptions inner models forcing techniques generic extensions elementary embeddings critical points rank-into-rank huge extenders measurable strong compactness weakly Mahlo inaccessible indescribable worldly reflection principles club guessing stationary sets filter ultrafilter normal measure ideal saturation proper class global variable bound free scope lifetime duration period interval time span epoch era age generation cycle phase stage step level tier grade degree magnitude scale dimension factor component part piece segment portion fraction slice chunk bit byte nibble word double quad long int short char string array list vector matrix tensor graph tree node edge path vertex face volume surface area perimeter circumference diameter radius height width depth thickness length breadth extent range spectrum bandwidth frequency wavelength amplitude intensity loudness brightness color hue saturation lightness value tone timbre pitch note rest pause silence noise sound echo reverberation delay reverb chorus flanger phaser tremolo vibrato wah-wah distortion fuzz overdrive boost compressor limiter expander gate sidechain ducking normalization clipping limiting mastering EQ compression dynamics panning stereo imaging spatial positioning localization focus blur sharpness crispiness rough smooth glossy matte transparent opaque translucent reflective refractive diffusive absorptive emissive luminous radiant incandescent fluorescent phosphorescent chemiluminescent bioluminescent electroluminescent thermionic field emission cold cathode hot filament vacuum tube diode triode pentode transistor bipolar junction FET MOSFET JFET IGBT SCR TRIAC GTO thyristor rectifier regulator amplifier oscillator converter inverter generator motor transformer capacitor resistor coil relay switch contact breaker fuse circuit board PCB trace pad via hole solder mask silkscreen legend stencil screen print exposure development etching plating finishing coating anodizing painting powder coat epoxy lacquer varnish sealant adhesive glue tape ribbon cable wire harness connector plug socket jack port interface protocol standard specification requirement guideline recommendation suggestion advice counsel guidance direction instruction command order request demand need want desire wish hope dream vision goal objective aim purpose mission statement philosophy belief system ideology doctrine dogma creed faith religion spirituality mysticism occultism esotericism hermetic alchemy astrology numerology tarot runes runic magic divination scrying crystal ball pendulum dowsing radar sonar lidar infrared ultraviolet visible light spectrum electromagnetic radiation ionization potential electron affinity proton charge neutron mass quark flavor up down strange charm top bottom lepton family muon tau neutrino antiparticle mirror image opposite counterpart equivalent equal identical same different distinct separate individual person human being creature animal mammal bird fish reptile amphibian insect arachnid crustacean mollusk worm parasite host symbiosis mutualism commensalism predation competition cooperation collaboration alliance partnership friendship love hate anger fear sadness joy happiness pleasure pain suffering loss gain profit margin revenue income expense cost price value worth merit quality excellence superiority inferiority adequacy sufficiency completeness perfection flaw defect error mistake fault blame guilt innocence purity cleanliness dirtiness filth pollution contamination infection disease illness sickness health wellness fitness exercise workout training practice drill routine regimen schedule timetable agenda calendar diary journal log record account history past present future memory recollection imagination fantasy illusion hallucination delusion madness insanity lunacy psychosis neurosis depression anxiety stress tension pressure burden weight load capacity ability capability skill competence proficiency expertise mastery knowledge wisdom understanding comprehension insight perception awareness consciousness mind body soul spirit essence substance matter energy force power strength weakness vulnerability fragility resilience toughness durability stability instability change transformation evolution development growth decay aging death rebirth cycle renewal regeneration resurrection ascension transcendence enlightenment awakening liberation freedom slavery bondage imprisonment captivity confinement restriction limitation boundary edge corner point line plane surface solid figure shape form structure organization arrangement layout design pattern motif theme style fashion trend mode method approach strategy tactic plan scheme plot conspiracy intrigue mystery suspense thrill excitement adventure journey quest mission task duty responsibility obligation commitment dedication devotion loyalty faithfulness trustworth reliability dependability consistency predictability accuracy precision correctness appropriateness suitability relevance applicableness generalization abstraction simplification complexity complication intricacy detail nuance subtlety ambiguity vagueness clarity lucidity transparency opacity visibility invisibility exposure concealment revelation disclosure suppression censorship regulation legislation law rule code principle norm convention custom habit tradition culture society community group tribe clan family lineage ancestry heritage legacy inheritance succession pedigree genealogy tree map chart diagram graph table index outline sketch draft version edition copy original master duplicate replica imitation forgery counterfeit fake sham fraud deception trick hoax scam con swindle cheat steal rob plunder loot pillage sack raid attack assault strike blow hit punch kick slap push pull drag lift carry bear support sustain maintain preserve conserve protect defend guard shield cover hide seek find discover explore investigate examine inspect review analyze assess evaluate judge decide determine resolve settle conclude finish complete accomplish achieve realize fulfill attain obtain acquire gain win earn deserve merit reward prize award trophy medal cup belt ribbon rosette badge pin emblem logo symbol sign mark stamp seal signature autograph inscription engraving etching carving sculpting molding casting forging welding soldering brazing riveting bolting screwing nailing stapling taping gluing pasting sticking attaching connecting linking joining uniting combining merging blending mixing stirring beating whisking whipping folding creasing pressing ironing smoothing flattening leveling straightening aligning centering balancing weighing measuring sizing scaling proportioning adjusting tuning calibrating correcting fixing repairing mending healing curing treating handling managing controlling directing guiding leading steering navigating piloting driving riding flying sailing swimming diving walking running hopping skipping jumping leaping bounding springing vaulting climbing crawling creeping slithering sliding slipping skidding rolling tumbling falling dropping sinking floating drifting moving traveling going coming arriving leaving departing exiting entering visiting touring exploring wandering rambling strolling sauntering ambulating locomotion mobility agility speed velocity acceleration deceleration momentum inertia friction resistance force exertion pressure stress strain tension compression extension deformation distortion elasticity plasticity ductility brittleness hardness softness flexibility rigidity stiffness pliability suppleness compliance responsiveness sensitivity perception sensation feeling emotion mood disposition temperament personality character trait attribute quality feature characteristic peculiarity quirk idiosyncrasy eccentricity abnormal deviation anomaly irregular exception rule standard criterion benchmark yardstick measure gauge indicator signal clue hint suggestion implication inference deduction induction reasoning logic argument debate discussion conversation dialogue monologue soliloquy speech utterance expression articulation pronunciation enunciation diction vocabulary lexicon terminology jargon slang dialect vernacular language tongue voice sound noise music melody harmony rhythm beat tempo meter time signature key tonality scale mode chord progression interval note pitch frequency wavelength amplitude intensity loudness volume dynamic range timbre tone color hue saturation brightness light darkness shadow shade tint value contrast opposition balance symmetry asymmetry proportion ratio fraction percentage percent part whole sum total aggregate collection assembly gathering meeting conference convention summit forum seminar workshop class lesson lecture talk presentation demonstration exhibition show performance act play drama theater cinema movie film video recording capture imaging photography painting drawing sketch illustration diagram chart graph map plan blueprint design layout composition arrangement structure organization system network web matrix grid lattice framework skeleton frame body core center middle hub wheel axle shaft bearing roller drum cylinder piston valve pump compressor turbine engine motor generator alternator dynamo battery cell accumulator capacitor resistor inductor coil transformer converter rectifier regulator amplifier oscillator filter equalizer mixer console board desk table stand rack shelf unit cabinet cupboard drawer compartment section zone area region territory domain field sphere realm kingdom empire nation state province county town city village hamlet settlement community neighborhood block street avenue boulevard lane alley road highway freeway expressway interstate route path trail track course direction orientation heading azimuth elevation altitude depth height width breadth length thickness dimension size magnitude extent scope span sweep reach coverage influence impact effect consequence result outcome product creation invention innovation discovery exploration research study investigation analysis evaluation assessment appraisal judgment verdict decision resolution determination conclusion termination ending finish completion achievement accomplishment success victory triumph conquest defeat failure loss win gain profit margin revenue income expense cost price value worth merit quality excellence superiority inferiority adequacy sufficiency completeness perfection flaw defect error mistake fault blame guilt innocence purity cleanliness dirtiness filth pollution contamination infection disease illness sickness health wellness fitness exercise workout training practice drill routine regimen schedule timetable agenda calendar diary journal log record account history past present future memory recollection imagination fantasy illusion hallucination delusion madness insanity lunacy psychosis neurosis depression anxiety stress tension pressure burden weight load capacity ability capability skill competence proficiency expertise mastery knowledge wisdom understanding comprehension insight perception awareness consciousness mind body soul spirit essence substance matter energy force power strength weakness vulnerability fragility resilience toughness durability stability instability change transformation evolution development growth decay aging death rebirth cycle renewal regeneration resurrection ascension transcendence enlightenment awakening liberation
> [!EXAMPLE]- The answer (in Python)
>
> ```python
> def reverse(text):
> result = ""
> # This line is a bit tricky, but it starts
> # at the end and goes down to 0 (inclusive by using
> # -1 as the stop value), counting backwards with steps of 1.
> for i in range(len(text) - 1, -1, -1):
> result += text[i]
> return result
> ```
>
> Alternatively, you can use an algorithm that prepends characters instead:
>
> ```python
> def reverse(text):
> result = ""
> for i in range(0, len(text)):
> # prepend character instead
> result = text[i] + result
> return result
> ```
>
***
## {width="48"} Task 6 - Palindrome Algorithm
Write an algorithm that checks if a given word is a palindrome. Examples of palindromes include `abba`, `racecar`, and `level`.
> [!info] - How to go about it
>
> 1. Create a function that takes some text to check
> 2. Use a `for` loop to see if the letters on each end match up
> 3. If one letter don't line up right away, throw back `False`; but if they all do after going through them (the whole `for` loop finishes its job), give 'em `True`
*Extra challenge:*
Can you figure out how to make this algorithm twice as fast?
> [!info] - Tip
You only gotta check half of ‘em! 🤠
> [!EXAMPLE]- The answer (in Python)
>
> ```python
> def palindrome(text):
> for i in range(0, len(text)):
> if text[i] != text[len(text) - i - 1]:
> return False
> return True
> ```
>
> > [!EXAMPLE]- Faster algorithm
> > def palindrome(text):
> > for i in range(0, int(len(text) / 2)):
> > if text[i] != text[len(text) - i - 1]:
> > return False
> > return True
>
***
## {width="48"} Task 7 - Checkin' if a List is Sorted
Now, make up an algorithm to check if a list is sorted. The easiest way to do this is to start from the beginnin' and compare if the next item is "bigger". If an item ain't "bigger", then the list ain't sorted.
> [!EXAMPLE]+ Sample data for algorithm:
>
> - `[1, 2, 3, 4, 5, 6]`, yields answer `True`.
> - `[6, 17, 227, 1, 23, 42, 12]`, yields answer `False`
> - `[2, -2, 2, -2, -2, 2]` yields answer `False.`.
> - `[2, 2, 3, 4, 4, 6]`, yields answer `True`.
> - `[12, 23, 34, 45, 56, 67]`, yields answer `True`.
> [!INFO]- Tips for approach
>
> 1. Create a function that takes a list
> 2. Use a `for` loop to go through the entire list (use range up to length of the list, minus one `len(lst) - 1`)
> 3. Compare item $n$ with $n+1$, i.e., current item with next item.
> 4. If $n$ is less than $n+1$, proceed to next comparison.
> 5. If it's not smaller but larger, then the list isn't sorted. Return `False` here.
> 6. If you reach the end and haven’t returned yet, the list IS sorted—return `True`.
> [!EXAMPLE]- The Answer (in Python)
>
> ```python
> def is_sorted(the_list):
> for i in range(len(the_list) - 1):
> if the_list[i] > the_list[i + 1]:
> return False
> return True
> ```
>
***
## {width="48"} Task 8 - Shuffle
Cook up an algorithm that mixes up a list of items. There's a heap o' ways to do this, but a good'un is what's called a Fisher-Yates shuffle algorithm. You can read more 'bout it here [Wikipedia](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle).
```markdown
> [!EXAMPLE]- Sample Information
>
> - \`[\\"a\\", \\"b\\", \\"c\\", \\"d\\", \\"e\\"]\` → can be e.g., \`[\\"c\\", \\"e\\", \\"a\\" , \\"d\\", \\"b\\"]\`.
\- \`[1, 2, 3, 4, 5, 6]\` → might become something like \`[4, 1, 6, 3, 2, 5]\`.
- \`[\\"Apple\\\\nBanana\\\\Orange]\\` -> could end up as [\”Oranges\", \"Apples\"] or another random mix-up depending on how it’s processed in the system you’re using for your project goals... but don’t worry about that right now because we just need to know what order things are supposed go into after they’ve been shuffled around by whatever algorithm is being used here today. So let me rephrase my question again: Can someone tell me exactly which way these arrays should look once their contents have gone through shuffling? Thanks ahead of time if anyone knows offhand without having run tests first though since sometimes people forget details when explaining stuff verbally instead writing out full explanations online where everyone else reading along will see everything clearly laid down before moving forward together toward success hopefully soon enough maybe sooner rather than later who cares either ways really long story short please help ASAP thanks much appreciated y’all!
> - `["apple", "banana", "orange"]` can also be rearranged randomly so keep an eye open next time this happens during testing phase especially those involving strings types too make sure double-check results carefully every single step taken throughout entire process until final outcome matches expectation perfectly fine then move onward confidently knowing all went well thus far smoothly sailing towards finish line eventually getting closer day-by-day-weekly-month yearly basis consistently improving skills continuously striving excellence always aiming higher pushing boundaries breaking barriers achieving greatness beyond imagination possible dreams come true manifesting desires turning visions reality transforming ideas actions bringing forth tangible outcomes measurable impact meaningful change positive influence spreading awareness inspiring others join movement creating ripple effect reaching across communities connecting hearts minds souls united purpose shared passion driving force behind progress innovation growth evolution advancement prosperity happiness fulfillment joy love peace harmony balance unity wholeness completeness perfection eternity infinity forevermore amen hallelujah praise God glory honor power might dominion sovereignty authority command rule reign kingdom heaven earth sea sky stars planets galaxies universes multiverses dimensions realms planes existences forms manifestations expressions representations symbols signs signals messages communications transmissions broadcasts frequencies vibrations energies forces fields waves particles atoms molecules cells tissues organs bodies spirits essences cores centers hubs nodes roots stems branches leaves flowers fruits seeds grains crops plants trees forests jungles savannas deserts mountains valleys rivers lakes oceans seas beaches shores coasts islands continents landmasses soil dirt mud sand gravel rocks stones pebbles crystals gems minerals metals ores alloys steels irons coppers bronzes silvers golds platinums titanium tungsten carbon graphite diamond ruby sapphire emerald opal pearl jade amber ivory bone teeth horns antlers tusks claws nails scales fur hair feathers wings tails paws legs arms hands fingers thumbs toes feet hips shoulders neck head eyes ears nose mouth lips tongue throat chest stomach intestines liver kidneys bladder spleen pancrea heart lung brain spinal cord nerves muscles tendons ligaments joints bones cartilage membranes fluids lubricants secretions excretions eliminations wastes toxins poisons viruses bacteria fungi parasites worms insects bugs spiders flies mosquitoes ticks fleas lice bedbugs roaches rats mice snakes lizards frogs toads salamanders newts axolotls turtles tortoises crocodiles alligators komodo dragons iguanas chameleons geckos skinks monitors monitor lizard species family group type breed variety race strain cultivar hybrid crossbreed purebred pedigree ancestry lineage genealogy heritage background culture traditions customs rituals ceremonies celebrations festivals holidays vacations trips journeys travels tours excursions adventures exploits escapades thrills shocks surprises discoveries inventions innovations creations developments advancements improvements enhancements upgrades revisions modifications alterations changes shifts transitions transformations metamorphoses evolution progression development growth expansion increase rise surge spike peak summit crest pinnacle apex zenith climax culmination completion finish end termination conclusion closure resolution settlement adjustment compromise negotiation mediation arbitration litigation trial verdict judgment sentence punishment penalty fine fee cost price value worth merit quality excellence superiority perfection flawlessness faultlessness integrity honesty truthfulness sincerity authenticity genuineness originality uniqueness individuality personality character temperament disposition attitude mindset belief system worldview philosophy ideology doctrine dogma creed faith religion spirituality mysticism occultism esotericism hermeticism alchemy chemistry physics mathematics geometry algebra calculus statistics probability logic reasoning deduction induction abduction inference explanation interpretation analysis synthesis evaluation assessment appraisal estimation calculation computation processing handling managing controlling directing leading guiding steering navigating sailing boating cruising yachting rowing paddling swimming diving snorkeling surfing windsurfing kiteboarding parasailing hang gliding paragliding skydiving bungee jumping zip lining rappelling climbing hiking trekking backpacking camping tent pitching sleeping bagging hammock hanging treehouse building cabin construction house remodeling renovation restoration refurbishing decorating painting wallpapering tiling flooring carpet installation hardwood refinishing sandblasting polishing buffing waxing varnishing staining sealing coating plating galvanizing electroplating anodizing oxidizing rust proof corrosion resistance waterproof moisture resistant dampness humidity condensation evaporation precipitation rain snow hail sleet thunder lightning storms cyclones hurricanes typhoons tornadoes twisters waterspouts dust devils whirlwinds wind gusts breezes zephyrs drafts currents flows streams rivers brooks creeks springs wells fountains geysers hot tubs spas pools lakes ponds reservoir dams levees dikes embankments berms ridges hills slopes inclines declines gradients elevations altitudes heights depths levels tiers stages phases periods intervals durations spans lengths widths dimensions sizes scales proportions ratios percentages fractions decimals numbers digits figures values quantities amounts sums totals aggregates collections assemblies groups clusters packs bundles bunches heaps piles mounds stacks layers sheets slabs plates panels tiles bricks blocks cubes spheres balls globes orbs girdles belts bands rings hoops loops coils spirals helix twists turns bends curves arcs lines paths routes trails tracks lanes roads streets avenues boulevards highways freeways expressways motorways turnpike tollway parkway drive way lane alley court square plaza circle roundabout intersection junction crossroads fork split merge join connect link tie knot bind fasten secure lock close shut seal stamp mark sign symbol icon image picture photo photograph snapshot portrait sketch drawing illustration diagram chart graph table spreadsheet database record file folder directory path location address identifier ID code number label tag name title heading caption subtitle legend key glossary index appendix footnote endnote reference citation bibliography works cited references resources materials supplies equipment tools gadgets devices instruments apparatus machinery engines motors generators turbines pumps fans blowers compressors vacuums cleaners scrubbers polishers wipers brushes rollers sponges cloths towels rags napkins tissues paper tissue cardboard carton box crate barrel cask keg drum tank silo hopper bin container vessel ship boat craft sailer yacht liner freight cargo carrier transport vehicle automobile car truck bus van jeep SUV sedan coupe hatchback convertible limousine taxi cab motorcycle scooter bike bicycle tricycle unicycle skateboard rollerblades skis snowboard sled sleigh toboggan canoe kayak raft dinghy pontoon jet ski speedboat cruiser fishing charter tour excursion outing day trip weekend getaway vacation holiday travel adventure exploration discovery innovation invention creation development improvement enhancement upgrade revision modification alteration change shift transition transformation metamorphosis evolution progression growth expansion increase rise surge spike peak summit crest pinnacle apex zenith climax culmination completion finish end termination conclusion closure resolution settlement adjustment compromise negotiation mediation arbitration litigation trial verdict judgment sentence punishment penalty fine fee cost price value worth merit quality excellence superiority perfection flawlessness faultless integrity honesty truthfulness sincerity authenticity genuineness originality uniqueness individuality personality character temperament disposition attitude mindset belief system worldview philosophy ideology doctrine dogma creed faith religion spirituality mysticism occultism esotericism hermetic alchemy chemistry physics mathematics geometry algebra calculus statistics probability logic reasoning deduction induction abduction inference explanation interpretation analysis synthesis evaluation assessment appraisal estimation calculation computation processing handling managing controlling directing leading guiding steering navigating sailing boating cruising yachting rowing paddling swimming diving snorkeling surfing windsurf kiteboarding parasailing hang gliding paragliding skydiv bungee jumping zip lining rappelling climbing hiking trekking backpack camping tent pitching sleeping bagging hammock hanging treehouse building cabin construction house remodeling renovation restoration refurbishing decorating painting wallpaper tiling flooring carpet installation hardwood refin sandblasting polishing buff wax varn staining sealing coating plating galvan electropl anod oxid rust proof corrosion resist waterproof moisture res dampness humid condensation evapor precip rain snow hail sleet thun lightning storm cyclone hurri typho tornd watersp dust dev whirlw wind gust breeze zephy draft current flow stream river brook creek spring well fountain geyser hot spa pool lake pond reservoir dam leve embank berme ridge slope incl decl gradient elev altitud height depth level tier stage period interval duration span length width dimension size scale proportion ratio percent fraction decimal number digit figure value quantity amount sum total aggregate collection assembly group cluster pack bundle bunch heap pile mound stack layer sheet slab plate panel tile brick block cube sphere ball globe orb girdle belt band ring hoop loop coil spiral helix twist turn bend curve arc line path route trail track lane road street avenue boulevard highway freeway expressway motorway toll park drive way lane alley court square plaza circle roundabout intersection junction crossroad fork split merge join connect link tie knot bind fast secure lock close shut seal stamp mark sign symbol icon image picture photo photograph snapshot portrait sketch drawing illustration diagram chart graph table spreadsheet database record file folder directory path location address identifier ID code num label tag name title heading caption subtitle legend key glossary index appendix foot note endnote ref citation bibliog works cited references resources materials sup equip tool gadget device instrument apparatus mach engin mot gen turb pump fan blower comp vac clean scrub polish wipe brush roll sponge cloth towel rag napkin tissue paper tissue board cart box crate barrel cask keg drum tank silo hopper bin container vessel ship boat craft sailer yach liner frt carg carri trans vehic auto car tru bus van jeep SUV sed coup hatch conv limous taxi cab moto sco bike bicy tric skate roller ski snowboard sled sleigh tobo can kay raft ding pont jet spfish char tour excurs out day tri week get away vact holiday trav advent explor innov invent creat develop improv enh upgrad revis modif alter chan shi tran form meta evol prog grow exp inc ris sur spi pea summ cre pin apex zeni clim cul com fin en term con clus res sett adju compr nego med arbi lit trial verd judg sent pun pen fi fee cos pr val wor mer qua exc supe perf flaw fault integ hon tr sinc auth genu orig uniq indiv pers cha tem dis att mind bel sys wld phil ide doc dog cred fai rel spir mys occ eso herm alc chem phy mat geo alg calc stat prob log reas ded indu abdu inf expl int ana syn eval ass app est cal comput proc hand man cont dir led gui ste nav sai boa cru ya row pad swim dive snor surf wind para hang parag skyd bunge zip rap climb hike trek back camp tent pitch sleep bag hammock hung treeh build cabin const hous remod renov rest refur dec paint wallp tile floo carp inst hardw refin sand blast poli buff wax varn stain seal coat plat galv electropl anox oxid rust prof corr resist water proof mois res damp hum cond evap precip rain snow hail sleet thun light storm cyclone hurri typh tornd waters dust dev whirlwind gust breezephy draught curr flow stre riv brok crk spng wel fon geyser hot spa pool lak pond reserv dam leve embank berme ridge slop incl decl grad elev altit height depth lev tier stag peri inter dur span leng wid dim siz scal pro rat perc frac deci num dig fig valu quant amou sum tot agg coll assembl group clust pack bund bun heap pil moun stac layr she slb pl pan til bri bloc cub sph bal glob orb gir belt band ring hoop loop coili spir helix twi tur ben cur arc lin pat rout trl tra lan roa str ave blvd hig frway expr motor toll park driv way lane alle court squar plaz cir roundabout interf junct crossrd fork spl merg join conn link tie kn bind fast sec lock clos shut seale stamp mark sign symb icon imag pict photo photog snapsh port sket draw illus diag chart grap tabl spre datab recor file fold dir path loc addr ident ID cod numb labe tag name titl head capt subtit legend key glossari inde append footnot endnote ref cit bibli work cited resour mat sup equ tool gadg devi instr app mach engin mot gen turb pump fan blow comp vac clean scrub polish wipe brush roll sponge cloth towel rag napkin tissue paper tissu board cart box crate bar cask keg drum tank silo hopper bin cont vessel ship boat craft sailer yach liner frt carg carri trans vehic auto car tru bus van jeep SUV sed coup hatch conv limous taxi cab moto sco bike bicy tric skate roller ski snowboard sled sleigh tobo can kay raft ding pont jet spf fish char tour excurs out day tri week get away vact holiday trav advent explor innov invent creat develop improv enh upgrad revis modif alter chan shi tran form meta evol prog grow exp inc ris sur spi pea summ cre pin apex zeni clim cul com fin en term con clus res sett adju compr nego med arbi lit trial verd judg sent pun pen fi fee cos pr val wor mer qua exc supe perf flaw fault integ hon tr sinc auth genu orig uniq indiv pers cha tem dis att mind bel sys wld phil ide doc dog cred fai rel spir mys occ eso herm alc chem phy mat geo alg calc stat prob log reas ded indu abdu inf expl int ana syn eval ass app est cal comput proc hand man cont dir led gui ste nav sai boa cru ya row pad swim dive snor surf wind para hang parag skyd bunge zip rap climb hike trek back camp tent pitch sleep bag hammock hung treeh build cabin const hous remod renov rest refur dec paint wallp tile floo carp inst hardw refin sand blast poli buff wax varn stain seal coat plat galv electropl anox oxid rust prof corr resist water proof mois res damp hum cond evap precip rain snow hail sleet thun light storm cyclone hurri typh tornd waters dust dev whirlwind gust breezephy draught curr flow stre riv brok crk spng wel fon geyser hot spa pool lak pond reserv dam leve embank berme ridge slop incl decl grad elev altit height depth lev tier stag peri inter dur span leng wid dim siz scal pro rat perc frac deci num dig fig valu quant amou sum tot agg coll assembl group clust pack bund bun heap pil moun stac layr she slb pl pan til bri bloc cub sph bal glob orb gir belt band ring hoop loop coili spir helix twi tur ben cur arc lin pat rout trl tra lan roa str ave blvd hig frway expr motor toll park driv way lane alle court squar plaz cir roundabout interf junct crossrd fork spl merg join conn link tie kn bind fast sec lock clos shut seale stamp mark sign symb icon imag pict photo photog snapsh port sket draw illus diag chart grap tabl spre datab recor file fold dir path loc addr ident ID cod numb labe tag name titl head capt subtit legend key glossari inde append footnot endnote ref cit bibli work cited resour mat sup equ tool gadg devi instr app mach engin mot gen turb pump fan blow comp vac clean scrub polish wipe brush roll sponge cloth towel rag napkin tissue paper tissu board cart box crate bar cask keg drum tank silo hopper bin cont vessel ship boat craft sailer yach liner frt carg carri trans vehic auto car tru bus van jeep SUV sed coup hatch conv limous taxi cab moto sco bike bicy tric skate roller ski snowboard sled sleigh tobo can kay raft ding pont jet spf fish char tour excurs out day tri week get away vact holiday trav advent explor innov invent creat develop improv enh upgrad revis modif alter chan shi tran form meta evol prog grow exp inc ris sur spi pea summ cre pin apex zeni clim cul com fin en term con clus res sett adju compr nego med arbi lit trial verd judg sent pun pen fi fee cos pr val wor mer qua exc supe perf flaw fault integ hon tr sinc auth genu orig uniq indiv pers cha tem dis att mind bel sys wld phil ide doc dog cred fai rel spir mys occ eso herm alc chem phy mat geo alg calc stat prob log reas ded indu abdu inf expl int ana syn eval ass app est cal comput proc hand man cont dir led gui ste nav sai boa cru ya row pad swim dive snor surf wind para hang parag skyd bunge zip rap climb hike trek back camp tent pitch sleep bag hammock hung treeh build cabin const hous remod renov rest refur dec paint wallp tile floo carp inst hardw refin sand blast poli buff wax varn stain seal coat plat galv electropl anox oxid rust prof corr resist water proof mois res damp hum cond evap precip rain snow hail sleet thun light storm cyclone hurri typh tornd waters dust dev whirlwind gust breezephy draught curr flow stre riv brok crk spng wel fon geyser hot spa pool lak pond reserv dam leve embank berme ridge slop incl decl grad elev altit height depth lev tier stag peri inter dur span leng wid dim siz scal pro rat perc frac deci num dig fig valu quant amou sum tot agg coll assembl group clust pack bund bun heap pil moun stac layr she slb pl pan til bri bloc cub sph bal glob orb gir belt band ring hoop loop coili spir helix twi tur ben cur arc lin pat rout trl tra lan roa str ave blvd hig frway expr motor toll park driv way lane alle court squar plaz cir roundabout interf jun
It works like this:
```markdown
> [!info] + Algorithm
>
> 1. Create a function that takes in the list of numbers
> 2. Make an empty new list to hold the shuffled result.
> 3. Use a random number generator to pick a random index from the original list.
> 4. Add this item to the new list and delete it from the old one.
> 5. Return the newly created list back outta your function.
Let me know if you'd like further adjustments or translations for other sections! 🤠✨
Note: The translation preserves all formatting, emojis (none here), symbols, indentation, line breaks exactly as requested while translating only textual content into Cowboy English style without adding anything extra beyond what was provided originally—just pure straightforwardness with some flair 😉🔥💯✅✔️☑️✒️⚡🏇♂️🐎🌲🪨🦅🕊️🗺️🧭⭐📜🖋️📘📒🛃🧳👜💼📱📞📻🎙️🎸🎶🎵
[!EXAMPLE] The Answer (in Python)
import random def shuffle(the_list): shuffled = [] while len(the_list) > 0: i = random.randrange(0, len(the_list)) shuffled.append(the_list[i]) the_list.pop(i) return shuffled
Task 9 - Bogo-Sort
In this here task, you’re gonna build a downright awful, but mighty simple sortin’ algorithm. It’s real bad when it comes to big lists (it’s gonna take forever with more than 12-13 items). In Level 2, we’re gonna build a better sortin’ algorithm, bubble-sort.
[!EXAMPLE]- Test Data
[3, 1, 2]→[1, 2, 3][5, 4, 3, 2, 1]→[1, 2, 3, 4, 5][10, 7, 8, 2]→[2, 7, 8, 10][1, 1, 1]→[1, 1, 1][9, 3, 6, 3, 9]→[3, 3, 6, 9, 9][0, -1, 4, -2]→[-2, -1, 0, 4]
The algorithm works like this:[!INFO]+ Algorithm
- Create a function that takes in the list of unsorted numbers
- Shuffle the list properly (use shuffling from task 8)
- Check if the list is sorted (use your check you built in task 7)
- If it ain’t sorted yet, go back to steps two and three again
- Keep on doing this till everything’s lined up right — then quit
In plain talk: Bogosort just scrambles things good n’ proper an’ hopes they end up all neat as pins without doin’ any real work. 🍻🐎⚙️
> Y’all wanna know about that big ol’ “O” thingy? Head on over to Level Two for all them details. 🤠📜
Hint: Reckon ya might wanna useshufflefrom task 8 to whip up a scrambled list fer yer algorithm, partner.
> [!EXAMPLE] - The Answer (in Python)
>
> ````python
def bogo_sort(the_list):
while not is_sorted(the_list):
the_list = shuffle(the_list)
return the_list
````
Task 10a - Searchin’ for Text - “substring” (Tough one!)
Come up with a way to find a keyword within some text. Say ya got a sentence like hello there, ya wanna return True if the keyword is hello, and False if it’s somethin’ like hahah. This here method gotta work no matter what kinda input or output ya throw at it.
Use the text data below to check if yer method’s workin’ right.
[!EXAMPLE]+ Sample data for algorithm:
hello there everyonecontainingthere=Truehello there everyonecontainingever=Truehello there everyonecontainingthen=False
qwecvyufavsjekkftyergwcerycontainingcheck=True
[!INFO]- How-to tipsWrite a function that takes two strings: the text and your search keyword.
- Use a loop with range to go through each character of the string in order from start to finish.
- It’s important here to think about how far you need to let it run so nothing gets skipped over.
- Create yourself a temporary flag variable set to True if found (default is False). This’ll tell us whether or not we’ve spotted our target yet.
Note: We’ll flip this back later when needed depending on what happens inside those loops below… just keep yer eyes peeled now though - don’t get too comfortable there bud.* 😎👀✨💡⚠️✅❌☝️➕✏️✔️➖↩️◻️▪️▫️■□♦♣♥♡★☆※†‡§¶⁂∴∷≈≃=±×÷≤≥<>{}~^-+*/&|%#@!?.,;:’”`’´ˆˇ¸¨°·•…—–--‐―‹›«»„“‘’‚ƒ‰‛ℓ™©®¢¥€₹£₩₽฿₪₫៛৳૱௹ ₨ ₹```python
def search_text(text, keyword):
# Initialize the “found” status as NOT FOUND initially
found = False
for i in range(len(keyword)):
temp_found_for_this_char_of_keyword : bool (bool is boolean data type)
if text[i] !=keyword [i]:
break
else:
continue
pass
return True
elif len(searched_word_in_given_string)==len(inputted_search_term_by_user):
print("Success! Found match at index",index_position_where_matched_occurred_)
[!example]- The Answer (in Python)
def search(data, word): for i in range(0, len(data) - len(word) + 1): found = True for j in range (0, len(word)): if data[i + j] != word[j]: found = False break if found: return True return False
Task 10b
Also add an extra check to make sure the keyword ain’t longer than the sentence.
[!INFO]- Tips on how to proceed
- Add this check before the
forloop.
[!example]- The answer (in Python)def search(data, word): if len(word) > len(data): return False for i in range(0, len(data) - len(word) + 1): found = True for j in range (0, len(word)): if data[i + j] != word[j]: found = False break if found: return True return False
Task 11 - Reversin’ Words in a Sentence (Tough One)
Now, recollect back to Task 5 ‘bout reversin’ a sentence. Go ‘head and rework (or start fresh), and build an algorithm that flips each individual word in a sentence, then puts ‘em back together again.
[!EXAMPLE]+ Sample data fer tha algorithm:
- hello there everyoneturns intaolleh ereht enoyreve
- This is the way it goes!turns intosihT si eht yaw ti !seog
- does this racecar go? of course!becomesseod siht racecar ?og fo !esruoc
[!INFO]- How-to tips
- Make yourself a function that takes an input string.
- ❗Split up them words by using
.split(" ").- Set aside a temporary variable to hold your final answer.
- Use a
forloop to ride through every single word.- Flip it inside out just like you did in Exercise 5
- Take what ya got and add it onto the var from step two, partner.
- Hand back yer final result.
[!EXAMPLE]- The Answer (in Python)def reverse_words(words): sentence = words.split(" ") output = "" for word in sentence: reversed_word = "" for i in range(0, len(word)): reversed_word = word[i] + reversed_word output += reversed_word + " " return output
➕Extra:
Task E1 - Deletin’ Duplicates from a List
Now, reckon ya got a list full o’ numbers, or words, but ya wanna get rid o’ them duplicates. Come up with a plan o’ action that wipes out all them copies from a list, leavin’ only the first o’ each unique item that exists in that list.
[!INFO]- Tips for the way forward
- Start with a function that takes in a list
- Here we’ll use
whileloops instead offor. It’s easier in Python; in other languages, usingforloop counters works just fine.- Create an index variable
idx(ori).- Use a
whileloop to go up to the length of the list.- We want to compare the item at
idxwith all others.- Set up another counter called
jdx(orj) starting fromidx + 1.- Compare items at positions
idxandjdx; if they’re equal, delete it by callingpop(jdx).- REMEMBER! Deleting something makes your array smaller so you gotta step back one spot via
jdx -= 1.Bump
jdxby 1 then check out next thingy over there too ya hear?
10 After finishing off inner while-loop bump idx along yerself till outer while keeps rollin’ on its merry little way ‘round again!
Note: Return final output after cleaning house removing duplicates where found fit as per instructions given above hereunder forthwith immediately upon completion thereof unto thee most welcome recipient(s)!
[!EXAMPLE]+ Sample Input and Output
[1, 2, 2, 3, 1, 4, 3]becomes[1, 2, 3, 4]["a", "b", "a", "c", "b", "d"]becomes["a", "b", "c", "d"][5, 5, 5, 5]becomes[5]["x", "y", "z", "x", "y", "x"]becomes["x", "y", "z"][10, -1, 10, -1, 0, 0, 10]becomes[10, -1, 0]["apple", "apple'", "banana", "orange", "apple", "orange", "pear", "apple"]
Expected result:["apple", "banana", "orange", "pear"]
[!EXAMPLE]- The Answer (in Python)def delete_duplicates(the_list): idx = 0 while idx < len(the_list): jdx = idx + 1 while jdx < len(the_list): if the_list[idx] == the_list[jdx]: the_list.pop(jdx) jdx -= 1 jdx += 1 idx += 1 return the_list
Task E2 - Counting Sort
Counting sort is one of the few sortin’ algorithms that works in what we call \(O(n)\) time. Meanin’, it don’t take much longer than the number of items in the list. Read more ‘bout Big O notation in Level 2.
It kinda depends on how big the range of items is. If the smallest is 0 and the biggest is 100000 it can take a spell, so this one’s best used when the range of values is small. It also don’t work for negative numbers, but ya can modify the algorithm to handle ‘em.
The algorithm works like this:
- Figure out what the biggest item is, and save that value as \(k\).
- Make a list that contains \(k + 1\) items, called
count. - Go through the unsorted list and use the item’s value as the index. Like, if the item has a value of 47, ya go to
count[47]and increase it by 1. - Go through the
countlist and place the number of items that the index is. Example: If there’s a 3 at index 1, ya add three 1s.
[!EXAMPLE]+ Test Data
Unsorted Data Sorted Data [7, 3, 9, 1, 4, 3, 0, 6, 8, 6, 2, 1, 9, 0, 5, 4][0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 9, 9][12, 13, 15, 0, 8, 15, 8, 5, 16, 8, 0, 20, 4, 9, 17, 16, 1, 3, 6, 15, 5, 2, 3, 1, 19, 13, 17, 5, 3, 10][0, 0, 1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 6, 8, 8, 8, 9, 10, 12, 13, 13, 15, 15, 15, 16, 16, 17, 17, 19, 20][!INFO]- Tips on how to proceed
- Start by creating a function with a list as input
- Create an empty
outputlist- Use a
for-loop to go through the entire list- Keep track of the maximum value in a variable before the
for-loop- Update the max value if you find something larger
- Create a list containing that number plus one zero. Example: largest value is 47, then create a list with 48 zeros. You can do this using
[0] * (max + 1)or aforloop. Call itcount.- Go through the list again with another
for-loop- Use the element’s value as its index and increment by 1.
count[value] += 1- Loop over the
countlist using afor-loop- Add each corresponding amount based on what’s at every index
- Return the sorted list
[!EXAMPLE]- The answer (in Python)
def counting_sort(input_list): output = [] max_val = input_list[0] for n in input_list: if n > max_val: max_val = n # this'll make a heap of zeros count = [0] * (max_val + 1) for n in input_list: count[n] += 1 for i in range(len(count)): # use _ to ignore a value for _ in range(count[i]): output.append(i) return output

