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 structure: Assignment 8.4

python data structures assignment 8.4 answers

Post a Comment

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

Popular posts from this blog

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

Image

Python data structures Chapter 6 Quiz

Image

python data structures assignment 8.4 answers

assignment 8.4 python data structures

Code examples.

  • answer assignment 8.4 python data structures
  • related assignment 7.1 python data structures

More Related Answers

  • python data structures 9.4

Answers Matrix View Full Screen

python data structures assignment 8.4 answers

Closely Related Answers

Assignment 7.1 python data structures.

Comfortable Cod

Documentation

Twitter Logo

Oops, You will need to install Grepper and log-in to perform this action.

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 8 week 4 Assignment 8.4

python data structures assignment 8.4 answers

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

chapter 6 week 1 Assignment 6.5

Image

python data structures assignment 8.4 answers

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:

python data structures assignment 8.4 answers

  • Python »
  • 3.8.4 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.

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; this only matters for mutable objects like lists. 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

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

IMAGES

  1. Python Data Structures Assignment 8.4 Solution [Coursera]

    python data structures assignment 8.4 answers

  2. Python Data Structures Assignment 8.4 Solution [Coursera]

    python data structures assignment 8.4 answers

  3. NPTEL: Programming ,Data Structures and Algorithms Using Python Week 3

    python data structures assignment 8.4 answers

  4. Programming Data Structures And Algorithms Using Python Assignment 8

    python data structures assignment 8.4 answers

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

    python data structures assignment 8.4 answers

  6. Python for everybody: data structures assignment 8.4

    python data structures assignment 8.4 answers

VIDEO

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

  2. Assignment 9.4 Python Data Structures

  3. Assignment

  4. PYTHON DATA STRUCTURES Assignment 7.1 [coursera]

  5. 9618

  6. Python for Data Science Week 4: Assignment 4 Solutions || 2023

COMMENTS

  1. LearningPython/Coursera/Python Data Structures/Assignment 8.4 ...

    Saved searches Use saved searches to filter your results more quickly

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

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

  3. Assignment 8.4 Python data structures

    ...Welcome to #mythoughts----- PYTHON DATA STRUCTURES Assignment 8.4COURSERA : Python For Everybody Assignment 8.4

  4. Python Data Structures Assignment 8.4 Solution [Coursera ...

    Solution link 👇https://www.instamojo.com/rahuljodhpur/python-data-structures-assignment-84-program-0b9ff/Python Data Structures Assignment 8.4 Solution [Cou...

  5. Coursera---Python-Data-Structure-Answers/Assignment 8.4 ...

    Contribute to Ritik2703/Coursera---Python-Data-Structure-Answers development by creating an account on GitHub.

  6. Python data structure: Assignment 8.4

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

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

  8. {"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name":"README.md","path":"README.md","contentType":"file"},{"name":"Week 1 (Chapter 6) Quiz answers ...

  9. assignment 8.4 python data structures

    More Related Answers ; python data structures 9.4; assignment 8.4 python data structures Comment . 0. Popularity 1/10 Helpfulness 1/10 Language python. Source: Grepper. Tags: data-structures python. Share . Link to this answer Share Copy Link . Contributed on Apr 26 2022 ...

  10. Coursera: 8.4 Assignment// python data structures assignment 8.4

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

  11. chapter 8 week 4 Assignment 8.4

    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.

  12. Python Data Structure Exercise for Beginners

    This data structure exercise is for beginners to understand and practice basic data structure in Python. Practice Python List, Set, Dictionary, and Tuple questions. The data structure is widely used to hold any data. To perform any programming tasks in Python, good knowledge of data structure is a must. Solve this exercise to have a good ...

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

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

  15. Python for everybody: data structures assignment 8.4

    #pythodatastructuresweek4assigment8_4#pythonforeverybodyA program that opens a text file containing several lines of words, reads each line and separates eac...

  16. 5. Data Structures

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

  17. ex 9.4 python coursera

    Currently working on this for Coursera's Python For everybody class. This is ex 9.4. ... Just put data straight into a dict. The else statements were not needed. You want to keep checking if the new value is larger then the old value, and if so, then make it the new value. ... One more thing, the assignment says to find all lines with "From ...

  18. Python-For-Everybody-Answers/2-Python-Data-Structure/Assignment

    Contribute to Kalpesh14m/Python-For-Everybody-Answers development by creating an account on GitHub.

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

  20. Python Data Structures || Week 4

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

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

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

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"week8":{"items":[{"name":"Assignment 8.4.py","path":"week8/Assignment 8.4.py","contentType":"file"},{"name ...

  23. Coursera-PY4E-Python-Data-Structures/Assignment-9.4 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.