Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Algorithms

&
Data Structure
Class by Venkatesh Tadinada
Housekeeping Tasks
● Verify internet connection speeds
● Make sure you have battery backups (accommodate for power cuts)
● Finding a quieter place is important (note not a quiet place).
● Practice daily
● Join the following sites and send me your handles
○ www.hackerrank.com [ find and follow venkatesh3 ]
○ https://projecteuler.net/
○ http://rosalind.info
● Every Saturday we will take attendance by getting scores from these 3 sites.
● Enjoy and have fun. Different people will learn at different pace, nothing is
wrong with it. [We need Dravids and Sehwags]
Contents
● What Is Computer Science?
● What Is Programming?
● Why Study Data Structures and Abstract Data Types?
● Why Study Algorithms?
● Review of Python
What Is Computer Science?
● Computer science is the study of problems, problem-solving, and the solutions
that come out of the problem-solving process.
● Computer science can be thought of as the study of algorithms.
● Computer science, as it pertains to the problem-solving process itself, is also
the study of abstraction.
● Procedural abstraction. We do not necessarily know how a function does its
calculations, but we know what the function is called and how to use it.
What Is Programming?
● Programming is the process of taking an algorithm and encoding it into a
notation, a programming language, so that it can be executed by a computer.
● Computer science is not the study of programming. Programming, however, is
an important part of what a computer scientist does.
● Programming languages must provide a notational way to represent both the
process and the data. To this end, languages provide control constructs and
data types.
Why Study Data Structures?
● By creating models of the problem domain, we are able to utilize a better and
more efficient problem-solving process.
● An abstract data type, sometimes called an ADT, is a logical description of how
we view the data and the operations that are allowed without regard to how
they will be implemented.
● This provides an implementation independent view of the data.
● Since there will usually be many different ways to implement an abstract data
type, this implementation independence allows the programmer to switch the
details of the implementation without changing the way the user of the data
interacts with it.
Why Study Algorithms?
● Computer scientists learn by experience.
● Being exposed to different problem-solving techniques and seeing how
different algorithms are designed helps us to take on the next challenging
problem that we are given.
● By considering a number of different algorithms, we can begin to develop
pattern recognition so that the next time a similar problem arises, we are better
able to solve it.
Review of Python
Built in atomic data types (1 of 2)

● There are two built in numeric classes that implement atomic data types:
○ int : Stores negative and positive integer values
○ float : Stores negative and positive floating point values
● Arithmetic operations that can be done on the above data type values:
○ Addition: +
○ Subtraction: -
○ Multiplication: *
○ Division: / //
○ Exponential: **
Built in atomic data types (2 of 2)

● Relational and logical operations that can be done on the above values:
○ less than: <
○ greater than: >
○ less than or equal: <=
○ greater than or equal: >=
○ equal: ==
○ not equal: !=
○ logical and: and
○ logical or: or
○ logical not: not
Lists (1 of 2)

● A list is an ordered collection of zero or more references to Python data


objects.
○ my_list = []
○ my_list_2 = [1, ‘abc’, True, 6.5]
● Methods to manipulate lists:
○ Append: a_list.append(item)
○ Insert: a_list.insert(i,item)
○ Pop: a_list.pop()
○ Pop: a_list.pop(i)
○ Sort: a_list.sort()
○ Reverse: a_list.reverse()
Lists (2 of 2)

○ Delete: del a_list[i]


○ Index: a_list.index(item)
○ Count: a_list.count(item)
○ Remove: a_list.remove(item)
Strings (1 of 1)

● Strings are sequential collections of zero or more letters, numbers and other
symbols.
● Literal string values are differentiated from identifiers by using quotation marks
(either single or double).
○ my_string = “Hello World!”
● Methods:
○ Center aligned: a_string.center(w)
○ Count: a_string.count(item)
○ Left justified: a_string.ljust(w)
○ Lower: a_string.lower()
○ Right justified: a_string.rjust(w)
○ Find: a_string.find(item)
○ Split: a_string.split(s_char)
Tuples (1 of 1)

● Tuples are very similar to lists in that they are heterogeneous sequences of
data. The difference is that a tuple is immutable, like a string. A tuple cannot be
changed.
○ my_tuple = (1, True, ‘abc’)
● Methods:
○ Add an element
■ Once created cannot add elements
○ Append an element
■ Once created cannot add elements
○ Delete an element
■ Once created cannot add elements
○ View an element
■ A_tuple[index_value]
Dictionary (1 of 2)

● Unordered set of elements in a key-value format. Can access a value from its
corresponding key but the other way round is not possible.
○ my_dict = {1: ‘a’, 2: ‘b’, 3: ‘c’}
● Methods:
○ Add an element
■ dict_ex[key] = value
○ Delete an element
■ dict_ex.pop(key)
○ View an element
■ A_dict[key]
Dictionary (2 of 2)

