[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You don’t need to use any particular framework or library from this class. But do it if it saves time.
A compact replacement for some accumulator patterns.
Simple list comprehensions
for loop.Write a dict comprehension that gives the indices of each word in a list of words. For example, if words = ['hello', 'world'], the output should be {'hello': 0, 'world': 1}.
Do these:
Suppose we have a sorted list:
We want to find the letter grade for, say, 89. Can we do this faster than searching the whole list?
Exercise: Write the code to search the whole list.
Trick: check the item in the middle element to see whether to look in the left or right half.
1.52 μs ± 5.23 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
'Random|variable|generators.|bytes|-----|uniform|bytes|(values|between|0|and|255)|integers|--------|uniform|within|range|sequences|---------|pick'
'2**19937-1.|extensively|implemented|threadsafe.|distributions|distributions|distributions|----------------------|------------------------------|---------------------------------------------'
Some material useful for simulations
CSV files
JSON (JavaScript Object Notation) files
Pickle
Suppose you want to add thunderstorms in your population simulation. For simpliciticy, they happen each day with probability p. Remember that random.random() generates a random number between 0 and 1. What fills in the blank?
import runpy; runpy.run_module("turtledemo")Do them now. Come get the prof out in the hall when everyone’s done.
Code you don’t have to write, or even install!
import re
ssn_regex = re.compile(r"""
^ # match the beginning of the string
(\d{3}) # match exactly 3 digits
- # match one dash
(\d{2}) # match exactly 2 digits
-
(\d{4}) # match exactly 4 digits
$ # match end of string
""", re.VERBOSE)
def is_valid_ssn(ssn):
match = ssn_regex.match(ssn)
if match:
print(match.groups())
return True
return False
is_valid_ssn("123-45-6789")('123', '45', '6789')
True
enumerate0 A
1 B
2 C
3 D
4 E
5 F
6 G
Example: Spelling Alphabet
['Charlie', 'Sierra']
Is there a better way?
['Charlie', 'Sierra']
Live demo. CodeMirror
Here are a few options to make it more absurd, playing with different elements:
1. **The enthusiastic lint roller tap-dances over the napping cumulonimbus cloud.**
2. **The wobbly purple teapot serenades the perpetually confused jellyfish.**
3. **The existential quantum foam meditates beneath the bewildered lamppost.**
4. **The vibrant spoon yodels into the mind of the forgotten comma.**
5. **The grumpy garden gnome procrastinates adjacent to the sarcastic dandelion.**
To set this up:
llm package (Manage Packages in Thonny, or pip install llm).llm-gemini in the same way.LLM_GEMINI_KEY=
and paste the key in the right-hand side (without quotes). Then restart Thonny.
(alternatively, run llm keys set gemini on a system Terminal.)
This way the model can remember the context of the conversation.
Here are five fun facts about the Moon:
1. **Footprints Last Forever (Almost):** Because the Moon has no atmosphere, there's no wind or water to erode anything. This means the footprints left by the Apollo astronauts (and their rover tracks!) will likely remain perfectly preserved for millions of years, unless disturbed by a meteorite impact.
2. **It's Our Solar System's Fifth-Largest Moon:** For a natural satellite, our Moon is surprisingly large. It's the fifth-largest moon in our solar system, even bigger than the dwarf planet Pluto!
3. **The Moon is "Tidally Locked":** We always see the same side of the Moon because it rotates on its axis at the exact same rate it orbits Earth. This phenomenon is called "tidal locking."
4. **It's Moving Away From Us:** The Moon is slowly drifting away from Earth at a rate of about 3.8 centimeters (1.5 inches) per year. This means that billions of years ago, it appeared much larger in the sky!
5. **The Moon Has "Moonquakes":** Just like Earth has earthquakes, the Moon experiences "moonquakes." These are much weaker than Earth's quakes and are thought to be caused by Earth's tidal pull, as well as thermal expansion and contraction, and meteorite impacts.
Here are five fun facts about the Sun:
1. **It's a Million-Earth Powerhouse:** You could fit approximately **1.3 million Earths** inside the Sun! It's so massive that it accounts for about 99.8% of the entire mass of our solar system.
2. **Not "Burning," But Fusing:** The Sun isn't "on fire" in the way wood burns. Instead, it's a giant ball of plasma (superheated, ionized gas) where **nuclear fusion** takes place in its core. Hydrogen atoms are constantly smashing together to form helium, releasing an enormous amount of energy in the process.
3. **Light Takes Its Time:** While sunlight reaches Earth in about 8 minutes and 20 seconds, the energy generated in the Sun's core takes a much, much longer journey. It can take **hundreds of thousands of years** for a photon of light to battle its way from the core to the Sun's surface before it finally zips towards Earth!
4. **It Has Its Own Weather System:** The Sun experiences incredible "space weather," including **solar flares** (intense bursts of radiation), **coronal mass ejections** (giant clouds of plasma), and **sunspots** (cooler, darker areas on its surface). These phenomena can sometimes affect technology on Earth.
5. **The Sun is Middle-Aged:** Our Sun is about **4.6 billion years old**, which makes it a "main-sequence star" in its prime. It has roughly another **5 billion years** of life left before it runs out of hydrogen fuel in its core and begins to swell into a red giant, eventually shedding its outer layers to become a white dwarf.