[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.squares_comp = [num * num for num in nums if num % 2 == 1]
{word: len(word) for word in ['hello', 'world']}
{char.lower() for char in 'Hello, world!' if char != ' '}{'!', ',', 'd', 'e', 'h', 'l', 'o', 'r', 'w'}
words = ['hello', 'world'], the output should be {'hello': 0, 'world': 1}.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.06 μs ± 15.8 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
def spell(letter):
if letter == "A":
return "Alfa"
elif letter == "B":
return "Bravo"
elif letter == "C":
return "Charlie"
elif letter == "D":
return "Delta"
elif letter == "S":
return "Sierra"
else:
return "?"
[spell(letter) for letter in "CS"]['Charlie', 'Sierra']
Is there a better way?
Live demo. CodeMirror
import llm
model = llm.get_model("gemini-1.5-flash-latest")
response = model.prompt("Replace some words to make the following sentence more absurd: 'The quick brown fox jumps over the lazy dog.'")
print(response.text())Several options, depending on the type of absurdity you're aiming for:
**Option 1 (Surreal):** "The incandescent turquoise badger teleports over the philosophical cucumber."
**Option 2 (Humorous):** "The enthusiastic purple squirrel tap-dances over the lethargic marshmallow."
**Option 3 (Slightly nonsensical):** "The flamboyant orange hamster levitates over the pensive garden gnome."
**Option 4 (More exaggerated):** "The ridiculously fast, neon-green ferret performs a triple backflip over a comatose hippopotamus."
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.
import llm
model = llm.get_model("gemini-1.5-flash-latest")
conversation = model.conversation()
response = conversation.prompt("Five fun facts about the moon.")
print(response.text())1. **Moonquakes:** The Moon experiences "moonquakes," but they're not like earthquakes. These tremors are much weaker and are caused by the Earth's gravitational pull.
2. **Footprints Forever:** Because the Moon has no atmosphere or wind, the footprints left by the Apollo astronauts will remain there for millions of years, undisturbed.
3. **A Rusty Moon:** Scientists have detected rust (hematite) on the Moon, which is surprising because rust needs oxygen and water, both of which are scarce on the Moon's surface. The exact process of its formation is still debated.
4. **The Moon is Slowly Drifting Away:** The Moon is moving about 1.5 inches away from the Earth each year.
5. **The "Dark Side" Isn't Really Dark:** The term "dark side of the Moon" is misleading. Both sides of the Moon receive sunlight over the course of a lunar month; it's just that one side always faces away from the Earth. A more accurate term is the "far side of the Moon."
Here are five fun facts about the Sun:
1. **It's Mostly Hydrogen and Helium:** The Sun is a giant ball of gas, primarily composed of hydrogen (about 73%) and helium (about 25%). The remaining 2% consists of trace amounts of heavier elements.
2. **Solar Flares and CMEs:** The Sun regularly erupts with solar flares, which are intense bursts of radiation, and coronal mass ejections (CMEs), which are huge clouds of plasma that can travel towards Earth and disrupt our technology.
3. **The Sun is a Star:** It might seem obvious, but it's important to remember that the Sun is just one star among billions in our Milky Way galaxy. It's just much closer to us than other stars, making it appear significantly brighter and larger.
4. **Sunspots are Cooler:** Sunspots, those dark patches on the Sun's surface, are actually cooler than the surrounding areas. They appear dark only by contrast to the brighter regions.
5. **The Sun Converts Mass into Energy:** The Sun's energy comes from nuclear fusion, where hydrogen atoms are fused together to form helium, releasing tremendous amounts of energy in the process (as described by Einstein's famous equation, E=mc²).