COMP9021 Principles of Programming Lab5

1. Most popular name

As in the fifth lecture, we use the data of the National Data on the relative frequency of given names in the population of U.S. births, stored in a subdirectory named names of the working directory, in files named yobxxxx.txt with xxxx (the year of birth) ranging from 1880 to 2013. Write a program most_popular_name.py that prompts the user for a first name, and finds out the first year when this name was most popular in terms of frequency of names being given, as a female name and as a male name.
本題分析Eric的解法姿染,他的單次運行效率較高叠必,程序相對簡單谢谦。相比之下醉蚁,我自己的寫法單次效率低,適合做大量查詢员舵。主要思路區(qū)別是我的寫法將所有文件遍歷后輸出一個龐大的字典棒仍,包括了年份、性別抡蛙、名字护昧、計數(shù)、頻率信息溜畅,程序復(fù)雜捏卓,單次運行效率低,勝在字典建立后多次查詢速度快慈格。

import os 
first_name = input('Enter a first name: ')
min_male_frequency, min_female_frequency = 0, 0
male_first_year, female_first_year = None, None
tallies = {'F': {}, 'M': {}}
records = {'F': {}, 'M': {}}
#字典的嵌套怠晴,第一個字典實現(xiàn)性別分類,第二個字典分別實現(xiàn)題目要求

for filename in os.listdir('names'):
    if not filename.endswith('.txt'):
        continue
    year = int(filename[3:7])
    with open('names' + '/' + filename) as name:
        for gender in {'F', 'M'}:
            tallies[gender][year] = 0   
        for line in name:
            name, gender, count = line.split(',')
            count = int(count)
            tallies[gender][year] += count
            if name == first_name:
                records[gender][year] = count
    #遍歷了所有文件浴捆,獲得了所有年份的總計數(shù)tallies蒜田,{'F': {1880: XXX, 1881:XXX...}, 'M': {1880:XXX...}}
    #獲得了所有年份要查詢名字的records,{'F': {1880: XXX, 1881:XXX...}, 'M': {1880:XXX...}}

frequencies = dict.fromkeys(('M', 'F'))
#以M和F作為key选泻,創(chuàng)建新的字典冲粤,{'F': None, 'M': None}
for gender in {'F','M'}:
    frequencies[gender] = [(records[gender][year] * 100 / tallies[gender][year], year) for year in records[gender]]
    frequencies[gender].sort(reverse = True)
#生成frequencies的dict美莫,方法是逐年查詢records和tallies字典,例如1880年梯捕,records中查到那一年該名字的計數(shù)records[gender][year]
#tallies中查到那一年所有名字的總計數(shù)厢呵,相除取百分比得到frequencies的數(shù)據(jù)。并由大到小排序傀顾。
#{'F':[(XX.XX, 1880), (XX.XX, 1881)...], 'M':[(XX.XX, 1880), (XX.XX, 1881)...]}
if frequencies['F']:
    min_female_frequency, female_first_year = frequencies['F'][0][0], frequencies['F'][0][1]
if frequencies['M']:
    min_male_frequency, male_first_year = frequencies['M'][0][0], frequencies['M'][0][1]
if not female_first_year:
    print(f'In all years, {first_name} was never given as a female name.')
else:
    print(f'In terms of frequency, {first_name} was the most popular as a female name '
                                                         f'first in the year {female_first_year}.\n'
                            f'It then accounted for {min_female_frequency:.2f}% of all female names'
         )
if not male_first_year:
    print(f'In all years, {first_name} was never given as a male name.')
else:
    print(f'In terms of frequency, {first_name} was the most popular as a male name'
                                                           f'first in the year {male_first_year}.\n'
                                f'It then accounted for {min_male_frequency:.2f}% of all male names'
         )

2. The 9 puzzle

Dispatch the integers from 0 to 8, with 0 possibly changed to None, as a list of 3 lists of size 3, to represent a 9 puzzle. For instance, let
[[4, 0, 8], [1, 3, 7], [5, 2, 6]]
OR
[[4, None ,8], [1, 3, 7], [5, 2, 6]]
represent the 9 puzzle

4   8
1 3 7
5 2 6

with the 8 integers being printed on 8 tiles that are placed in a frame with one location being tile free. The aim is to slide tiles horizontally or vertically so as to eventually reach the configuration

