Instantly share code, notes, and snippets.

@jennyonjourney

jennyonjourney / gist:f71a36dfa36849378a1be9f7708e5e01

  • Download ZIP
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.
  • Learn more about clone URLs
  • Save jennyonjourney/f71a36dfa36849378a1be9f7708e5e01 to your computer and use it in GitHub Desktop.

@anishagithub

anishagithub commented Jul 3, 2021

why is my code not working: xs=open('8.5not.txt') c=dict() p=list() for line in xs: if line.startswith('From '): words=line.split() else: continue for word in words: m=word[5].split(':') c[m[0]]=c.get(m[0],0)+1 for k,v in c.items(): p.append(k,v) p.sort() print(p)

Sorry, something went wrong.

@kapazan

kapazan commented Oct 16, 2022

The code works but it is still problematic. If you write "From" instead of "From " without a space at the end, code blows up as it also iterates the lines whose length are smaller than 5.

Programming for Everybody: Assignment 10.2 Tuples and Sorting - edorlando07/datasciencecoursera GitHub Wiki

###Python Data Structures

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.

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

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

A sample section of the text file is listed below:

###The actual code starts below:

###If words was printed now, the output would include the following:

###The next piece of the code is continued below

###The next piece of the code is continued below:

#The final output is delivered below:

  • Python »
  • 3.12.3 Documentation »
  • The Python Tutorial »
  • 5. Data Structures
  • Theme Auto Light Dark |

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. It raises an IndexError if the list is empty or the index is outside the list range.

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 inner list comprehension 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 are membership tests that determine whether a value is in (or not in) a container. 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.

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

assignment 10.2 python data structures

  • Runestone in social media: Follow @iRunestone Our Facebook Page
  • Table of Contents
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • This Chapter
  • 1. Introduction' data-toggle="tooltip" >

Problem Solving with Algorithms and Data Structures using Python ¶

PythonDS Cover

By Brad Miller and David Ranum, Luther College

