python data structures coursera assignment 6 5

Python Data Structures

Week 1 - assignment 6.5.

Write code using find() and string slicing to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out.

text = "X-DSPAM-Confidence: 0.8475";

text = "X-DSPAM-Confidence: 0.8475"

Colpos = text.find(':') # Colon Position

text_a_Colpos = text[Colpos+1 : ] # Text after colon position

number = text_a_Colpos.strip()

print(float(number))

ans = float(text_a_Colpos)

# Using Split and join functions

num_str = text_a_Colpos.split() # string format of number in list

d = ""

num = d.join(num_str) # converts list into string

num_f = float(num)

print(num_f)

=============================================================================================

Week 3 - Assignment 7.1

Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below.

when you are testing below enter words.txt as the file name.

file = input('Enter the file name: ')

fhandle = open(file)

for line in fhandle:

line_strip = line.strip()

line = line_strip.upper()

print(line)

Assignment 7.2

Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:

X-DSPAM-Confidence: 0.8475

Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.

when you are testing below enter mbox-short.txt as the file name.

fname = input('Enter the file name: ')

fhandle = open(fname)

for line in fhandle :

if 'X-DSPAM-Confidence:' in line :

Colpos = line.find(':')

num_string = line[Colpos + 1 : ]

num = float(num_string)

count = count + 1

Total = Total + num

avg = Total / count

print('Average spam confidence:',avg)

===============================================================================================

Week 4 - Assignment 8.4

Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

fhandle = open('romeo.txt')

lst = list()

words = line.split()

print(words)

for word in words:

if lst is None:

lst.append(word)

elif word in lst:

Assignment 8.5

Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line:

From [email protected] Sat Jan 5 09:14:16 2008

You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end.

Hint: make sure not to include the lines that start with 'From:'.

if line.startswith('From') :

if line[4] is ':' :

req_line = line.split()

print(req_line[1])

print('There were',count, 'lines in the file with From as the first word')

==============================================================================================

Week 5 - Assignment 9.4

Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.

reg_mailer = dict() # regular mailer

mail = words[1]

# reg_mailer[mail] = reg_mailer.get(mail,0) + 1

if reg_mailer is None or mail not in reg_mailer :

reg_mailer[mail] = 1

reg_mailer[mail] = reg_mailer[mail] + 1

a = max(reg_mailer.values())

for key, value in reg_mailer.items() :

if value == a :

print(key,a)

Week 6 - Assignment 10.2

Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages.

You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.

Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.

time_mail = dict()

time = words[5]

time_tup = time.split(':')

time_tuple = time_tup[0]

time_mail[time_tuple] = time_mail.get(time_tuple,0) + 1

# if reg_mailer is None or mail not in reg_mailer :

# reg_mailer[mail] = 1

# reg_mailer[mail] = reg_mailer[mail] + 1

ans = sorted(time_mail.items())

for k,v in ans:

Search This Blog

Coursera python data structures assignment answers.

This course will introduce the core data structure of the Python programming ... And, the answer is only for hint . it is helpful for those student who haven't submit Assignment and who confused ... These five lines are the lines to do this particular assignment where we are ...

chapter 6 week 1 Assignment 6.5

python data structures coursera assignment 6 5

Post a Comment

if you have any doubt , please write comment

Popular posts from this blog

Chapter 9 week 5 assignment 9.4.

Image

chapter 10 week 6 Assignment 10.2

Image

  • Python »
  • 3.9.19 Documentation »
  • The Python Tutorial »

5. Data Structures ¶

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.

5.1. More on Lists ¶

The list data type has some more methods. Here are all of the methods of list objects:

Add an item to the end of the list. Equivalent to a[len(a):] = [x] .

Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable .

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x) .

Remove the first item from the list whose value is equal to x . It raises a ValueError if there is no such item.

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

Remove all items from the list. Equivalent to del a[:] .

Return zero-based index in the list of the first item whose value is equal to x . Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Return the number of times x appears in the list.

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

Reverse the elements of the list in place.

Return a shallow copy of the list. Equivalent to a[:] .

An example that uses most of the list methods:

You might have noticed that methods like insert , remove or sort that only modify the list have no return value printed – they return the default None . 1 This is a design principle for all mutable data structures in Python.

Another thing you might notice is that not all data can be sorted or compared. For instance, [None, 'hello', 10] doesn’t sort because integers can’t be compared to strings and None can’t be compared to other types. Also, there are some types that don’t have a defined ordering relation. For example, 3+4j < 5+7j isn’t a valid comparison.

