青少年python编程竞赛答案(青少年python比赛)
python 编程 求答案!2、3两题
#!/usr/bin/env?python
#coding=utf-8
import?re
from?datetime?import?datetime?as?dt,?timedelta
import?platform
if?platform.python_version()[:1]?==?'2':?#判断python版本是2还是3
????import?sys
????reload(sys)
????sys.setdefaultencoding('utf8')
class?Idcard(object):
????'''?
?????m?=?Idcard('225122198611134730')
?????print(m.sex)
????男
?????m.birth
????'1986-11-13'
?????m.age
????30
????'''
????def?__init__(self,idcard):
????????self.idcard?=?idcard????????
????????if?len(idcard)?==?15:
????????????sex,?birth?=?idcard[-1:],?'19'?+?idcard[6:12]
????????elif?len(idcard)?==?18:
????????????sex,?birth?=?idcard[-2:-1],?idcard[6:14]???
????????else:
????????????raise?Exception('len(idcard)?is?{}?(15/18)'.format(len(idcard)))
????????self._sex?=?int(sex)?%?2
????????self._birth?=?birth
????
????@property
????def?sex(self):
????????return?u'男'?if?self._sex?%?2?else?u'女'
????@property
????def?age(self):??
????????now,?bir?=?dt.now(),?dt.strptime(self._birth,?'%Y%m%d')
????????beforebirth?=?(now?-?dt(now.year,?bir.month,?bir.day)).days??0
????????return?dt.now().year?-?int(self._birth[:4])?-?beforebirth
????@property
????def?birth(self):
????????return?dt.strptime(self._birth,?'%Y%m%d').strftime('%Y-%m-%d')
def?alignment(str1,?space,?align?=?'left'):
????length?=?len(str1.encode('gb2312'))
????space?=?space?-?length?if?space?=length?else?0
????if?align?==?'left':
????????str1?=?str1?+?'?'?*?space
????elif?align?==?'right':
????????str1?=?'?'*?space?+str1
????elif?align?==?'center':
????????str1?=?'?'?*?(space?//2)?+str1?+?'?'*?(space?-?space?//?2)
????return?str1
????
def?main():
????fname?=?'customer.txt'
????'''
????with?open(fname,?'w')?as?f:
????????f.write("""
????????郑文杰?225122198611134730
????????文萍?225122198912094740
????????郑妈妈??225122590303476
????????郑爸爸?225122560506471
????????""")
????'''????
????newf?=?'ourcustomers.txt'
????with?open(fname)?as?f:
????????s?=?f.readlines()
????L,?newL?=?[re.split(r'\s+',?i.strip())?for?i?in?s],?[]
????for?i?in?L:
????????if?len(i)?==?2:
????????????g?=?Idcard(i[1])
????????????newL.append('{}{}{}'.format(
????????????????alignment(i[0],?10),?alignment(g.sex,?8),?g.age))
????with?open(newf,?'w')?as?f:
????????f.write('\n'.join(newL))
????print('\n'.join(newL[:100]))
????print('Customer?data?has?been?write?into?{}'.format(newf))
if?__name__?==?'__main__':
????import?doctest
????doctest.testmod()
????main()
Python编程题求助
该答案为组合数学中著名的卡特兰数,其通式为C(2n,n)-C(2n,n-1)
这里采用递推关系求解,即动态规划的方法
设n对父子有d[n]种出场策略,注意初值d[0]=1
因为每个孩子前面必有一个父亲与之对应
对于i对父子,遍历第j个孩子,该孩子前面有j-1个孩子,对应d[j-1]种出场策略
后面有i-j个孩子,对应d[i-j]种出场策略,则d[i]+=d[j-1]*d[i-j],最终d[n]即为所求
python代码如下:
n = int(input())
d = [0] * (n+1)
d[0] = 1
for i in range(n+1):
? for j in range(i+1):
? ? ? d[i] += d[j-1] * d[i-j]
print(d[n])
运行结果如下:
望采纳~
蓝桥杯python青少年组初赛对几题可以通过
如果通过初赛的话,大约答对八道题就可以了,在青少年组初赛的时候,但是这个答案是不准确的,如果想知道你具体参加了,看之后就知道了,希望我的回答对你有帮助,谢谢