练习有一个小程序,计算一个字符串中每个字符出现的次数。
代码如下:
#统计一个字符串中每个字符出现的次数
messages = 'It was a bright cold day in Feb 23,and the clocks were striking twelve'
count = {}
for i in messages:
count.setdefault(i,0)
count[i] = count[i] + 1
print(count)
执行结果如下:
井字棋盘数据结构建模例子:
代码如下:
#井字棋盘,数据结构建模
chessboard = {'t-l':' ','t-c':' ','t-r':' ',
'c-l':' ','c-c':' ','c-r':' ',
'b-l':' ','b-c':' ','b-r':' '
}
def printboadr(board):
print(board['t-l']+'|'+board['t-c']+'|'+board['t-r'])
print('-*-*-')
print(board['c-l']+'|'+board['c-c']+'|'+board['c-r'])
print('-*-*-')
print(board['b-l']+'|'+board['b-c']+'|'+board['b-r'])
turn = 'X'
for i in range(9):
printboadr(chessboard)
print('please choose a place to fill it(for example:t-l)')
play = input()
chessboard[play] = turn
if turn == 'X':
turn = 'O'
else:
turn ='X'
printboadr(chessboard)
执行结果如下:
后边还会有各种小练习和项目练习。