5.1.1. Using Lists as Stacks ¶

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append() . To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

5.1.2. Using Lists as Queues ¶

It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:

5.1.3. List Comprehensions ¶

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:

or, equivalently:

which is more concise and readable.

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

and it’s equivalent to:

Note how the order of the for and if statements is the same in both these snippets.

If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.

List comprehensions can contain complex expressions and nested functions:

5.1.4. Nested List Comprehensions ¶

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

The following list comprehension will transpose rows and columns:

As we saw in the previous section, the nested listcomp is evaluated in the context of the for that follows it, so this example is equivalent to:

which, in turn, is the same as:

In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:

See Unpacking Argument Lists for details on the asterisk in this line.

5.2. The del statement ¶

There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:

del can also be used to delete entire variables:

Referencing the name a hereafter is an error (at least until another value is assigned to it). We’ll find other uses for del later.

5.3. Tuples and Sequences ¶

We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range ). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple .

A tuple consists of a number of values separated by commas, for instance:

As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable , and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples ). Lists are mutable , and their elements are usually homogeneous and are accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:

The statement t = 12345, 54321, 'hello!' is an example of tuple packing : the values 12345 , 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

5.4. Sets ¶

Python also includes a data type for sets . A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set() , not {} ; the latter creates an empty dictionary, a data structure that we discuss in the next section.

Here is a brief demonstration:

Similarly to list comprehensions , set comprehensions are also supported:

5.5. Dictionaries ¶

Another useful data type built into Python is the dictionary (see Mapping Types — dict ). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys , which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend() .

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {} . Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del . If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.

Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.

Here is a small example using a dictionary:

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

5.6. Looping Techniques ¶

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

Using set() on a sequence eliminates duplicate elements. The use of sorted() in combination with set() over a sequence is an idiomatic way to loop over unique elements of the sequence in sorted order.

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

5.7. More on Conditions ¶

The conditions used in while and if statements can contain any operators, not just comparisons.

The comparison operators in and not in check whether a value occurs (does not occur) in a sequence. The operators is and is not compare whether two objects are really the same object. All comparison operators have the same priority, which is lower than that of all numerical operators.

Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c .

Comparisons may be combined using the Boolean operators and and or , and the outcome of a comparison (or of any other Boolean expression) may be negated with not . These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C . As always, parentheses can be used to express the desired composition.

The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C . When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.

It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,

Note that in Python, unlike C, assignment inside expressions must be done explicitly with the walrus operator := . This avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.

5.8. Comparing Sequences and Other Types ¶

Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:

Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.

Other languages may return the mutated object, which allows method chaining, such as d->insert("a")->remove("b")->sort(); .

Table of Contents

  • 5.1.1. Using Lists as Stacks
  • 5.1.2. Using Lists as Queues
  • 5.1.3. List Comprehensions
  • 5.1.4. Nested List Comprehensions
  • 5.2. The del statement
  • 5.3. Tuples and Sequences
  • 5.5. Dictionaries
  • 5.6. Looping Techniques
  • 5.7. More on Conditions
  • 5.8. Comparing Sequences and Other Types

Previous topic

4. More Control Flow Tools

  • Report a Bug
  • Show Source

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

My solutions to assignments of Data structures and algorithms (by UCSD and HSE) on Coursera. All problems from Course 1 to Course 5 have been solved.

Sonia-96/Coursera-Data_Structures_and_Algorithms

Folders and files, repository files navigation, coursera-data_structures_and_algorithms.

My solutions to assignments of Data structures and algorithms (by UCSD and HSE) on Coursera. All problems from course 1 to course 5 have been solved.

Course 1: Algorithmic Toolbox [Certificate]

Algorithmic Warm-up

  • Fibonacci Number
  • Last Digit of a Large Fibonacci Number
  • Greatest Common Divisor
  • Least Common Multiple
  • Fibonacci Number Again
  • Last Digit of the Sum of Fibonacci Numbers
  • Last Digit of the Sum of Fibonacci Numbers Again
  • Last Digit of the Sum of Squares of Fibonacci Numbers

Greedy Algorithms

  • Money Change
  • Maximum Value of the Loot
  • Car Fueling
  • Maximum Advertisement Revenue
  • Collecting Signatures
  • Maximum Number of Prizes
  • Maximum Salary

Divide and Conquer

  • Binary Search
  • Majority Element
  • Improving Quick Sort
  • Number of Inversions
  • Organizing a Lottery [naive] [faster]
  • Closest Points

