Python Data Structures Assignment答案

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

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.

text = "X-DSPAM-Confidence:    0.8475"
p1 = text.find('0')
p2 = text.find('5')
num = text[p1: p2+1]
n = float(num)
print(n)

Desired Output

0.8475

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.

You can download the sample data at http://www.py4e.com/code3/words.txthttps://www.py4e.com/code3/words.txt

# Use words.txt as the file name
fname = input('Enter the name:')
fh = open(fname)
iny = fh.read()
iny= iny.rstrip()
print(iny.upper())

Desired Output

WRITING PROGRAMS OR PROGRAMMING IS A VERY CREATIVE
AND REWARDING ACTIVITY  YOU CAN WRITE PROGRAMS FOR
MANY REASONS RANGING FROM MAKING YOUR LIVING TO SOLVING
A DIFFICULT DATA ANALYSIS PROBLEM TO HAVING FUN TO HELPING
SOMEONE ELSE SOLVE A PROBLEM  THIS BOOK ASSUMES THAT
{\EM EVERYONE} NEEDS TO KNOW HOW TO PROGRAM AND THAT ONCE
YOU KNOW HOW TO PROGRAM, YOU WILL FIGURE OUT WHAT YOU WANT
TO DO WITH YOUR NEWFOUND SKILLS

WE ARE SURROUNDED IN OUR DAILY LIVES WITH COMPUTERS RANGING
FROM LAPTOPS TO CELL PHONES  WE CAN THINK OF THESE COMPUTERS
AS OUR PERSONAL ASSISTANTS WHO CAN TAKE CARE OF MANY THINGS
ON OUR BEHALF  THE HARDWARE IN OUR CURRENT-DAY COMPUTERS
IS ESSENTIALLY BUILT TO CONTINUOUSLY AS US THE QUESTION
WHAT WOULD YOU LIKE ME TO DO NEXT

OUR COMPUTERS ARE FAST AND HAVE VASTS AMOUNTS OF MEMORY AND
COULD BE VERY HELPFUL TO US IF WE ONLY KNEW THE LANGUAGE TO
SPEAK TO EXPLAIN TO THE COMPUTER WHAT WE WOULD LIKE IT TO
DO NEXT IF WE KNEW THIS LANGUAGE WE COULD TELL THE
COMPUTER TO DO TASKS ON OUR BEHALF THAT WERE REPTITIVE
INTERESTINGLY, THE KINDS OF THINGS COMPUTERS CAN DO BEST
ARE OFTEN THE KINDS OF THINGS THAT WE HUMANS FIND BORING
AND MIND-NUMBING


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.

You can download the sample data at http://www.py4e.com/code3/mbox-short.txthttps://www.py4e.com/code3/mbox-short.txt?PHPSESSID=01888bb1a18690edaeded43edd9110ad when you are testing below enter mbox-short.txt as the file name. 

# Use the file name mbox-short.txt as the file name
fname = input('Enter file name:')
fh = open(fname)
s = 0
n = 0
for line in fh :
    if not line.startswith('X-DSPAM-Confidence:'):
        continue
    p = line.find('0')
    str1 = line[p:]
    num = float(str1)
    s += num
    n += 1
aver = s / n
print("Average spam confidence:", aver)

Desired Output

Average spam confidence: 0.7507185185185187

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 python sort() order as shown in the desired output.

You can download the sample data at http://www.py4e.com/code3/romeo.txthttps://www.py4e.com/code3/romeo.txt?PHPSESSID=4f9bfb0979a24fb3ccdb7fa64419d841

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh :
	listofword = line.split()
	for word in listofword :
		if word not in lst :
			lst.append(word)
lst.sort()
print(lst)

Desired Output

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

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 stephen.marquard@uct.ac.za 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:'. Also look at the last line of the sample output to see how to print the count.

You can download the sample data at http://www.py4e.com/code3/mbox-short.txthttps://www.py4e.com/code3/mbox-short.txt?PHPSESSID=b4616915ad2cb387edf54c15ddfcf06c

fname = input('Enter file name : ')
if len(fname) < 1 :
    fname = "mbox-short.txt"
fh = open(fname)
count = 0
for line in fh :
    if line.startswith('From ') :
        piece = line.split()
        email = piece[1]
        print(email)
        count += 1
    else :
        pass
print("There were", count, "lines in the file with From as the first word")

Desired Output

stephen.marquard@uct.ac.za
louis@media.berkeley.edu
zqian@umich.edu
rjlowe@iupui.edu
zqian@umich.edu
rjlowe@iupui.edu
cwen@iupui.edu
cwen@iupui.edu
gsilver@umich.edu
gsilver@umich.edu
zqian@umich.edu
gsilver@umich.edu
wagnermr@iupui.edu
zqian@umich.edu
antranig@caret.cam.ac.uk
gopal.ramasammycook@gmail.com
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
stephen.marquard@uct.ac.za
louis@media.berkeley.edu
louis@media.berkeley.edu
ray@media.berkeley.edu
cwen@iupui.edu
cwen@iupui.edu
cwen@iupui.edu
There were 27 lines in the file with From as the first word


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. 

 Hint: make sure not to include the lines that start with 'From:'. Also look at the last line of the sample output to see how to print the count.