1 2 3
4 5 6
7 8

It can be shown that the puzzle is solvable iff the permutation of the integers 1, . . . , 8, determined by reading those integers off the puzzle from top to bottom and from left to right, is even. This is clearly a necessary condition since:
--sliding a tile horizontally does not change the number of inversions;
--sliding a tile vertically changes the number of inversions by -2, 0 or 2;
--the parity of the identity is even.
Write a program nine_puzzle.py with a function:
--validate_9_puzzle(grid) that prints out whether or not grid is a valid representation of a solvable 9 puzzle

def test(grid):
    if len(grid) != 3:
        return
    test = []
    for row in grid:
        for column in row:
            test.append(column)
    #把所有g(shù)rid里面的element放在一個list中
    if None in test:
        test[test.index(None)] = 0
    #如果有None例书,改成0
    if sorted(test) != list(range(9)):
        return
    #如果不是1-8的數(shù)字和0/None構(gòu)成拣度,則不成立潮罪。這里不要用.sort()谅猾,那樣會改變原來的grid順序
    permutation = 0
    for i in range(8):
        for j in range(i + 1, 9):
            if test[i] and test[j] and test[i] > test[j]:
                permutation += 1
    #判斷從前向后所有非零數(shù)字(0在題中代表可以和任何相鄰數(shù)字互換位置),如果前面的數(shù)字比后面的大嫉拐,則記錄加1
    if permutation % 2:
        return 
    else:
        return grid

def validate_9_puzzle(grid):
    if test(grid):
        print('This is a valid 9 puzzle, and it is solvable')
    else:
        print('This is an invalid or unsolvable 9 puzzle')
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末哩都,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子婉徘,更是在濱河造成了極大的恐慌漠嵌,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,214評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件判哥,死亡現(xiàn)場離奇詭異献雅,居然都是意外死亡,警方通過查閱死者的電腦和手機塌计,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評論 2 382
  • 文/潘曉璐 我一進店門挺身,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人锌仅,你說我怎么就攤上這事章钾。” “怎么了热芹?”我有些...
    開封第一講書人閱讀 152,543評論 0 341
  • 文/不壞的土叔 我叫張陵贱傀,是天一觀的道長。 經(jīng)常有香客問我伊脓,道長府寒,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,221評論 1 279
  • 正文 為了忘掉前任报腔,我火速辦了婚禮株搔,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘纯蛾。我一直安慰自己纤房,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 64,224評論 5 371
  • 文/花漫 我一把揭開白布翻诉。 她就那樣靜靜地躺著炮姨,像睡著了一般捌刮。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上舒岸,一...
    開封第一講書人閱讀 49,007評論 1 284
  • 那天绅作,我揣著相機與錄音,去河邊找鬼蛾派。 笑死棚蓄,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的碍脏。 我是一名探鬼主播,決...
    沈念sama閱讀 38,313評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼稍算,長吁一口氣:“原來是場噩夢啊……” “哼典尾!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起糊探,我...
    開封第一講書人閱讀 36,956評論 0 259
  • 序言:老撾萬榮一對情侶失蹤钾埂,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后科平,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體褥紫,經(jīng)...
    沈念sama閱讀 43,441評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,925評論 2 323
  • 正文 我和宋清朗相戀三年瞪慧,在試婚紗的時候發(fā)現(xiàn)自己被綠了髓考。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,018評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡弃酌,死狀恐怖氨菇,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情妓湘,我是刑警寧澤查蓉,帶...
    沈念sama閱讀 33,685評論 4 322
  • 正文 年R本政府宣布,位于F島的核電站榜贴,受9級特大地震影響豌研,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜唬党,卻給世界環(huán)境...
    茶點故事閱讀 39,234評論 3 307
  • 文/蒙蒙 一鹃共、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧初嘹,春花似錦及汉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽房铭。三九已至,卻和暖如春温眉,著一層夾襖步出監(jiān)牢的瞬間缸匪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評論 1 261
  • 我被黑心中介騙來泰國打工类溢, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留凌蔬,地道東北人。 一個月前我還...
    沈念sama閱讀 45,467評論 2 352
  • 正文 我出身青樓闯冷,卻偏偏與公主長得像砂心,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子蛇耀,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,762評論 2 345

推薦閱讀更多精彩內(nèi)容