today,we will study python's list / dictionary opt
dict detail informations's reference 5.Data Strunctures :https://docs.python.org/2.7/library/stdtypes.html#typesmapping
1.using list as stacks:==>>last-in, first-out”,we need used the collections.deque
stack = [1,2,3,4,5,6,7]
stack.append(8)
stack.append(9)
stack
Out[75]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
stack.pop()
Out[76]: 9
stack.pop()
Out[77]: 8
stack.pop()
Out[80]: 7
stack.pop()
Out[81]: 6
stack
Out[82]: [1, 2, 3, 4, 5]
2.using lists as queues:===>>first-in, first-out
stack
Out[83]: [1, 2, 3, 4, 5]
from collections import deque
stack.append(6)
stack
Out[86]: [1, 2, 3, 4, 5, 6]
stack = deque(stack)
stack.popleft()
Out[90]: 1
stack.popleft()
Out[91]: 2
stack
Out[92]: deque([3, 4, 5, 6])
3.coding informations:
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 26 12:36:37 2016
Using the while function to achieve the following functions
1.sum for 1..100
2.get all odd and even from 1..100
3.sum for 1-2+3-4..100
4.The 100 random integers were placed in the dictionary of dic key k1(values >50) and k2(values<50)
@author: trsenzhang
"""
import random
#sum(1..100)=5050
def getSum():
num = 0
result = 0
while num < 101:
result += num
num += 1
return result
#get 1…100 o
def getOddEven(type):
l1 = []
l2 = []
num = 1
while num < 101:
if (num % 2) == 0:
l1.append(num)
else:
l2.append(num)
num += 1
if type == '1':
return l2
elif type == '0':
return l1
else:
return '结果异常'
#sum 1-2+3-4+5-6….99
def getSum1():
num = 0
result = 0
flag = 1
while num < 101:
if (num % 2) == 0:
flag = -1
else:
flag = 1
result = result +num*flag
num += 1
return result
#produce 100 random integer
def ProduceRange():
l_num = []
for i in range(1,100):
num = random.randint(1,100)
l_num.append(num)
i += 1
return l_num
#if l_num > 50 : put l_num into the k1 for dict else put l_num into k2 for dict
def getDict():
l_num = ProduceRange()
print "the list' number is : %s " %l_num
dic = {}
print str.center('The Result',80,'#')
for i in l_num:
if i > 50:
try :
if dic.has_key('k1'):
dic[‘k1’].append(i,)
else:
dic[‘k1’] = [i,]
except:
return '%s values have problem' % i
else:
try :
if dic.has_key('k2'):
dic[‘k2’].append(i,)
else:
dic[‘k2’] = [i,]
except:
return '%s values have problem' % i
return dic
if __name__ == '__main__':
result = getSum()
print result
result1 = getOddEven('1')
print 'even is %s' % result1
result2 = getOddEven('0')
print 'odd is %s' % result2
result3 = getSum1()
print result3
result5 = getDict()
print result5