Dynamic Programming 1

  • Money Change Again
  • Primitive Calculator
  • Edit Distance
  • Longest Common Subsequence of Two Sequences
  • Longest Common Subsequence of Three Sequences

Dynamic Programming 2

  • Maximum Amount of Gold
  • Partitioning Souvenirs
  • Maximum Value of an Arithmetic Expression

Course 2: Data Structures [Certificate]

Basic Data Structures

  • Check brackets in the code
  • Compute tree height
  • Network packet processing simulation
  • Extending stack interface
  • Maximum in Sliding Window

Priority Queues and Disjoint Sets

  • Convert array into heap
  • Parallel processing
  • Merging tables

Hash Tables and Hash Functions

  • Hashing with chains
  • Find pattern in text
  • Substring equality
  • Longest common substring
  • Pattern matching with mismatches

Binary Search Trees

  • Binary tree traversals
  • Is it a binary search tree? [in-order traversal] [min/max constraint]
  • Is it a binary search tree? Hard version
  • Set with range sums
  • Rope [naive method] [rope structure]

Course 3: Algorithms on Graphs [Certificate]

Undirected Graphs

  • Finding an Exit from a Maze
  • Adding Exits to a Maze

Directed Graphs

  • Checking Consistency of CS Curriculum
  • Determining an Order of Courses
  • Advanced Problem: Checking Whether Any Intersection in a City is Reachable from Any Other

Most Direct Route

  • Computing the Minimum Number of Flight Segments
  • Checking whether a Graph is Bipartite

Fastest Route

  • Computing the Minimum Cost of a Flight
  • Detecting Anomalies in Currency Exchange Rates
  • Advanced Problem: Exchanging Money Optimally

Minimum Spanning Trees

  • Building Roads to Connect Cities

Course 4: Algorithms on Strings [Certificate]

Suffix Trees

  • Construct a Trie from a Collection of Patterns
  • Implement TrieMatching
  • Extend TrieMatching
  • Construct the Suffix Tree of a String
  • Advanced Problem: Find the Shortest Non-Shared Substring of Two Strings

Burrows–Wheeler Transform and Suffix Arrays

  • Construct the Burrows–Wheeler Transform of a String
  • Reconstruct a String from its Burrows–Wheeler Transform
  • Implement BetterBWMatching
  • Construct the Suffix Array of a String

Algorithmic Challenges

  • Find All Occurrences of a Pattern in a String
  • Construct the Suffix Array of a Long String
  • Pattern Matching with the Suffix Array
  • Advanced Problem: Construct the Suffix Tree from the Suffix Array

Course 5: Advanced Algorithms and Complexity [Certificate]

Flows in Networks

  • Evacuating People
  • Assigning Airline Crews to Flights
  • Advanced Problem: Stock Charts

Linear Programming

  • Infer Energy Values of Ingredients [1] [2]
  • Optimal Diet Problem
  • Advanced Problem: Online Advertisement Allocation (Two-Phase Simplex)

NP-completeness

  • Assign Frequencies to the Cells of a GSM Network
  • Cleaning the Apartment
  • Advanced Problem: Advertisement Budget Allocation

Coping with NP-completeness

  • Integrated Circuit Design
  • Plan a Fun Party
  • School Bus (Traveling Salesman)
  • Advanced Problem: Reschedule the Exams
  • Python 100.0%
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Operators

Precedence and associativity of operators in python.

  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic

Ternary Operator in Python

  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. 

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Identity Operators and Membership Operators

Python Operators

Arithmetic Operators in Python

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication , and division .

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

Example of Arithmetic Operators in Python

Division operators.

In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. 

There are two types of division operators: 

Float division

  • Floor division

The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:

Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’ , and ‘-10/2’ results in ‘-5.0’ .

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:

Example: The code demonstrates integer (floor) division operations using the // in Python operators . It provides results as follows: ’10//3′ equals ‘3’ , ‘-5//2’ equals ‘-3’ , ‘ 5.0//2′ equals ‘2.0’ , and ‘-5.0//2’ equals ‘-3.0’ . Integer division returns the largest integer less than or equal to the division result.

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

  • P – Parentheses
  • E – Exponentiation
  • M – Multiplication (Multiplication and division have the same precedence)
  • D – Division
  • A – Addition (Addition and subtraction have the same precedence)
  • S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’ . It adds (‘+’) , subtracts (‘-‘) , multiplies (‘*’) , computes the remainder (‘%’) , and raises a to the power of ‘b (**)’ . The results of these operations are printed.