There is a wonderful collection of YouTube videos recorded by Gerry Jenkins to support all of the chapters in this text.

  • 1.1. Objectives
  • 1.2. Getting Started
  • 1.3. What Is Computer Science?
  • 1.4. What Is Programming?
  • 1.5. Why Study Data Structures and Abstract Data Types?
  • 1.6. Why Study Algorithms?
  • 1.7. Review of Basic Python
  • 1.8.1. Built-in Atomic Data Types
  • 1.8.2. Built-in Collection Data Types
  • 1.9.1. String Formatting
  • 1.10. Control Structures
  • 1.11. Exception Handling
  • 1.12. Defining Functions
  • 1.13.1. A Fraction Class
  • 1.13.2. Inheritance: Logic Gates and Circuits
  • 1.14. Summary
  • 1.15. Key Terms
  • 1.16. Discussion Questions
  • 1.17. Programming Exercises
  • 2.1.1. A Basic implementation of the MSDie class
  • 2.2. Making your Class Comparable
  • 3.1. Objectives
  • 3.2. What Is Algorithm Analysis?
  • 3.3. Big-O Notation
  • 3.4.1. Solution 1: Checking Off
  • 3.4.2. Solution 2: Sort and Compare
  • 3.4.3. Solution 3: Brute Force
  • 3.4.4. Solution 4: Count and Compare
  • 3.5. Performance of Python Data Structures
  • 3.7. Dictionaries
  • 3.8. Summary
  • 3.9. Key Terms
  • 3.10. Discussion Questions
  • 3.11. Programming Exercises
  • 4.1. Objectives
  • 4.2. What Are Linear Structures?
  • 4.3. What is a Stack?
  • 4.4. The Stack Abstract Data Type
  • 4.5. Implementing a Stack in Python
  • 4.6. Simple Balanced Parentheses
  • 4.7. Balanced Symbols (A General Case)
  • 4.8. Converting Decimal Numbers to Binary Numbers
  • 4.9.1. Conversion of Infix Expressions to Prefix and Postfix
  • 4.9.2. General Infix-to-Postfix Conversion
  • 4.9.3. Postfix Evaluation
  • 4.10. What Is a Queue?
  • 4.11. The Queue Abstract Data Type
  • 4.12. Implementing a Queue in Python
  • 4.13. Simulation: Hot Potato
  • 4.14.1. Main Simulation Steps
  • 4.14.2. Python Implementation
  • 4.14.3. Discussion
  • 4.15. What Is a Deque?
  • 4.16. The Deque Abstract Data Type
  • 4.17. Implementing a Deque in Python
  • 4.18. Palindrome-Checker
  • 4.19. Lists
  • 4.20. The Unordered List Abstract Data Type
  • 4.21.1. The Node Class
  • 4.21.2. The Unordered List Class
  • 4.22. The Ordered List Abstract Data Type
  • 4.23.1. Analysis of Linked Lists
  • 4.24. Summary
  • 4.25. Key Terms
  • 4.26. Discussion Questions
  • 4.27. Programming Exercises
  • 5.1. Objectives
  • 5.2. What Is Recursion?
  • 5.3. Calculating the Sum of a List of Numbers
  • 5.4. The Three Laws of Recursion
  • 5.5. Converting an Integer to a String in Any Base
  • 5.6. Stack Frames: Implementing Recursion
  • 5.7. Introduction: Visualizing Recursion
  • 5.8. Sierpinski Triangle
  • 5.9. Complex Recursive Problems
  • 5.10. Tower of Hanoi
  • 5.11. Exploring a Maze
  • 5.12. Dynamic Programming
  • 5.13. Summary
  • 5.14. Key Terms
  • 5.15. Discussion Questions
  • 5.16. Glossary
  • 5.17. Programming Exercises
  • 6.1. Objectives
  • 6.2. Searching
  • 6.3.1. Analysis of Sequential Search
  • 6.4.1. Analysis of Binary Search
  • 6.5.1. Hash Functions
  • 6.5.2. Collision Resolution
  • 6.5.3. Implementing the Map Abstract Data Type
  • 6.5.4. Analysis of Hashing
  • 6.6. Sorting
  • 6.7. The Bubble Sort
  • 6.8. The Selection Sort
  • 6.9. The Insertion Sort
  • 6.10. The Shell Sort
  • 6.11. The Merge Sort
  • 6.12. The Quick Sort
  • 6.13. Summary
  • 6.14. Key Terms
  • 6.15. Discussion Questions
  • 6.16. Programming Exercises
  • 7.1. Objectives
  • 7.2. Examples of Trees
  • 7.3. Vocabulary and Definitions
  • 7.4. List of Lists Representation
  • 7.5. Nodes and References
  • 7.6. Parse Tree
  • 7.7. Tree Traversals
  • 7.8. Priority Queues with Binary Heaps
  • 7.9. Binary Heap Operations
  • 7.10.1. The Structure Property
  • 7.10.2. The Heap Order Property
  • 7.10.3. Heap Operations
  • 7.11. Binary Search Trees
  • 7.12. Search Tree Operations
  • 7.13. Search Tree Implementation
  • 7.14. Search Tree Analysis
  • 7.15. Balanced Binary Search Trees
  • 7.16. AVL Tree Performance
  • 7.17. AVL Tree Implementation
  • 7.18. Summary of Map ADT Implementations
  • 7.19. Summary
  • 7.20. Key Terms
  • 7.21. Discussion Questions
  • 7.22. Programming Exercises
  • 8.1. Objectives
  • 8.2. Vocabulary and Definitions
  • 8.3. The Graph Abstract Data Type
  • 8.4. An Adjacency Matrix
  • 8.5. An Adjacency List
  • 8.6. Implementation
  • 8.7. The Word Ladder Problem
  • 8.8. Building the Word Ladder Graph
  • 8.9. Implementing Breadth First Search
  • 8.10. Breadth First Search Analysis
  • 8.11. The Knight’s Tour Problem
  • 8.12. Building the Knight’s Tour Graph
  • 8.13. Implementing Knight’s Tour
  • 8.14. Knight’s Tour Analysis
  • 8.15. General Depth First Search
  • 8.16. Depth First Search Analysis
  • 8.17. Topological Sorting
  • 8.18. Strongly Connected Components
  • 8.19. Shortest Path Problems
  • 8.20. Dijkstra’s Algorithm
  • 8.21. Analysis of Dijkstra’s Algorithm
  • 8.22. Prim’s Spanning Tree Algorithm
  • 8.23. Summary
  • 8.24. Key Terms
  • 8.25. Discussion Questions
  • 8.26. Programming Exercises

