Chapter 4 Pythonのコンテナ型の紹介

session04-01.py
[3, "cat", 6.5, 2]  # define an unnamed list
myList = [3, "cat", 6.5, 2]  # assign the list to a name
myList
session04-02.py
myList = [3, "cat", 6.5, 2]  # assign the list to a name
myList
myList[2]               # item2 using indexing
myList + ["read", 7]  # concatenate list with another list
myList*3  # repeat list 3 times
len(myList)  # number of items in list
len(myList*4)
myList[1:3]  # slice items 1 to 2
3 in myList  # test whether item is in list
"dog" in myList
"dog" not in myList
del myList[2]  # delete item 2
myList
session04-03.py
changeList = [1, 2, "buckle my shoe", 3, 4, "shut the door"]
changeList
changeList[2] = "the sky is blue"  # change item 2
changeList
[1, 2, 'the sky is blue', 3, 4, 'shut the door']

name = "Monte"
name[2] = "x"  # attempt to change character in a string
session04-04.py
myList = [1, 2, 3, 4]
myList
listOfMyList = [myList]*3  # [myList] is a list containing myList
listOfMyList
myList[2] = 45  # change one item in mylist
listOfMyList
[[1, 2, 3, 4], [1, 2, 45, 4], [1, 2, 45, 4]]
session04-05.py
range(10)  # range is a sequence
list(range(10))  # create a list from a range
list(range(10, 2, -2))
list("the quick fox")  # create a list from a string
session04-06.py
myList = list((1024, 3, True, 6.5))
myList
myList.append(False)  # add False to end of list
myList
myList.insert(2, 4.5)  # insert 4.5 at index 2
myList
myList.pop()  # remove and return last item
myList
myList.pop(3)
myList
myList.sort()  # sort the list
myList
myList.reverse()  # reverse the order od the list
myList
myList.count(6.5)  # count occurrences of 6.5
myList.index(4.5)  # return index of 4.5
myList.remove(6.5)  # delete 6.5
myList
myList.clear()  # delete all items
myList
session04-07.py
team = "Minnesota Vikings"
team.split()  # split using spaces or tabs
team.split('i')  # split using i as delimiter
team.split('nn')  # split using nn as delimiter
session04-08.py
earthquakes = [37, 32, 46, 28, 37, 41, 31]
max(earthquakes)
min(earthquakes)
max(earthquakes) - min(earthquakes)
max("house")  # max/min also on characters in strings
min("house")
listing04-01.py
def getRange(alist):
    return max(alist) - min(alist)
session04-09.py
getRange([2, 5])
earthquakes = [37, 32, 46, 28, 37, 41, 31]
getRange(earthquakes)
listing04-02.py
def getMax(aList):
    maxSoFar = aList[0]
    for pos in range(1, len(aList)):
        if aList[pos] > maxSoFar:
            maxSoFar = aList[pos]

    return maxSoFar
listing04-03.py
def mean(aList):
    mean = sum(aList) / len(aList)
    return mean
listing04-04.py
def mean(aList):
    mean = sum(aList) / len(aList)
    return mean
session04-10.py
import statistics
earthquakes = [37, 32, 46, 28, 37, 41, 31]
mean(earthquakes)  # call our mean function
statistics.mean(earthquakes)  # call the statistics mean function
session04-11.py
aList = [24, 5, 8, 2, 9, 15, 10]  # odd number of items
aList.sort()
aList
len(aList)
len(aList) // 2  # find index of middle item
aList[3]  # 9 is median
bList = [2, 5, 8, 9, 10, 15, 24, 54]  # even number of sorted items
len(bList)
len(bList) // 2  # index of right middle item
bList[4]  # higher of two middle items
bList[3]  # lower of two middle items
mean([bList[4], bList[3]])  # median is the average
listing04-05.py
def median(aList):
    copyList = aList[:]  # make a copy using slice operator
    copyList.sort()  # sort the copy
    if len(copyList) % 2 == 0:  # even length
        rightMid = len(copyList) // 2
        leftMid = rightMid - 1
        median = (copyList[leftMid] + copyList[rightMid]) / 2
    else:  # odd length
        mid = len(copyList) // 2
        median = copyList[mid]
    return median
session04-12.py
import statistics
earthquakes7 = [37, 32, 46, 28, 37, 41, 31]  # 7items
median(earthquakes7)
earthquakes8 = [37, 32, 46, 28, 37, 41, 31, 29]  # 8items
median(earthquakes8)
statistics.median(earthquakes7)
statistics.median(earthquakes8)
session04-13.py
ages = {'David': 45, 'Brenda': 46}  # create dict with 2 pairs
ages
ages['David']  # given the key, access value
ages['Kelsey'] = 19  # add new pair
ages
ages['Hannah'] = 16  # add 2 new pairs
ages['Rylea'] = 7
ages
{'David': 45, 'Brenda': 46, 'Keysey': 19, 'Hannah': 16, 'Rylea': 7}
len(ages)  # len is number of pairs
ages['David'] = ages['David'] + 1  # change value using key
ages['David']
ages['Rylea'] = 8  # update value directly
ages
{'David': 46, 'Brenda': 46, 'Keysey': 19, 'Hannah': 16, 'Rylea': 8}
session04-14.py
ages = {'David': 45, 'Brenda': 46, 'Keysey': 19,
        'Hannah': 16, 'Rylea': 7}

