What are Algorithims?
Whats the difference between these two math problems: (3+1)3 + 89 + 4(2+8) 3(1+3) + 8(1+4) + 89
Nothing! They are just two different ways of doing them!
Whats the difference between these two math problems: 3((9-6)+7) + 7 - (9+8) 3(9-(6+7)) + 7 - 9 + 8
A lot! This changes the output by quite a bit!
Here are examples of this basic concept in terms of programming:
print("What is the temperature outside °F?")
temp = int(input())
if temp > 85:
print("It is too hot outside!")
elif temp >= 65:
print("Sure, I will play outside!")
else:
print("It is too cold outside!")
print("What is the temperature outside °F?")
temp = int(input())
if temp == 85:
print("It is too hot outside!")
if temp == 65:
print("Sure, I will play outside!")
if temp < 65:
print("It is too cold outside!")
Didn’t get it?
Hint:
- What if I input 60 degrees °F?
- What if I input 90 degrees °F?
Hack #1: What is the difference between these two pieces of code? (in terms of their output)
num = 1
while num <= 100:
if num % 4 != 0:
print(num, end=' ')
num += 1
def print_numbers():
for i in range(1, 101):
if i % 4 != 0:
print(i)
print_numbers()
So when developing algorithms, different pieces of code could do the same thing, and two similar pieces of code could do very different things.
Data Collections
Purpose of Data Collection
To gather accurate and relevant information for specific purposes, such as solving problems, making informed decisions, or predicting future trends.
Techniques
Surveys and Questionnaires: Structured methods for gathering data from a large number of respondents. They can be administered in-person, online, or through other mediums.
Observations: Watching and recording actions or behaviors in a systematic manner.
Experiments: Conducting controlled tests or trials to determine cause and effect relationships.
Simulations: Using models to imitate real-world situations.
Interviews: One-on-one or group discussions to gain in-depth insights.
Sensors and Automated Collection: Using electronic devices to automatically collect data, like temperature sensors or traffic cameras.
Sampling: Instead of studying an entire population, a subset (or sample) can be studied to make inferences about the entire group.
Techniques include random sampling, stratified sampling, and convenience sampling.
Bias and Error
Data collection methods can introduce bias or error. It’s crucial to be aware of potential sources of bias, like leading questions in surveys or non-random sampling methods.
Privacy and Ethics
Always consider the ethical implications of data collection. Obtain consent when necessary, anonymize data to protect individuals’ privacy, and be transparent about how data will be used.
Hack #2:
def find_max(numbers):
max_value = numbers[0]
for number in numbers:
if number > max_value:
max_value = number
return max_value
#List of numbers
numbers = [23, 45, 67, 89, 12, 34, 56, 78]
max_value = find_max(numbers)
print(max_value)
List of numbers numbers = [23, 45, 67, 89, 12, 34, 56, 78]
TODO: Modify the given algorithm to find the minimum value in the list of numbers. Hint: You only need to change two lines of code.
# Place your code here...
def find_min(numbers):
min_value = numbers[0]
for number in numbers:
if number < min_value:
min_value = number
return min_value
numbers = [23, 45, 67 , 89, 12, 34, 56, 78]
min_value = find_min(numbers)
print(min_value)
12
Solution:
Modified Algorithm to find the minimum value.
def find_min(numbers):
min_value = numbers[0]
for number in numbers:
if number < min_value:
min_value = number
return min_value
#alling the function
min_value = find_min(numbers)
print(min_value) # Output: 12
Cell In[6], line 8
Calling the function
^
SyntaxError: invalid syntax
Creating/Modifying Algorithms
Important steps for creating an algorithm:
- Define functions
- Initialize ways to store data (array, lists, dictionaries, etc…)
- Depending on the context, use iteration to specify conditions for variable
- Output generated values from the algorithm
Helpful tips for modifying algorithms:
- Understand the algorithm so you’re able to easily apply changes to it.
- Break the program down into chunks.
- Focus on each small part of the algorithm to get it to work.
- Make sure to test individual components, and then the whole code together (This makes identifying errors, and correcting mistakes easier).
Example (The sum of all even numbers between 1 and a given positive integer):
def sum_of_evens(n):
total = 0
for i in range(2, n + 1, 2): #Note the 2 and the very end initializes a step size of 2 for the function
total += i
return total
n = int(input("Enter a positive integer: "))
result = sum_of_evens(n)
print(f"The sum of even numbers from 1 to {n} is {result}")
Hack #3:
TODO: Adapt the above algorithm to output for the sum of odd numbers between 1 and a given integer.
Try to come up with a unique algorithm (way) to achieve the above task.
# Place your code here...
def sum_of_odds(n):
total = 0
for i in range(1, n+1, 2):
total += i
return total
n = int(input("enter a postive integer: "))
result = sum_of_odds(n)
print(f"the sum of odd numbers from 1 to {n} is {result}")
enter a postive integer: 12
the sum of odd numbers from 1 to 12 is 36
Solution:
Think about how you would define an odd number, and output the sum of each element.
def sum_of_odd_numbers(n):
total = 0
for i in range(1, n + 1):
if i % 2 != 0: # Check if the number is odd
total += i
return total
n = int(input("Enter a value for n: "))
result = sum_of_odd_numbers(n)
print(f"The sum of odd numbers from 1 to {n} is: {result}")
Random Number Generation
RANDOM (a, b) generates a number from a to b inclusive. Each result from the randomization is equally likely to occur. Using random number generation in a program means each execution may produce a different result. We can use the results from randomization to program simulations.
What are the possibities for Answ3? Answ1 (0,2) #This means Answ1 can be anywhere from 0 to 2 Answ2 (1,5) #This means Answ1 can be anywhere from 1 to 5 Answ3 = Answ1 + Answ2
The lowest number answ1 will generate is 0 and the lowest number answ2 will generate is 1. Therefore, the lowest number answ3 could be is 1. The highest number answ1 will generate is 2 and the highest number answ2 will generate is 5. Therefore, the highest number answ3 could be is 7.
Generating Random Values:
- In AP CSP, students learn to generate random values using certain code constructs, like the random module in Python which allows for random integer generation between specified values using random.randint(a, b)1. This random number generation introduces an element of unpredictability, vital for many programming applications. Application in Simulations:
- Random values are crucial in simulations, mimicking real-world unpredictability. They help in creating diverse scenarios in simulations like weather patterns or game dynamics, thus providing a more realistic or varied simulation experience. Evaluating Code Segments:
- Utilizing random values can aid in evaluating code segments by testing how code reacts to varied input, which is particularly useful in identifying potential bugs or inefficiencies.
If you roll a die 3 times, and take the sum of all your rolls, what is the highest possible amount and the lowest possible amount you can get?
Roll 1 (1,6) Roll 2 (1,6) Roll 3 (1,6)
Lowest: 3 Most: 18
import random
def generate_random():
value = random.randint(1, 100)
print(f'Random value between 1 and 100: {value}')
dice_roll = random.randint(1, 6)
print(f'Dice Roll: {dice_roll}')
# Call the function
generate_random()
Hack #4
Lets continue the fun… Make an algorithm that assigns 5 days with a random temperatures between 60-90 degrees Fahrenheit!
# Place your code here...
import random
def generate_random():
value = random.randint(60, 90)
return value
for i in range(5):
print(f"day {i+1}: {generate_random()} degrees F")
day 1: 88 degrees F
day 2: 68 degrees F
day 3: 60 degrees F
day 4: 77 degrees F
day 5: 81 degrees F
Solution:
How can you iterate between a range of 5 days, along with generate a random temperature between 60-90?
import random
def simulate_weather():
for day in range(1, 6):
temperature = random.randint(60, 90)
print(f'Day {day}: Temperature: {temperature}°F')
# Call the function
simulate_weather()
Homework:
- Create a program that follows the Collatz Conjecture.
If a number is even, divide by 2.
If a number is odd, multiply by 3 and add 1.
If implemented correctly this algorithm will eventually go to 1. Try defining the initial number with any number beside 1 to see an interesting ouput. Output the result as a list. You may set a starting value for the list, so that the program can generate the list of numbers created when following the process.
Ideas for above 90%: Try implementing user input into this program. Ask the user to enter a number they would like to start with.
# Place your code here...
num = int(input("enter a positive integer:"))
nums = [num]
def collatz(n):
if n % 2 == 0:
n //= 2
elif n % 2 == 1:
n *= 3
n += 1
return n
while num != 1:
num = collatz(num)
nums.append(num)
for i in range(len(nums) - 1):
print(nums[i], "->", end=" ")
print(nums[-1])
print("num of terms:", len(nums))
enter a positive integer: 2098093850295
2098093850295 -> 6294281550886 -> 3147140775443 -> 9441422326330 -> 4720711163165 -> 14162133489496 -> 7081066744748 -> 3540533372374 -> 1770266686187 -> 5310800058562 -> 2655400029281 -> 7966200087844 -> 3983100043922 -> 1991550021961 -> 5974650065884 -> 2987325032942 -> 1493662516471 -> 4480987549414 -> 2240493774707 -> 6721481324122 -> 3360740662061 -> 10082221986184 -> 5041110993092 -> 2520555496546 -> 1260277748273 -> 3780833244820 -> 1890416622410 -> 945208311205 -> 2835624933616 -> 1417812466808 -> 708906233404 -> 354453116702 -> 177226558351 -> 531679675054 -> 265839837527 -> 797519512582 -> 398759756291 -> 1196279268874 -> 598139634437 -> 1794418903312 -> 897209451656 -> 448604725828 -> 224302362914 -> 112151181457 -> 336453544372 -> 168226772186 -> 84113386093 -> 252340158280 -> 126170079140 -> 63085039570 -> 31542519785 -> 94627559356 -> 47313779678 -> 23656889839 -> 70970669518 -> 35485334759 -> 106456004278 -> 53228002139 -> 159684006418 -> 79842003209 -> 239526009628 -> 119763004814 -> 59881502407 -> 179644507222 -> 89822253611 -> 269466760834 -> 134733380417 -> 404200141252 -> 202100070626 -> 101050035313 -> 303150105940 -> 151575052970 -> 75787526485 -> 227362579456 -> 113681289728 -> 56840644864 -> 28420322432 -> 14210161216 -> 7105080608 -> 3552540304 -> 1776270152 -> 888135076 -> 444067538 -> 222033769 -> 666101308 -> 333050654 -> 166525327 -> 499575982 -> 249787991 -> 749363974 -> 374681987 -> 1124045962 -> 562022981 -> 1686068944 -> 843034472 -> 421517236 -> 210758618 -> 105379309 -> 316137928 -> 158068964 -> 79034482 -> 39517241 -> 118551724 -> 59275862 -> 29637931 -> 88913794 -> 44456897 -> 133370692 -> 66685346 -> 33342673 -> 100028020 -> 50014010 -> 25007005 -> 75021016 -> 37510508 -> 18755254 -> 9377627 -> 28132882 -> 14066441 -> 42199324 -> 21099662 -> 10549831 -> 31649494 -> 15824747 -> 47474242 -> 23737121 -> 71211364 -> 35605682 -> 17802841 -> 53408524 -> 26704262 -> 13352131 -> 40056394 -> 20028197 -> 60084592 -> 30042296 -> 15021148 -> 7510574 -> 3755287 -> 11265862 -> 5632931 -> 16898794 -> 8449397 -> 25348192 -> 12674096 -> 6337048 -> 3168524 -> 1584262 -> 792131 -> 2376394 -> 1188197 -> 3564592 -> 1782296 -> 891148 -> 445574 -> 222787 -> 668362 -> 334181 -> 1002544 -> 501272 -> 250636 -> 125318 -> 62659 -> 187978 -> 93989 -> 281968 -> 140984 -> 70492 -> 35246 -> 17623 -> 52870 -> 26435 -> 79306 -> 39653 -> 118960 -> 59480 -> 29740 -> 14870 -> 7435 -> 22306 -> 11153 -> 33460 -> 16730 -> 8365 -> 25096 -> 12548 -> 6274 -> 3137 -> 9412 -> 4706 -> 2353 -> 7060 -> 3530 -> 1765 -> 5296 -> 2648 -> 1324 -> 662 -> 331 -> 994 -> 497 -> 1492 -> 746 -> 373 -> 1120 -> 560 -> 280 -> 140 -> 70 -> 35 -> 106 -> 53 -> 160 -> 80 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
num of terms: 223
- Create an algorithm that generates terms to the Fibonacci Sequence which outputs a specific number of terms defined in your code. The sequence starts off like 1, 1, 2, 3, 5, … each following term being the sum of the previous two.
Ideas for above 90%:
- Add user input
- Display error message when an invalid input is specified
- Find a way for the program to only specify a specific term in the sequence
# Place your code here...
def fib(num):
if num == 1:
return 0
if num == 2:
return 1
return fib(num-1) + fib(num-2)
num = int(input("enter a positive integer:"))
for i in range(num):
print(f"F({i+1}):", fib(i+1))
enter a positive integer: 10
F(1): 0
F(2): 1
F(3): 1
F(4): 2
F(5): 3
F(6): 5
F(7): 8
F(8): 13
F(9): 21
F(10): 34
- Make a statistics calculator that calculates the mean, median, and mode of a specific series. Do this using iteration and without the use of imported modules (like the statistics one) that allows you to call pre defined functions like mean, median, and mode. Each of these calculations follows an algorithm.
Ideas for above 90%:
- Randomly generate a list of numbers (you can define it as a list of 5) to apply the calculator to.
- If you can, generate a random number of elements in the data set as well (keep it between 5-10 elements).
# Place your code here...
import random
random_nums = []
mode_nums = {}
mode = []
for i in range(random.randint(5,10)):
random_nums.append(random.randint(1,100))
total = 0
for num in range(len(random_nums)):
total += random_nums[num]
mean = total/len(random_nums)
if len(random_nums) % 2 == 0:
median = (random_nums[len(random_nums)//2] + random_nums[len(random_nums)//2 - 1])/2
else:
median = random_nums[(len(random_nums)-1)//2]
for num in random_nums:
if num in mode_nums:
mode_nums[num] += 1
else:
mode_nums[num] = 1
count = max(mode_nums.values())
if count == 1:
mode = "no mode"
else:
for num, max_count in mode_nums.items():
if max_count == count:
mode.append(num)
print(random_nums)
print(mean)
print(median)
print(mode)
[22, 10, 54, 23, 80, 61]
41.666666666666664
38.5
no mode