Acknowledgements ¶

We are very grateful to Franklin Beedle Publishers for allowing us to make this interactive textbook freely available. This online version is dedicated to the memory of our first editor, Jim Leisy, who wanted us to “change the world.”

Indices and tables ¶

Search Page

Creative Commons License

Search This Blog

Ashvini sharma.

Hello dosto! Welcome to my Blog . I am so happy to visit my blog. In this blog you can find your maximum information as like related to Coursera in, you find all quiz and assignment weekly as your course embedded.

Python data structures: Assignment 10.2

Post a comment.

Comments here for more information.........

Popular posts from this blog

Python data structures: assignment 7.1, python data structure: assignment 8.4, programming for everybody (python) assignment 5.2, coursera:web application technologies and django.

Image

Python data structures Chapter 6 Quiz

Image

Data Structures and Algorithms in Python

This course is a beginner-friendly introduction to common data structures (linked lists, stacks, queues, graphs) and algorithms (search, sorting, recursion, dynamic programming) in Python. This course will help you ace coding assessments and technical interviews.

  • Watch live hands-on coding-focused video tutorials
  • Practice coding with cloud Jupyter notebooks
  • Solve questions from real programming interviews
  • Earn a verified certificate of accomplishment

Lesson 1 - Binary Search, Linked Lists and Complexity Preview

  • Linear and Binary Search
  • Complexity and Big O Notation
  • Linked Lists using Python Classes

Assignment 1 - Binary Search Practice Preview

  • Understand and solve a problem systematically
  • Implement linear search and analyze it
  • Optimize the solution using binary search

Lesson 2 - Binary Search Trees, Traversals and Recursion Preview

  • Binary trees, traversals, and recursion
  • Binary search trees & common operations
  • Balanced binary trees and optimizations

Assignment 2 - Hash Tables and Python Dictionaries

  • Hash tables from scratch in Python
  • Handling collisions using linear probing
  • Replicating Python dictionaries

Lesson 3 - Sorting Algorithms and Divide & Conquer

  • Bubble sort and Insertion Sort
  • Merge sort using Divide & Conquer
  • Quicksort and average complexity

Assignment 3 - Divide and Conquer Practice

  • Implement polynomial multiplication
  • Optimize using divide and conquer
  • Analyze time and space complexity

Lesson 4 - Recursion and Dynamic Programming

  • Recursion and memoization
  • Subsequence and knapsack problems
  • Backtracking and pruning

Lesson 5 - Graph Algorithms (BFS, DFS & Shortest Paths)

  • Graphs, trees, and adjacency lists
  • Breadth-first and depth-first search
  • Shortest paths and directed graphs

Project - Solve a Programming Problem Step-by-Step

  • Pick an interesting coding problem
  • Solve the problem step-by-step
  • Document and present the solution

Lesson 6 - Python Interview Questions, Tips & Advice

  • Practice questions and solutions
  • Tips for solving coding challenges
  • Advice for cracking coding interviews

Certificate of Accomplishment

Earn a verified certificate of accomplishment ( sample ) by completing all weekly assignments. The certificate can be added to your LinkedIn profile, linked from your Resume, and downloaded as a PDF.

Instructor - Aakash N S

Aakash N S is the co-founder and CEO of Jovian . Previously, Aakash has worked as a software engineer (APIs & Data Platforms) at Twitter in Ireland & San Francisco and graduated from the Indian Institute of Technology, Bombay. He’s also an avid blogger, open-source contributor, and online educator.

assignment 10.2 python data structures

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:

IMAGES

  1. Python Data Structures Cheat-sheet

    assignment 10.2 python data structures

  2. Python Data Structures #2: Linked List

    assignment 10.2 python data structures

  3. Fundamental Data Structures in Python

    assignment 10.2 python data structures

  4. Python Tutorials: How to use Data Structures in Python

    assignment 10.2 python data structures

  5. Data Structures in Python (A Complete Guide)

    assignment 10.2 python data structures

  6. Python Data Structure| Assignment 10.2 solution

    assignment 10.2 python data structures

