Algorithms can be written in different ways and still accomplish the same tasks. Algorithms that look similar often yield differnet outputs. To solve the same problem, many different algorithms can be used.

Therefore, algorithms are very important for programmers, and today we're going to explore how to determine the outcome of algorithms, how to deteremine the output of similar algorithms, how to edit existing algorithms, and how to develop our own algorithms.

Determine the outcome of algorithms

Consider the following algorithm.

def mystery(num, num2):
    if (num % num2 == 0):
        print("True")
    else:
        print("False")

mystery(30, 4)
False
  1. What does the algorithm do? Please explain in words. An algorithm is a coded formula written into software that, when triggered, prompts the tech to take relevant action to solve a problem. Computer algorithms work via input and output. When data is entered, the system analyses the information given and executes the correct commands to produce the desired result.

  2. What if I put in 30 as num and 4 as num2. What would be the output? Answer: false

Determine the outcome of similar algorithms

What is the output of this algorithm? Answer: it is too hot outside

temp = 95
if (temp >= 90):
    print("it is too hot outside")
else:
    if (temp >= 65):
        print("I will go outside")
    else:
        print("it is too cold outside")
it is too hot outside

What is the output of this algorithm? it looks similar but the output is different! Answer: it is too hot outside i will go outside

x = "it is too hot outside"

temp = 65
if (temp >= 90):
    print(x)
else:
    if (temp >= 65):
        print(x)
    else:
        print(x)
it is too hot outside

Editing Algorithms

Task: Please edit the algorithm above to have it yield the same results as the previous algorithm! (no matter what temp you put in)

Developing Algorithms

To develop algorithms, we first need to understand what the question is asking. Then, think about how you would approach it as a human and then try to find what pattern you went through to arrive at the answer. Apply this to code, and there you have it! An algorithm!

Let's say you wanted to sum up the first five integers. How would you do this in real life? Your thought process would probably be:

  • The sum of the first integer is 1.
  • Then, increase that integer by 1. I now add 2 to my existing sum (1). My new sum is 3.
  • Repeat until I add 5 to my sum. The resulting sum is 15.

Now let's translate this into code.

sum = 0 # start with a sum of 0
for i in range (1, 6): # you will repeat the process five times for integers 1-5
    sum = sum + i # add the number to your sum
print(sum) # print the result
15

Task: Write an algorithm in python that sums up the first 5 odd integers. You can use the following code as a starter.

sum = 0
for i in range (1,10,2):
    sum = sum + i
print(sum)
25

Homework

Create an algorithm that will start with any positive integer n and display the full sequence of numbers that result from the Collatz Conjecture. The COllatz Conjecture is as follows:

  1. start with any positive integer
  2. if the number is even, divide by 2
  3. if the number is odd, multiply by 3 and add 1
  4. repeat steps 2 and 3 until you reach 1

Example: if the starting number was 6, the output would be 6, 3, 10, 5, 16, 8, 4, 2, 1

numb = int(input("Please enter a postive number:"))
print(numb)
while numb != 1:
    
    if numb % 2 ==0:
        numb = numb/2
        print(numb)
    else:
        numb = ((numb*3)+1)
        print(numb)

    
20000000
10000000.0
5000000.0
2500000.0
1250000.0
625000.0
312500.0
156250.0
78125.0
234376.0
117188.0
58594.0
29297.0
87892.0
43946.0
21973.0
65920.0
32960.0
16480.0
8240.0
4120.0
2060.0
1030.0
515.0
1546.0
773.0
2320.0
1160.0
580.0
290.0
145.0
436.0
218.0
109.0
328.0
164.0
82.0
41.0
124.0
62.0
31.0
94.0
47.0
142.0
71.0
214.0
107.0
322.0
161.0
484.0
242.0
121.0
364.0
182.0
91.0
274.0
137.0
412.0
206.0
103.0
310.0
155.0
466.0
233.0
700.0
350.0
175.0
526.0
263.0
790.0
395.0
1186.0
593.0
1780.0
890.0
445.0
1336.0
668.0
334.0
167.0
502.0
251.0
754.0
377.0
1132.0
566.0
283.0
850.0
425.0
1276.0
638.0
319.0
958.0
479.0
1438.0
719.0
2158.0
1079.0
3238.0
1619.0
4858.0
2429.0
7288.0
3644.0
1822.0
911.0
2734.0
1367.0
4102.0
2051.0
6154.0
3077.0
9232.0
4616.0
2308.0
1154.0
577.0
1732.0
866.0
433.0
1300.0
650.0
325.0
976.0
488.0
244.0
122.0
61.0
184.0
92.0
46.0
23.0
70.0
35.0
106.0
53.0
160.0
80.0
40.0
20.0
10.0
5.0
16.0
8.0
4.0
2.0
1.0

