Data Processing and Visulisation with Python
Python Exercise 13
Multiplication
Write a Python function to multiply all the items in a list of numbers.
def multiplyItems(m):
mult = 1
for i in m :
mult = i * mult
return mult
multiplyItems([3.2, 7.1, 2.5, 4.3])
multiplyItems([1,2,3,4,5,6,7])
Removing Duplicates
Write a Python function to take a given list and return a new one without duplicates (keep original list unchanged).
Hint:
You do not have to work on the same list, i.e., you can create a new list and add nonduplicated item into it, then return the new one.
def removeDuplicates(m):
newList = []
for i in m:
if i not in newList:
newList.append(i)
return newList
removeDuplicates(['Tom', 'John', 'Victor', 'Jane', 'Tom', 'Mary', 'Jane', 'Tom'])
Common member
Write a Python function that takes two lists and returns True if they have at least one common member, otherwise False.
def haveCommonMember(m,n):
for i in m:
if i in n :
return True
else :
return False
haveCommonMember([2,5,7,8,9,5], [1,3,4,3,6,0,1])
haveCommonMember([4,6,7,8,4,7], [5,6,8,4,1,2])
Shuffle a list
Write a Python function to shuffle a given list.
def shuffleList(s):
import random as r
r.shuffle(s)
return s
A = [1,2,3,4,5,6,7,8,9]
shuffleList(A)
A
Permutation of list items
Write a Python function to generate and print all permutations of a list items (the list has no duplicate).
method 1
def listPermutation(m):
length = len(m)
for i in range(length):
a = m.pop(i)
for j in range(length):
new = m.insert(j,a)
return new
listPermutation([1,2,3])
listPermutation(['Tom', 'Mary', 'John', 'David'])
method 2
#Q5
import itertools
def listPermutation(alist):
li=list(itertools.permutations(alist))
for i in range(len(li)):
print(list(li[i]))
listPermutation([1,2,3])
method 3
#Q5
def permute(p,s):
if len(s):
for i,c in enumerate(s):
permute(p+[c],s[:i]+s[i+1:])
else:
print(p)
def listPermutation(l):
permute([],l)
listPermutation([1,2,3])
Chinese Zodiac (list version)
Write a Python function to return the sign of the Chinese Zodiac for a given year.
Zodiac Animal | Recent Years |
---|---|
Rat | 1924, 1936, 1948, 1960, 1972, 1984, 1996, 2008, 2020 |
Ox | 1925, 1937, 1949, 1961, 1973, 1985, 1997, 2009, 2021 |
Tiger | 1926, 1938, 1950, 1962, 1974, 1986, 1998, 2010, 2022 |
Rabbit | 1927, 1939, 1951, 1963, 1975, 1987, 1999, 2011, 2023 |
Dragon | 1928, 1940, 1952, 1964, 1976, 1988, 2000, 2012, 2024 |
Snake | 1929, 1941, 1953, 1965, 1977, 1989, 2001, 2013, 2025 |
Horse | 1930, 1942, 1954, 1966, 1978, 1990, 2002, 2014, 2026 |
Goat | 1931, 1943, 1955, 1967, 1979, 1991, 2003, 2015, 2027 |
Monkey | 1932, 1944, 1956, 1968, 1980, 1992, 2004, 2016, 2028 |
Rooster | 1933, 1945, 1957, 1969, 1981, 1993, 2005, 2017, 2029 |
Dog | 1934, 1946, 1958, 1970, 1982, 1994, 2006, 2018, 2030 |
Pig | 1935, 1947, 1959, 1971, 1983, 1995, 2007, 2019, 2031 |
def chineseZodia(m):
ChineseZodiac = ['Rat','Ox','Tiger','Rabbit','Dragon','Snake','Horse','Goat','Monkey','Rooster','Dog','Pig']
return ChineseZodiac[(m+8)%12]
chineseZodia(2019)
Astrological sign (list version)
Write a Python function to return astrological sign for given date of birth.
Note:
- Aries: March 21 - April 19
- Taurus: April 20 - May 20
- Gemini: May 21 - June 20
- Cancer: June 21 - July 22
- Leo: July 23 - August 22
- Virgo: August 23 - September 22
- Libra: September 23 - October 22
- Scorpio: October 23 - November 21
- Sagittarius: November 22 - December 21
- Capricorn: December 22 - January 19
- Aquarius: January 20 - February 18
- Pisces: February 19 - March 20
method 1
#Q7
def astrologicalSign(month,date):
months={"January":0,"February":1,"March":2,"April":3,"May":4,"June":5,"July":6,"August":7,"September":8,"October":9,"November":10,"December":11}
signs=["Aquarius","Pisces","Aries","Taurus","Gemini","Cancer","Leo","Virgo","Libra","Scorpio","Sagittarius","Capricorn"]
r=[20,19,21,20,21,21,23,23,23,23,22,22]
for key,value in months.items():
if key == month.title():
if date >= r[value]:
return signs[value]
else:
return signs[value-1]
astrologicalSign('February', 23)
method 2
#Q7
def astrologicalSign(month,day):
m1 = ['January','February','March','April','May','June','July','August','September','October','November','December']
m2 = ['Capricorn','Aquarius','Pisces','Aries','Taurus','Gemini','Cancer','Leo','Virgo','Libra','Scorpio','Sagittarius','Capricorn']
n = [19,20,21,22,23]
b = m1.index(month)
if month == 'February':
a = n[0]
if month == 'January' or month == 'April':
a = n[1]
if month == 'March' or month == 'May' or month == 'June':
a = n[2]
if month == 'November' or month == 'December':
a = n[3]
else:
a = n[4]
if day < a:
c = m2[b]
else:
c = m2[b+1]
return c
method 3
def astrologicalSign(m,d):
month = ["March","April","May","June","July","August","September","October","November","December","January","February"]
date = [21,20,21,21,23,23,23,23,22,22,20,19]
astro_sign = ["Aries","Taurus","Gemini","Cancer","Leo","Virgo","Libra","Scorpio","Sagittarius","Capricorn","Aguarius","Pisces"]
if d>= date[month.index(m)]:
return astro_sign[month.index(m)]
return astro_sign[(month.index(m)-1)%12]
Busy day
File ‘mbox.txt’ contains a lot of emails including message body and header. In each header, the first line starting with ‘From’ contains the date and time when the email was sent, as well as the day of week. Please write a Python program to scan the file and print out how many emails there are in this file and their distribution in days of week.
Hint:
Create a list [‘Sun’, ‘Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’], then search and sum up the frequencies for each one.
method 1
fs = open("mbox.txt","r")
n = 0
l1 = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
l2 = [0,0,0,0,0,0,0]
for line in fs:
line.strip()
if line[:5] == "From ":
n += 1
k = line.split()
v = l1.index(k[2])
l2[v] += 1
print("There are", n, "emails in the file.")
print("Their distribution in days of week:")
print("day", "amount", "percentage", sep="\t")
for i in range(7):
print(l1[i],l2[i],l2[i]/sum(l2)*100, sep="\t")
fs.close()
method 2
#8
with open('mbox.txt','r') as f:
week = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
count_dict = {}
for line in f:
if line.startswith('From '):
# print(line.split(' '))
target = line.split(' ')[2]
count_dict[target] = count_dict.get(target,0)+1
all_emails = sum(count_dict.values())
print(f'There are {all_emails} emails in the file.')
print('Their distribution in days of week:')
print('day amount percentage')
for i in week:
temp = count_dict[i]
print(i,temp,temp/all_emails*100,sep='\t')
method 3
# Q8
with open('mbox.txt') as f:
count=0
day=['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
amount=[0,0,0,0,0,0,0]
for i in f:
if i.startswith('From '): #注意From 后面要加一个空格
count+=1
for j in day:
if j in i:
amount[day.index(j)]+=1
print(f'There are {count} emails in the file.')
print('Their distribution in days of week:')
print('day','amount','percentage',sep='\t')
for i in range(7):
print(day[i],amount[i],100*amount[i]/count,sep='\t')