Control Flow#
Exercise 1: Reaction Time Data Analysis#
Given a list of reaction times (in milliseconds) from a cognitive task, calculate the average reaction time, and count how many trials had reaction times faster than a threshold (e.g. 300 ms).
reaction_times = [250, 320, 300, 450, 280, 310, 290, 510, 305, 330]
threshold = 300
# Average reaction time
total_time = 0
for time in reaction_times:
total_time += time
average_time = total_time / len(reaction_times)
print(f"Average reaction time: {average_time} ms")
# Count number of trials faster than threshold
fast_trials = 0
for time in reaction_times:
if time < threshold:
fast_trials += 1
print(f"Number of trials faster than {threshold} ms: {fast_trials}")
Average reaction time: 334.5 ms
Number of trials faster than 300 ms: 3
Exercise 2: Counting Spikes in Neural Data#
Assume you have a list of voltage readings from a neuron over time. A spike occurs whenever the voltage is above a threshold (e.g., 50 mV). Write code to count the number of spikes.
voltage_readings = [45, 52, 49, 55, 60, 48, 47, 53, 49, 50, 65]
threshold = 50
# Count spikes
spike_count = 0
for voltage in voltage_readings:
if voltage > threshold:
spike_count += 1
print(f"Number of spikes: {spike_count}")
Number of spikes: 5
Exercise 3: Emotional Word Count#
You are provided with a list of words from a psychological text analysis of participants’ speech. Count how many words are classified as “positive” or “negative” based on pre-defined lists.
Hint: you can use in
to check if an item belongs to a list, e.g. if item in list
…
words = ["peaceful", "happy", "sad", "joy", "angry", "calm", "excited", "joyful", "miserable"]
positive_words = ["happy", "thankful", "joy", "calm", "excited", "joyful", "peaceful", "content"]
negative_words = ["sad", "depressed", "angry", "miserable", "anxious"]
# Count positive and negative words
positive_count = 0
negative_count = 0
for word in words:
if word in positive_words:
positive_count += 1
elif word in negative_words:
negative_count += 1
print(f"Positive words: {positive_count}")
print(f"Negative words: {negative_count}")
Positive words: 6
Negative words: 3
Exercise 4: Stimulus Response Check#
Suppose a participant’s responses to a series of stimuli are recorded as “yes” or “no”. Write a loop to check if there are any cases where the participant said “yes” three times in a row. If so, print a message that they reached a “high response” period.
Hint: You can use break
to exit the for loop if you found a high response period.
responses = ["no", "yes", "yes", "yes", "no", "no", "yes", "no"]
# Check for three consecutive "yes" responses
high_response = False
for i in range(len(responses) - 2):
if responses[i] == "yes" and responses[i + 1] == "yes" and responses[i + 2] == "yes":
high_response = True
break
if high_response:
print("High response period detected (three consecutive 'yes' responses).")
else:
print("No high response period detected.")
High response period detected (three consecutive 'yes' responses).
Exercise 5: Simulating a Stroop Task#
In a simplified Stroop task, participants must say the color of the text, not the word. You have a list of color-word pairs; print only the color for each item.
Hint: If you iterate over pairs of values, you need to make sure to then handle the values within the pair correcly (e.g. by putting them into individual variables with tuple unpacking).
color_word_pairs = [("red", "BLUE"), ("green", "RED"), ("blue", "GREEN"), ("yellow", "BLUE")]
for pair in color_word_pairs:
color, word = pair
print(f"Say the color: {color}")
Say the color: red
Say the color: green
Say the color: blue
Say the color: yellow
Exercise 6: Neuron Firing Rate Simulation#
Given a list of neuron firing intervals (in milliseconds) for a neuron over time, calculate the individual firing rates as well as the average firing rate. The firing rate of a neuron is the reciprocal of the firing interval in seconds (e.g. a firing interval of 100 ms would mean a firing ratr of \(\frac{1}{0.1s} = 10 Hz\)).
intervals = [100, 200, 150, 120, 180, 90] # in ms
# Calculate firing rates and average rate
firing_rates = []
for interval in intervals:
firing_rate = 1000 / interval # 1000 ms -> 1 second
firing_rates.append(firing_rate)
total_rate = 0
for rate in firing_rates:
total_rate += rate
average_firing_rate = total_rate / len(firing_rates)
print("Firing rates (Hz):", firing_rates)
print(f"Average firing rate: {average_firing_rate:.2f} Hz")
Firing rates (Hz): [10.0, 5.0, 6.666666666666667, 8.333333333333334, 5.555555555555555, 11.11111111111111]
Average firing rate: 7.78 Hz
Exercise 7: Experimental Data Normalization#
Given a list of participants’ scores on a memory test, normalize the scores to a range of 0 to 1 by dividing each score by the maximum score.
Hint: Create and fill a new list that contains the normalized scores.
scores = [45, 55, 80, 90, 60, 70]
# Find the maximum score
max_score = max(scores)
# Normalize scores
normalized_scores = []
for score in scores:
normalized_score = score / max_score
normalized_scores.append(normalized_score)
print("Normalized scores:", normalized_scores)
Normalized scores: [0.5, 0.6111111111111112, 0.8888888888888888, 1.0, 0.6666666666666666, 0.7777777777777778]
Exercise 8: Analyzing Sleep Patterns#
Each item in the sleep_stages list represents 15 minutes of sleep categorized into different stages: "Awake"
, "Light Sleep"
, "Deep Sleep"
, and "REM"
. The task is to analyze sleep patterns by calculating the total time spent in each stage, finding the longest continuous period of deep sleep, and determining if at least 20% of the sleep time was spent in REM.
Calculate the total time spent in each sleep stage.
Identify the longest continuous period spent in “Deep Sleep.”
Determine if the participant achieved at least 20% of the total sleep time in “REM” sleep.
Hint: You could, for example, create a dictionary to hold the counts of each state before calculating the total time spent in each state.
# Simulated sleep stages data for 8 hours (32 intervals of 15 minutes each)
sleep_stages = [
"Awake", "Light Sleep", "Light Sleep", "Deep Sleep", "Deep Sleep", "Deep Sleep",
"REM", "REM", "Light Sleep", "Light Sleep", "Awake", "Deep Sleep",
"Light Sleep", "Deep Sleep", "REM", "REM", "Deep Sleep", "Light Sleep",
"Awake", "Light Sleep", "Deep Sleep", "Deep Sleep", "REM", "REM",
"Light Sleep", "Light Sleep", "REM", "Light Sleep", "Awake", "Light Sleep",
"Awake", "Awake"
]
# 1: Calculate total time spent in each sleep stage
sleep_stage_counts = {}
for stage in sleep_stages:
if stage in sleep_stage_counts:
sleep_stage_counts[stage] += 1
else:
sleep_stage_counts[stage] = 1
# Convert counts to minutes by multiplying each count by 15
print("Total time spent in each sleep stage (in minutes):")
for stage, count in sleep_stage_counts.items():
print(f"{stage}: {count * 15} minutes")
# 2: Find the longest continuous period of "Deep Sleep"
max_deep_sleep = 0
current_deep_sleep = 0
for stage in sleep_stages:
if stage == "Deep Sleep":
current_deep_sleep += 15 # each interval is 15 minutes
if current_deep_sleep > max_deep_sleep:
max_deep_sleep = current_deep_sleep
else:
current_deep_sleep = 0
print(f"Longest continuous period in Deep Sleep: {max_deep_sleep} minutes")
# 3: Check if REM sleep is at least 20% of total sleep time
total_sleep_time = len(sleep_stages) * 15 # total time in minutes
rem_sleep_time = sleep_stage_counts.get("REM", 0) * 15
if (rem_sleep_time / total_sleep_time) >= 0.20:
print("Participant achieved at least 20% of sleep time in REM sleep.")
else:
print("Participant did not achieve 20% of sleep time in REM sleep.")
Total time spent in each sleep stage (in minutes):
Awake: 90 minutes
Light Sleep: 165 minutes
Deep Sleep: 120 minutes
REM: 105 minutes
Longest continuous period in Deep Sleep: 45 minutes
Participant achieved at least 20% of sleep time in REM sleep.