ages
ages.keys()  # request keys
list(ages.keys())  # convert to list of keys
ages.values()  # request values
list(ages.values())  # convert to list of values
ages.items()  # request items
list(ages.items())  # returns list of tuples
ages.get('Lena', 'No age listed')  # get value with default
'Rylea' in ages  # key in dict?
del ages['David']  # delete item using key
ages
for name in ages.keys():  # iterate through keys
    print(name)

for name in ages:  # also iterate through keys
    print(name)

for age in ages.values():  # iterate through values
    print(age)

# python 3.8 later
for item in reversed(ages.items()):  # iterate items in reverse
    print(item)
# colab with python 3.7
# key_list = list(ages.keys())
# for k in reversed(key_list):  # iterate items in reverse
#    print(k, ages[k])
ages.clear()  # delete all items
ages

ages.clear()  # delete all items
ages
listing04-06.py
def mode(aList):
    countDict = {}

    for item in aList:
        if item in countDict:
            countDict[item] = countDict[item] + 1
        else:
            countDict[item] = 1
    # more code to come
listing04-07.py
def mode(aList):
    countDict = {}

    for item in aList:
        if item in countDict:
            countDict[item] = countDict[item] + 1
        else:
            countDict[item] = 1

    countList = countDict.values()
    maxCount = max(countList)

    modeList = []
    for item in countDict:
        if countDict[item] == maxCount:
            modeList.append(item)

        return modeList
session04-15.py
mode([1, 1, 4, 5, 6, 2, 4, 7, 1, 4, 6, 1])
mode([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6])
earthquakes = [37, 32, 46, 28, 37, 41, 31]
mode(earthquakes)

import statistics  # use multimode method in statistics module

def multimode(valList):
    freq = {}
    for v in valList:
        if v in freq:
            freq[v] += 1
        else:
            freq[v] = 1
    maxVal = max(freq.values())
    modes = []
    for k, v in freq.items():
        if v == maxVal:
            modes.append(k)
    return modes

# python 3.8
statistics.multimode([1, 1, 4, 5, 6, 2, 4, 7, 1, 4, 6, 1])
statistics.multimode([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6])
# python 3.7 for colab
# multimode([1, 1, 4, 5, 6, 2, 4, 7, 1, 4, 6, 1])
# multimode([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6])
listing04-08.py
def frequencyTable(aList):
    countDict = {}

    for item in aList:
        if item in countDict:
            countDict[item] = countDict[item] + 1
        else:
            countDict[item] = 1

    itemList = list(countDict.keys())
    itemList.sort()

    print("ITEM", "FREQUENCY")  # table headers

    for item in itemList:
        print(item, "      ", countDict[item])
session04-16.py
frequencyTable([3, 1, 1, 5, 3, 1, 2, 2, 3, 5, 3, 5, 4, 4, 6, 7, 6, 7, 5, 7, 8,
                3, 8, 2, 3, 4, 1, 5, 6, 7])
listing04-09.py
def frequencyTableAlt(aList):
    print("ITEM", "FREQUENCY")  # print table headers
    sortedList = aList[:]  # copy aList
    sortedList.sort()

    previous = sortedList[0]
    groupCount = 0
    for current in sortedList:
        if current == previous:  # same value as group
            groupCount = groupCount + 1
            previous = current
        else:  # new group detected
            print(previous, "    ", groupCount)
            previous = current
            groupCount = 1

    print(current, "     ", groupCount)  # print last group
listing04-10.py
# listing 4-10
import turtle


def frequencyChart(aList):

    countDict = {}  # generate dictionary of counts

    for item in aList:
        if item in countDict:
            countDict[item] = countDict[item] + 1
        else:
            countDict[item] = 1

    itemList = list(countDict.keys())  # get list of keys
    maxItem = len(itemList) - 1
    itemList.sort()

    countList = countDict.values()  # get list of counts
    maxCount = max(countList)

    wn = turtle.Screen()
    chartT = turtle.Turtle()
    wn.setworldcoordinates(-1, -1, maxItem + 1, maxCount + 1)
    chartT.hideturtle()  # do not display the turtle

    chartT.up()  # draw base line
    chartT.goto(0, 0)
    chartT.down()
    chartT.goto(maxItem, 0)
    chartT.up()

    chartT.goto(-1, 0)  # show min and max
    chartT.write("0", font=("Helvetica", 16, "bold"))
    chartT.goto(-1, maxCount)
    chartT.write(str(maxCount), font=("Helvetica", 16, "bold"))

    for index in range(len(itemList)):
        chartT.goto(index, -1)  # label item value
        chartT.write(str(itemList[index]), font=("Helvetica", 16, "bold"))

        chartT.goto(index, 0)  # draw lint to height of count
        chartT.down()
        chartT.goto(index, countDict[itemList[index]])
        chartT.up()
    wn.exitonclick()

frequencyChart([3, 3, 5, 7, 1, 2, 5, 2, 3, 4, 6, 3, 4, 6, 3, 4, 5, 6, 6])
listing04-1.11.py
import math


def standardDev(aList):
    theMean = mean(aList)

    total = 0
    for item in aList:
        difference = item - theMean  # subtract from mean
        diffSq = difference ** 2  # squere the difference
        total = total + diffSq  # add t running total

    sDev = math.sqrt(total / (len(aList) - 1))
    return sDev
session04-17.py
dataList = [7, 11, 9, 18, 15, 12]
mean(dataList)
standardDev(dataList)
dataList2 = [2, 10, 6, 24, 18, 12]
mean(dataList2)
standardDev(dataList2)
earthquakes = [37, 32, 46, 28, 37, 41, 31]
standardDev(earthquakes)

statistics.stdev(earthquakes)
statistics.stdev(earthquakes, statistics.mean(earthquakes))