○ Keys
■ my_dict.keys()
○ Values
■ my_dict.values()
○ Items
■ my_dict.items()
○ Get
■ my_dict.get(k)
■ my_dict.get(k,alt)
Sets (1 of 2)

● A set is an unordered collection of zero or more immutable Python data


objects. Sets do not allow duplicates.
○ my_set = {1, ‘my cat’, False}
○ My_set = set()
● Methods:
○ Storing values in a set
■ my_Set.add(value)
■ my_Set.update(value)
○ Removing values from a set
■ my_Set.discard(value)
■ my_Set.remove(value)
■ my_Set.pop(value) or my_Set.pop()
Sets (2 of 2)

■ Set operations
● set1.union(set2)
● set1.intersection(set2)
● set1.difference(set2)
● set1.symmetric_difference(set2)
Operations that can be done on
sequences: (1 of 1)

● Indexing: [ ]
● Concatenation: +
● Repetition: *
● Membership: in
● Length: len
● Slicing: [ : ]
Input (1 of 1)

● Python provides us with a function that allows us to ask a user to enter some
data and returns a reference to the data in the form of a string. The function is
called input.
● Python’s input function takes a single parameter that is a string. This string is
often called the prompt because it contains some helpful text prompting the
user to enter something.
○ user_data = input(“Enter value”)
● Input stores value as string. So to perform any numeric operations onit, you
need to typecast it.
○ int(input())
String formatting (1 of 2)

● Print:
○ print takes zero or more parameters and displays them using a single blank as the default
separator. It is possible to change the separator character by setting the sep argument.
■ print(“Hello world”)
● Output: Hello World
■ print(“Hello”, “World”, sep=”---”)
● Output: Hello---World
■ print(“Hello”, end=”---”); print(“World”)
● Output: Hello---World
String formatting (2 of 2)

● String formats:
○ You can use a format operator (%) and a conversion character (s, d, i, f, etc) in a string to specify
what kind of value to be printed.
■ print(“My name is %s and my age is %d” % (name, age))
■ print("The %(item)s costs %(cost)7.1f cents" % item_dict)
● Uses dictionary key values in the string.
○ You can use constant values between format operater and conversion character to specify
width of the string.
■ %20d: Put the value in a field width of 20
■ %-20d: Put the value in a field 20 characters wide, left-justified
■ %+20d: Put the value in a field 20 characters wide, right-justified
■ %020d: Put the value in a field 20 characters wide, fill in with leading zeros
■ %20.2f: Put the value in a field 20 characters wide with 2 characters to the right of the
decimal point.
Control Structure (1 of 2)

● Loops:
○ To execute a particular block of code repeatedly we use loops.
○ While loops:
■ while i < 10 :
■ print(i)
○ For loops:
■ for i in range(10):
■ print(i)
Control Structure (2 of 2)

● Selection statements:
○ Checking a condition and executing related block of code.
○ If-else:
■ if condition:
■ <statement>
■ else:
■ <statement>
List Comprehension (1 of 1)

● There is an alternative method for creating a list that uses iteration and
selection constructs. The is known as a list comprehension. A list
comprehension allows you to easily create a list based on some processing or
selection criteria.
○ sq_list = [x * x for x in range(1, 11)]
○ print(sq_list)
■ Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Exception Handling (1 of 2)

● Logical errors lead to very bad situations such as trying to divide by zero or
trying to access an item in a list where the index of the item is outside the
bounds of the list.
● In this case, the logic error leads to a runtime error that causes the program to
terminate. These types of runtime errors are typically called exceptions.
● Exceptions can be handled, catched, by writing the exception causing lines in
a block and handling those errors in a separate block.
Exception Handling (2 of 2)

○ try:
○ <exception causing lines>
○ except:
○ <handling those exceptions>
● Example:
○ try:
○ print(10//0)
○ except:
○ print(“Can not divide a value by zero”)
Functions (1 of 1)

● Basic concept of a function


○ It is a block of organized code which has a specific functionality and is reusable.
● Syntax to define a function
○ def function_name:
○ <statement>
○ <statement>
Classes (1 of 2)

● One of the most powerful features in an object-oriented programming


language is the ability to allow a programmer to create new classes that model
data that is needed to solve the problem.
● To create a class:
○ class class_name:
○ #methods and attributes of the class
Classes (2 of 2)

● __init__ function of a class is its constructor.


○ def __init__(self[, parameters]):
○ # initialization of attributes of the class
● self is a special parameter that will always be used as a reference back to the
object itself.
● __str__ is the method to convert an object into a string.
○ def __str__(self):
○ return str(self.obj )
● __add__ is the method to add two values (+). Similar methods are available for
subtraction, multiplication, division, equals to, less than equals to, etc.

You might also like