Note: Refer to Differences between / and // for some interesting facts about these two Python operators.

Comparison of Python Operators

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.

Example of Comparison Operators in Python

Let’s see an example of Comparison Operators in Python.

Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’ .

Logical Operators in Python

Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to combine conditional statements.

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:

  • Logical not
  • logical and

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true ( ‘and’ ), if at least one of them is true ( ‘or’ ), and negates the value of ‘a’ using ‘not’ . The results are printed accordingly.

Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:

  • Bitwise NOT
  • Bitwise Shift
  • Bitwise AND
  • Bitwise XOR

Here is an example showing how Bitwise Operators in Python work:

Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’ . It performs bitwise AND (&) , OR (|) , NOT (~) , XOR (^) , right shift (>>) , and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers.

Python Assignment operators are used to assign values to the variables.

Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’ . The results of each operation are printed, showing the impact of these operations on the value of ‘b’ .

Identity Operators in Python

In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical. 

Example Identity Operators in Python

Let’s see an example of Identity Operators in Python.

Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’ ).

Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

Examples of Membership Operators in Python

The following code shows how to implement Membership Operators in Python:

Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.

in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. 

It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :   [on_true] if [expression] else [on_false] 

Examples of Ternary Operator in Python

The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional assignment to determine the smaller of the two values and assigns it to the variable ‘min’ . Finally, it prints the value of ‘min’ , which is 10 in this case.

In Python, Operator precedence and associativity determine the priorities of the operator.

Operator Precedence in Python

This is used in an expression with more than one operator with different precedence to determine which operation to perform first.

Let’s see an example of how Operator Precedence in Python works:

Example: The code first calculates and prints the value of the expression 10 + 20 * 30 , which is 610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the name is “ Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”

Operator Associativity in Python

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

The following code shows how Operator Associativity in Python works:

Example: The code showcases various mathematical operations. It calculates and prints the results of division and multiplication, addition and subtraction, subtraction within parentheses, and exponentiation. The code illustrates different mathematical calculations and their outcomes.

To try your knowledge of Python Operators, you can take out the quiz on Operators in Python . 

Python Operator Exercise Questions

Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below.

Q1. Code to implement basic arithmetic operations on integers

Q2. Code to implement Comparison operations on integers

Explore more Exercises: Practice Exercise on Operators in Python

Please Login to comment...

Similar reads.

  • python-basics
  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Python Data Structures Assignment 6.5 Solution [Coursera]

    python data structures coursera assignment 6 5

  2. Coursera: Python Data Structures Complete Course Assignment Solutions |Python Data Structures Answer

    python data structures coursera assignment 6 5

  3. Coursera Python Data Structures WEEK 5 & 6 Quiz Answers

    python data structures coursera assignment 6 5

  4. Data Structures and Algorithms in Python

    python data structures coursera assignment 6 5

  5. Coursera: Python Data-Structures University of Michigan -all

    python data structures coursera assignment 6 5

  6. Data Structures and Algorithms In Python

    python data structures coursera assignment 6 5

VIDEO

  1. Python For Everybody Assignment 8.5

  2. Coursera: 8.4 Assignment// python data structures assignment 8.4 solution

  3. Python for Data Science, AI & Development,(week1-5) All Quiz Answers.#coursera #mr #quiz #quiztime

  4. Programming Data Structures And Algorithms Using Python Week 6 Assignment

  5. NPTEL: Programming , Data Structures and Algorithms Using Python Week 2 Quiz answer with proof(100%)

  6. Python for Data Science, AI & Development IBM Skills Network

