Design of Computer Programs L1

Paste_Image.png

第一講主要是做一個撲克牌游戲,主要是撲克牌規(guī)則的設(shè)計瘟忱。復(fù)用了max函數(shù)。涉及到了重構(gòu)和測試的概念,以及在程序編寫過程中需要注意Correctness充岛,effeciency, feature和elegance四方面。以下是較完整代碼:

import random


def poker(hands):
    """Return a list of winning hands: poker([hand,...]) => [hand,...]"""
    return allmax(hands, key=hand_rank)


def allmax(iterable, key=None):
    """Return a list of all items equal to the max of the iterable."""

    # maxv = hand_rank(max(iterable, key=key))
    # maxl = []
    # for item in iterable:
    #     if hand_rank(item) == maxv:
    #         maxl.append(item)
    # return maxl if len(maxl) > 0 else None

    result, maxval = [], None
    key = key or (lambda x: x)
    for x in iterable:
        xval = key(x)
        if not result or xval>maxval:
            result, maxval = [x], xval
        elif xval == maxval:
            result.append(x)
    return result

def hand_rank(hand):
    "Return a value indicating the ranking of a hand."
    ranks = card_ranks(hand)
    if straight(ranks) and flush(hand):
        return (8, max(ranks))
    elif kind(4, ranks):
        return (7, kind(4, ranks), kind(1, ranks))
    elif kind(3, ranks) and kind(2, ranks):
        return (6, kind(3, ranks), kind(2, ranks))
    elif flush(hand):
        return (5, ranks)
    elif straight(ranks):
        return (4, max(ranks))
    elif kind(3, ranks):
        return (3, kind(3, ranks), ranks)
    elif two_pair(ranks):
        return (2, two_pair(ranks), ranks)
    elif kind(2, ranks):
        return (1, kind(2, ranks), ranks)
    else:
        return (0, ranks)

def card_ranks(hand):
    "Return a list of the ranks, sorted with higher first."
    ranks = ['--23456789TJQKA'.index(r) for r, s in hand]
    ranks.sort(reverse = True)
    return [5, 4, 3, 2, 1] if (ranks == [14, 5, 4, 3, 2]) else ranks

def flush(hand):
    "Return True if all the cards have the same suit."
    suits = [s for r,s in hand]
    return len(set(suits)) == 1

def straight(ranks):
    "Return True if the ordered ranks form a 5-card straight."
    return (max(ranks)-min(ranks) == 4) and len(set(ranks)) == 5

def kind(n, ranks):
    """Return the first rank that this hand has exactly n-of-a-kind of.
    Return None if there is no n-of-a-kind in the hand."""
    for r in ranks:
        if ranks.count(r) == n: return r
    return None

def two_pair(ranks):
    "If there are two pair here, return the two ranks of the two pairs, else None."
    pair = kind(2, ranks)
    lowpair = kind(2, list(reversed(ranks)))
    if pair and lowpair != pair:
        return (pair, lowpair)
    else:
        return None

def test():
    "Test cases for the functions in poker program."
    sf1 = "6C 7C 8C 9C TC".split() # Straight Flush
    sf2 = "6D 7D 8D 9D TD".split() # Straight Flush
    fk = "9D 9H 9S 9C 7D".split() # Four of a Kind
    fh = "TD TC TH 7C 7D".split() # Full House
    assert poker([sf1, sf2, fk, fh]) == [sf1, sf2]
    # print(hand_rank(max([sf1, sf2], key=hand_rank)))
    print('tests pass')


mydeck = [r+s for r in '23456789TJQKA' for s in 'SHDC']

def deal(numhands, n=5, deck=mydeck):
    """發(fā)牌"""
    # hands = []
    # for handindex in range(numhands):
    #     hand = []
    #     for i in range(n):
    #         temp = random.choice(deck)
    #         hand.append(temp)
    #         deck.remove(temp)
    #     hands.append(hand)
    # return hands
    random.shuffle(deck)
    return [deck[n*i:n*(i+1)] for i in range(numhands)]

Knuth's Algorithm P.

import random


def shuffle(deck):
    """Knuth's Algorithm P."""
    n = len(deck)
    for i in range(n-1):
        swap(deck, i, random.randrange(i, n))


def swap(deck, i, j):
    """Swap elements i and j of a collection"""
    deck[i], deck[j] = deck[j], deck[i]

此部分在最后講了純函數(shù)的概念耕蝉,純函數(shù)是做計算(computing)的函數(shù)崔梗,返回計算結(jié)果,便于測試垒在。而另一類函數(shù)是Doing類蒜魄,表示一些過程指令,無返回值,所以難于測試谈为。(是不是類似函數(shù)式編程中的純函數(shù)旅挤?)

HW1

HW1

HW2

HW2
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市伞鲫,隨后出現(xiàn)的幾起案子粘茄,更是在濱河造成了極大的恐慌,老刑警劉巖秕脓,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件柒瓣,死亡現(xiàn)場離奇詭異,居然都是意外死亡撒会,警方通過查閱死者的電腦和手機嘹朗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來诵肛,“玉大人屹培,你說我怎么就攤上這事≌荩” “怎么了褪秀?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長薛训。 經(jīng)常有香客問我媒吗,道長,這世上最難降的妖魔是什么乙埃? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任闸英,我火速辦了婚禮,結(jié)果婚禮上介袜,老公的妹妹穿的比我還像新娘甫何。我一直安慰自己,他們只是感情好遇伞,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布辙喂。 她就那樣靜靜地躺著,像睡著了一般鸠珠。 火紅的嫁衣襯著肌膚如雪巍耗。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天渐排,我揣著相機與錄音炬太,去河邊找鬼。 笑死驯耻,一個胖子當著我的面吹牛娄琉,可吹牛的內(nèi)容都是我干的次乓。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼孽水,長吁一口氣:“原來是場噩夢啊……” “哼票腰!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起女气,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤杏慰,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后炼鞠,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缘滥,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年谒主,在試婚紗的時候發(fā)現(xiàn)自己被綠了朝扼。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡霎肯,死狀恐怖擎颖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情观游,我是刑警寧澤搂捧,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站懂缕,受9級特大地震影響允跑,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜搪柑,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一聋丝、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧工碾,春花似錦潮针、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽瓣戚。三九已至端圈,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間子库,已是汗流浹背舱权。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留仑嗅,地道東北人宴倍。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓张症,卻偏偏與公主長得像,于是被迫代替她去往敵國和親鸵贬。 傳聞我的和親對象是個殘疾皇子俗他,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355

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