3.12 and 3.13 Calling and Developing Procedures

  • A procedure = a named set of instructions that can take in parameters and return values
    • May be called "method" or "function" in different programming languages
  • Parameters are independent variables used in the procedure to produce a result. It allows a procedure to execute without initially knowing specific input values
  • Procedures can be classified as sequencing, selection, and iteration

Calling Procedures

  • To call a procedure you would write the name of the procedure followed by the parentheses with the parameters of the procedure
  • Procedures do not require parameters, but the parentheses must be there (can be empty)
x = 5 # input calues can be changed when using parameters
y = 3

def multiply(x, y): # x and y are the parameters
    product = x * y
    return product

answer = multiply(x, y) # this is calling the procedure
print("The product of", x, "times", y, "is", answer)
The product of 5 times 3 is 15

Determining the Result of a Procedure

  • To determine the result of a procedure or any code: follow code line by line and see what each one does

  • Using syntax, you can determine the result by

    • function parameters
    • return value and statements
  • return values: write "return" followed by the expression you would like to return var
  • A return statement exits a function and instructs python to continue executing the program and to return a certain value

  • Value can be string, a tuple, or any other type that is being sent back to the main program

def divide(num1,num2):
      x = num1/num2
      return x 
      # x = return value
  • Modularity - the practice of breaking a complex program into smaller, independent parts or modules that can be used and reused in different parts of the program
  • Abstraction - the practice of hiding the details of how a particular code or system works and exposing only the essential features or functions that are necessary for other parts of the program to use
  • Duplication - having multiple duplicate code blocks, often decreasing readability and efficiency
  • Logic - the sequence of steps and operations that a computer follows to execute a program, including the specific instructions and decision-making processes built into the code
  • Procedure - a module of code that is created to complete a certain task, this is basically a function
  • Procedure Name - the name that is given to a function/procedure
  • Parameters - a variable that is used in a function to allow for data to be imported into a function
  • Arguments - a way to provide information to a function, usually defined outside a function and then imported into a function with parameters
# This code simulates the scoring at a cheerleading competition <- the overall score for the comp is 25% of your first performance (day 1) and 75% of your second performance (day 2)
scores_given = ["Code 5", "Coed"]
team_name = input("What is the name of your team?")

def combined_score(score1, score2): #defining this function makes it much simpiler when trying to score hundreds of teams
    # instead of writing all of this code again for each team, it is used repeatedly
    combined_score = ((0.25*score1)+(0.75*score2))
    print(team_name,"'s overall score for the competition is ", combined_score)
    scores_given.append(team_name)
   

combined_score(score1 = int(input("what was your day 1 score?")), score2 = int(input("what was you day 2 score?")))
print("Scores have been given to ", scores_given)
TGLC 's overall score for the competition is  97.25
Scores have been given to  ['Code 5', 'Coed', 'TGLC']

3.14-3.15 Libraries and Random Values

College Board Essential Knowledge

  • A software library contains procedures that can be used in the creation of new programs.
  • Existing segments of code can come from internal or external sources, ie. libraries or previously written code.
  • The use of libraries simplifies the task of creating complex programs.
  • Application program interfaces (APIs) are specifications for how the procedures in a library behave and can be used.
  • Documentation for a library or API is necessary in understanding the key behaviors provided by the API/library and how to utilize them in your work.

Defining a Library

  • A library is a collection of code from an external source that can be used to add functionality to a program.
  • Libraries are very useful, as they can be used to save time and effort in the development process
  • Libraries are usually included in a program using a special keyword called "import" This keyword tells the program to look for the library and use its code

What is randomization?

  • Randomization generates a value between two numbers. For example RANDOM(1,3) may result as 1 or 2 or 3
import random # "import" and then the name of the library
#imported library allows me to use their random number generator
number = random.randint(0,100)
print("you're random number is",number)
if number == 21:
    print("you win!")
else:
    print("better luck next time :(")
you're random number is 1
better luck next time :(
# another example of import random
import random
landed_on = random.randint(1,8)
if landed_on <= 3:
    color = "green"
elif 4<= landed_on <= 5:
    color = "blue"
elif landed_on == 6:
    color = "purple"
elif landed_on == 7:
    color = "red"
elif landed_on == 8:
    color = "orange"

print("your color is", color)
your color is orange

There are many different methods within the random library

seed() | Initialize the random number generator

getstate() | Returns the current internal state of the random number generator

setstate() | Restores the internal state of the random number generator

getrandbits() | Returns a number representing the random bits

randrange() | Returns a random number between the given range

randint() | Returns a random number between the given range

choice() | Returns a random element from the given sequence

choices() | Returns a list with a random selection from the given sequence

shuffle() | Takes a sequence and returns the sequence in a random order

sample() | Returns a given sample of a sequence

random() | Returns a random float number between 0 and 1

uniform() | Returns a random float number between two given parameters

betavariate() | Returns a random float number between 0 and 1 based on the Beta distribution (used in statistics)

expovariate() | Returns a random float number based on the Exponential distribution (used in statistics)

gammavariate() | Returns a random float number based on the Gamma distribution (used in statistics)

gauss() | Returns a random float number based on the Gaussian distribution (used in probability theories)

lognormvariate() | Returns a random float number based on a log-normal distribution (used in probability theories)

normalvariate() | Returns a random float number based on the normal distribution (used in probability theories)

vonmisesvariate() | Returns a random float number based on the von Mises distribution (used in directional statistics)

paretovariate() | Returns a random float number based on the Pareto distribution (used in probability theories)

weibullvariate() | Returns a random float number based on the Weibull distribution (used in statistics)

3.17-3.18 Algorithm Efficiency and Undecidable Problems

Vocabulary

  • Collatz: The Collatz conjecture is one of the most famous unsolved problems in mathematics. The conjecture asks whether repeating two simple arithmetic operations will eventually transform every positive integer into 1.

  • Hailstone numbers: The sequence of integers generated by Collatz conjecture are called Hailstone Numbers. Examples: Input : N = 7 Output : Hailstone Numbers: 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 No.

  • Iteration: The action or a process of iterating or repeating: such as. : a procedure in which repetition of a sequence of operations yields results successively closer to a desired result.

  • Undecidable problems: An undecidable problem is one that should give a "yes" or "no" answer, but yet no algorithm exists that can answer correctly on all inputs.

  • Unsolvable problems: An unsolvable problem is one for which no algorithm can ever be written to find the solution.

  • Algorithmic efficiency: an aspect of algorithmic programming that measures the number of steps needed to solve a problem

    • inefficient and efficent algorithms have the same objective but one runs more efficiently than the other
  • heuristic approach: a technique designed for solving a problem more quickly when classic methods are too slow

sequence = []
def combinedcollatz(i):
    while i > 1:
        if (i % 2):    # i is odd
            sequence.append(i)
            i = 3*i + 1
        else:   # i is even
            sequence.append(i)
            i = i//2
    if i == 1:
        sequence.append(1)
    else:
        print(i, "is invalid, please try again") #this will print if the number is invalid
i = int(input('Enter i: '))
combinedcollatz(i)
print("Hailstone numbers: ", sequence, "\nNumber of iterations: ", len(sequence)-1)
Hailstone numbers:  [34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] 
Number of iterations:  13