COMMENTS

  1. Coursera-PY4E-Python-Data-Structures/Assignment-6.5 at master ...

    Contribute to riya2905/Coursera-PY4E-Python-Data-Structures development by creating an account on GitHub.

  2. Python Data Structures Assignment 6.5 Solution [Coursera ...

    Python Data Structures Assignment 6.5 Solution [Coursera] | Assignment 6.5 Python Data StructuresCoursera: Programming For Everybody Assignment 6.5 program s...

  3. Python Data Structures

    This course will introduce the core data structures of the Python programming language. We will move past the basics of procedural programming and explore how we can use the Python built-in data structures such as lists, dictionaries, and tuples to perform increasingly complex data analysis. This course will cover Chapters 6-10 of the textbook ...

  4. Coursera: 6.5 assignment solution//PYTHON DATA STRUCTURES ASSIGNMENT 6

    # Coursera :- #python data structures# Python👇👇program here 👇👇https://1drv.ms/w/s!AspSlroH33QienFKFd9JabrN5skCHAPTER :- PYTHON DATA STRUCTURESASSIGNMENT...

  5. N. Lokesh Reddy

    Python Data Structures. Week 1 - Assignment 6.5. Write code using find() and string slicing to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out. ... The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in ...

  6. Coursera: Python Data Structures Complete Course Assignment ...

    Text File of All 7 Assignment Coding :- https://ko-fi.com/s/bf5f9906dfFiles For Indian Payment Users:- Https://imojo.in/PythonC2Python Data Structures Course...

  7. shreyansh225/Coursera-Python-Data-Structures-University-of ...

    All my solved ASSIGNMENTS & QUIZZES in Python Data Structure course on COURSERA using Python 3. Topics python coursera python3 coursera-assignment coursera-python python-data-structures coursera-solutions

  8. chapter 6 week 1 Assignment 6.5

    chapter 6 week 1 Assignment 6.5. Tuesday, June 16, 2020. 6.5 Write code using find () and string slicing (see section 6.10) to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out.

  9. 5. Data Structures

    This is a design principle for all mutable data structures in Python. 5.1.1. Using Lists as Stacks ¶. The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved ("last-in, first-out"). To add an item to the top of the stack, use append().

  10. PYTHON-DATA STRUCTURE(ASSIGNMENT-6.5) COUSERA

    About Press Copyright Contact us Creators Advertise Developers Terms Privacy Policy & Safety How YouTube works Test new features NFL Sunday Ticket Press Copyright ...

  11. Python Data Structures

    We will move past the basics of procedural programming and explore how we can use the Python built-in data structures such as lists, dictionaries, and tuples to perform increasingly complex data analysis. This course will cover Chapters 6-10 of the textbook "Python for Everybody". This course covers Python 3.

  12. Algorithms for Searching, Sorting, and Indexing

    In this module, the student will learn about the basics of data structures that organize data to make certain types of operations faster. The module starts with a broad introduction to data structures and talks about some simple data structures such as first-in first out queues and last-in first out stack.

  13. Python Data Structures

    Offered by University of Michigan. This course will introduce the core data structures of the Python programming language. We will move past ... Enroll for free.

  14. 5. Data Structures

    5. Data Structures¶ This chapter describes some things you've learned about already in more detail, and adds some new things as well. 5.1. More on Lists¶ The list data type has some more methods. Here are all of the methods of list objects: list.append (x) Add an item to the end of the list. Equivalent to a[len(a):] = [x]. list.extend ...

  15. Python Data Structures || Week 1

    Hi everyone,This video is for education purpose onlylike share and subscribe for more videoPlease visit my Blog to see more contenthttps://priyadigitalworld....

  16. Sonia-96/Coursera-Data_Structures_and_Algorithms

    My solutions to assignments of Data structures and algorithms (by UCSD and HSE) on Coursera. All problems from Course 1 to Course 5 have been solved. - Sonia-96/Coursera-Data_Structures_and_Algorithms

  17. Python Data Structures Course by University of Michigan

    In the first part of the capstone, students will do some visualizations to become familiar with the technologies in use and then will pursue their own project to visualize some other data that they have or can find. Chapters 15 and 16 from the book "Python for Everybody" will serve as the backbone for the capstone. This course covers Python 3.

  18. Python Operators

    Assignment Operators in Python. Let's see an example of Assignment Operators in Python. Example: The code starts with 'a' and 'b' both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on 'b'.

  19. Coursera: 8.5 Assignment solution//Python data structures ...

    #circuitryproject# Coursera #python data structures# PythonCHAPTER :- PYTHON DATA STRUCTURESASSIGNMENT:- 👇👇👇👇Assignment:- 6.5 Solution 👇👇https://youtu...

  20. Learner Reviews & Feedback for Get Started with Python Course

    Course 2, "Get Started With Python," in the Advanced Data Analytics specialization by Google on Coursera was an invaluable learning experience. The content provided a solid foundation in Python programming, covering essential topics such as functions, conditional statements, loops, strings, and data structures.

  21. Databases and SQL for Data Science with Python

    You will: -write foundational SQL statements like: SELECT, INSERT, UPDATE, and DELETE -filter result sets, use WHERE, COUNT, DISTINCT, and LIMIT clauses -differentiate between DML & DDL -CREATE, ALTER, DROP and load tables -use string patterns and ranges; ORDER and GROUP result sets, and built-in database functions -build sub-queries and query ...