VIDEO

  1. Programming, Data Structures and Algorithms using Python || NPTEL week 1 answers 2024 || #nptel

  2. python

  3. python

  4. Week3Programming, Data Structures And Algorithms Using Python|Assignment3ANSWERS|NPTEL|Jan2024

  5. python

  6. 0x03. Python

COMMENTS

  1. Python Data Structures (Coursera) Assignement 10.2 · GitHub

    Python Data Structures (Coursera) Assignement 10.2. # 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.

  2. Coursera-PY4E-Python-Data-Structures/Assignment-10.2 at master ...

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  3. Python Data Structures Assignment 10.2 Solution [Coursera ...

    Python Data Structures Assignment 10.2 Solution [Coursera] | Assignment 10.2 Python Data StructuresCoursera: Programming For Everybody Assignment 10.2 progra...

  4. python-for-everybody/wk 10

    wk 10 - assignment 10.2.py. Cannot retrieve latest commit at this time. __author__ = 'edwardlau' """ 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 ...

  5. Python-For-Everybody--Python-Data-Structures-Certification/Assignment

    All of the projects that were completed in order to receive the Python For Everybody (Python Data Structures) certification from Coursera. The certification can be viewed below in the README. - Pyt...

  6. Coursera :Python Data Structures Assignment 10.2 Graded

    In This Video I Show you Coursera :Python Data Structures Assignment 10 2 GradedSubscribe to channel :Learn with KritarthNext Channel :Kritarth Editz-----...

  7. Programming for Everybody: Assignment 10.2 Tuples and Sorting

    ###Python Data Structures. 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. From [email protected] Sat Jan 5 09:14:16 2008

  8. Python For Everybody Assignment 10.2

    Code link: https://drive.google.com/file/d/1sdKGvWnmPnmu1AixTyvU06OFvJ12e4cg/view?usp=sharingCoursera: Python For Everybody Assignment 10.2 program solution ...

  9. Python Data Structures Course by University of Michigan

    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 ...

  10. GitHub: Let's build from here · GitHub

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"Coursera/Python Data Structures":{"items":[{"name":"Coursera (Python Data Structures-[Assignment 10.2] ) .py ...

  11. 5. Data Structures

    Data Structures — Python 3.12.3 documentation. 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:

  12. Coursera :10.2 Assignment solution/ Python data structures10.2

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

  13. Problem Solving with Algorithms and Data Structures using Python

    Problem Solving with Algorithms and Data Structures using Python¶. By Brad Miller and David Ranum, Luther College. Assignments; There is a wonderful collection of YouTube videos recorded by Gerry Jenkins to support all of the chapters in this text.

  14. Python data structures: Assignment 10.2

    Coursera: Python data structures Assignment 10.2 Week 6 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.

  15. 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 ...

  16. {"payload":{"allShortcutsEnabled":false,"fileTree":{"Coursera/Python

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"Coursera/Python Data Structures":{"items":[{"name":"Assignment 10.2.py","path":"Coursera/Python Data Structures ...

  17. Assignment 10.2 Python Data Structures

    Hello EveryOne. Welcome to #mythoughts...-----Thanks for watching!!-----PythonData Structures Assignment10...

  18. Data Structures and Algorithms in Python

    Data Structures and Algorithms in Python. 89.9k. 6. 4. This course is a beginner-friendly introduction to common data structures (linked lists, stacks, queues, graphs) and algorithms (search, sorting, recursion, dynamic programming) in Python. This course will help you ace coding assessments and technical interviews.

  19. N. Lokesh Reddy

    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.

  20. coursera-python-for-everybody-specialization/Course_2_Python_Data

    Current repository contains all assignments, notes, quizzes and course materials from the "Python for Everybody Specialization" provided by Coursera and University of Michigan. - sersavn/...

  21. Python Data Structure| Assignment 10.2 solution

    #Python#python data structure#a popular course on Coursera taught by Michigan State University, USA#Python#Pythondatastructure#Assignment_10.2#solution#Cours...

  22. GitHub

    Coursera---Python-Data-Structure-Answers. this contains all the answers to the quizes and asssignments for "Programming for Everybody (Python- Data Structures)" on Coursera by the University of Michigan.

  23. PYTHON DATA STRUCTURE (ASSIGNMENT-10.2)

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