Challenges and Homework

You have one homework problem.

Yes just one.

Don't get excited though.

Problem: Given a specific integer N, return the square root of N (R) if N is a perfect square, otherwise, return the square root of N rounded down to the nearest integer

Input: N (Integer)

Output: R (Integer)

Constraints: Do not use any built-in math operations such as sqrt(x) or x**(0.5), Try complete the problem in logarithmic time.

Hint 1: Maybe you can use Binary Search to try and reduce the number of checks you have to perform?

Hint 2: Is there a mathematical pattern amongst numbers and their square roots that could help you reduce the number of searches or iterations you must execute? Is there some value or rule you can set before applying binary search to narrow the range of possible values?

def sqrt(num):
    if(num==0):
        return 0
    low = 1
    high = num//2
    while(low<=high):
        mid = low+(high-low)//2
        if(mid*mid ==num):
            return mid
        if(mid*mid< num):
            low=mid+1
            answers = mid    
        else:
            high = mid-1
    return answers
print(sqrt(4))
2
from math import sqrt as sq
test_cases = [0,1,4,85248289,22297284,18939904,91107025,69122596,9721924,37810201,1893294144,8722812816,644398225]
answers = [int(sq(x)) for x in test_cases]

def checkValid():
    for i in range(len(test_cases)):
        if sqrt(test_cases[i]) == answers[i]:
            print("Check number {} passed".format(i+1))
        else:
            print("Check number {} failed".format(i+1))

checkValid()
Check number 1 passed
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb Cell 23 in <cell line: 12>()
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb#X33sdnNjb2RlLXJlbW90ZQ%3D%3D?line=8'>9</a>         else:
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb#X33sdnNjb2RlLXJlbW90ZQ%3D%3D?line=9'>10</a>             print("Check number {} failed".format(i+1))
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb#X33sdnNjb2RlLXJlbW90ZQ%3D%3D?line=11'>12</a> checkValid()

/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb Cell 23 in checkValid()
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb#X33sdnNjb2RlLXJlbW90ZQ%3D%3D?line=4'>5</a> def checkValid():
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb#X33sdnNjb2RlLXJlbW90ZQ%3D%3D?line=5'>6</a>     for i in range(len(test_cases)):
----> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb#X33sdnNjb2RlLXJlbW90ZQ%3D%3D?line=6'>7</a>         if sqrt(test_cases[i]) == answers[i]:
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb#X33sdnNjb2RlLXJlbW90ZQ%3D%3D?line=7'>8</a>             print("Check number {} passed".format(i+1))
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb#X33sdnNjb2RlLXJlbW90ZQ%3D%3D?line=8'>9</a>         else:

/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb Cell 23 in sqrt(num)
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb#X33sdnNjb2RlLXJlbW90ZQ%3D%3D?line=12'>13</a>     else:
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb#X33sdnNjb2RlLXJlbW90ZQ%3D%3D?line=13'>14</a>         high = mid-1
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/ananyag2617/vscode/ananyagaurav2617/_notebooks/2022-11-29-Developing-Algorithms.ipynb#X33sdnNjb2RlLXJlbW90ZQ%3D%3D?line=14'>15</a> return answers

UnboundLocalError: local variable 'answers' referenced before assignment