You can download the sample data at http://www.py4e.com/code3/mbox-short.txthttps://www.py4e.com/code3/mbox-short.txt?PHPSESSID=b4616915ad2cb387edf54c15ddfcf06c

fname = input('Enter file name : ')
if len(fname) < 1 :
    fname = "mbox-short.txt"
fh = open(fname)

count = dict()
for line in fh :
    if line.startswith('From ') :
        words = line.split()
        email = words[1]
        count[email] = count.get(email, 0) + 1

maxcount = None
maxname = None
for k, v in count.items() :
    if maxcount == None or v > maxcount :
        maxcount = v
        maxname = k
print(maxname, maxcount)

 Desired Output

cwen@iupui.edu 5

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 stephen.marquard@uct.ac.za 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. 

 Hint: make sure not to include the lines that start with 'From:'. Also look at the last line of the sample output to see how to print the count.

You can download the sample data at http://www.py4e.com/code3/mbox-short.txthttps://www.py4e.com/code3/mbox-short.txt?PHPSESSID=b4616915ad2cb387edf54c15ddfcf06c

name = input('Enter file: ')
if len(name) < 1 :
    name = 'mbox-short.txt'
hand = open(name)

dic = {}
for line1 in hand :
    if line1.startswith('From ') :
        words1 = line1.split()
        time = words1[5]
        words2 = time.split(':')
        hour = words2[0]
        dic[hour] = dic.get(hour, 0) + 1

for k, v in sorted(dic.items(), reverse=False) :
    print(k, v)

Desired Output

04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Python数据结构是指在Python编程语言中可用的数据类型和数据结构,包括列表、元组、字典、集合等。这些数据结构可以用于存储和操作数据,使得Python编程更加高效和灵活。Python的数据结构具有易于使用、灵活性强、可扩展性好等特点,因此在数据分析、机器学习、人工智能等领域得到了广泛应用。 ### 回答2: Python数据结构是Python编程语言中的基本概念,指用于存储和组织数据的数据类型和数据结构。数据类型包括数字、字符串、布尔值、列表、元组、字典和集合等。数据结构是指相互之间存在一定关系的数据组成的组合,如栈、队列、链表、树、图等。 Python中最常用的数据结构有: 1. 列表(list):包含一组有序的元素,可以是任何数据类型,并且是可变的。 2. 元组(tuple):与列表类似,但是不可变,一旦创建就不能修改。 3. 字典(dictionary):使用键值对存储数据,键是可哈希的数据类型(即可通过哈希算法得到唯一标识符的数据类型),值可以是任何数据类型。 4. 集合(set):无序的不重复元素的集合。可以进行交、并、差等集合操作。 5. 栈(stack):先进后出的数据结构,可以用列表实现。 6. 队列(queue):先进先出的数据结构,可以用列表实现,也可以使用Python标准库中的队列模块(queue)或双端队列模块(collections.deque)。 7. 堆(heap):特殊的二叉树结构,最小堆和最大堆可以通过heapq库来实现。 8. 树(tree):节点之间存在父子关系,经常用于搜索和排序。Python没有内置树结构,但可以使用第三方库来实现。 Python数据结构非常灵活和易于使用,可以根据不同的需求选择不同的数据结构。掌握Python数据结构对于有效编程至关重要。 ### 回答3: Python 数据结构是指一组数据的组织方式,是一种管理和组织数据的方法。Python 中的数据结构可以按照不同的目的和需求进行分类,主要包括以下几种类型: 1. 列表(Lists):列表是 Python 中最常用的数据结构之一,它可以存储多个值,并允许对这些值进行操作和处理。列表中的元素可以是任何数据类型,包括数字、字符串、布尔值和其他列表等。 2. 元组(Tuples):元组类似于列表,但是它们是不可变的,一旦创建就不能修改其内容。元组通常用于存储不变的数据,如各种常量、元组等。 3. 字典(Dictionaries):字典是一种映射类型的数据结构,用于存储 key-value 对,其中 key 和 value 都可以是任何数据类型。字典的主要特点是可变性和无序性。 4. 集合(Sets):集合是一个无序的不重复元素序列,可以用于去重和求交集、并集、差集等集合运算。 5. 栈(Stacks):栈是一种后进先出(LIFO)的数据结构,常用于递归函数、表达式求值和历史记录中的后退操作。 6. 队列(Queues):队列是一种先进先出(FIFO)的数据结构,常用于处理排队等待的任务。 Python 数据结构的实现可以利用内置函数或第三方库,如 NumPy、Pandas、SciPy 等,这些库封装了很多高效的数据结构和算法,并提供了丰富的功能函数和方法,可以大大提高数据处理和分析的效率和准确性。对于 Python 开发者来说,了解和掌握不同类型的数据结构以及其使用方法,是编写高效、可靠和易于维护的程序的关键之一。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

*OASIS*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值