zoukankan      html  css  js  c++  java
  • python3面试题 按规律写出下一个数1,11,21,1211,111221

    观察下面数字的规律

    1

    11

    21

    1211

    111221

    第一项是数字1

    描述前一项,这数是1,即“1个1”,记作“11”

    描述前一项,这数是11,即“2个1”,记作“21”

    描述前一项,这数是21,即“1个2,1个1”,记作“1211”

    描述前一项,这数是1211,即“1个1,1个2,2个1”,记作“111221”

    用Python实现前N(N=10)个

    方式1:从高位起,先统计某一个数字的次数

        再循环5次,即实现前10;

    a=[1,11,21,1211,111221]
    for i in range(5):
    n = str(a[-1]) #取列表中的最后一个数字,并转换为字符串;
    cn=len(n) #长度
    # print(n)
    nstr=''
    count=1
    for j in range(cn-1):
    # print(n[j])
    if n[j]==n[j+1]: #比较相邻的两数,相等
    count+=1
    if j==cn-2:
    nstr+=str(count)+str(n[j+1])
    # print(count)
    else: #不相等,则下入新的字符串中
    nstr+=str(count)+str(n[j])
    if j==cn-2:
    nstr += str(1) + str(n[j+1])
    count=1
    a.append(int(nstr)) #列表追加为整数
    # print(nstr)
    print(a)

     运行结果

    [1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

    方式2:将相同数字的分为一组;如,a='111221', ['111','22','1']

    a=[1,11,21,1211,111221]
    for m in range(5):
        b=str(a[-1])
        newl=[]
        zstr=""
        newstr=""
        for i in b:
            if len(zstr)==0:
                zstr=i
            else:
                if i==zstr[0]:
                    zstr+=i
                else:
                    newl.append(zstr)
                    zstr=i
        newl.append(zstr)
        # print(zstr)
        # print(newl)
        for i in newl:
            newstr+="{}{}".format(len(i),i[0])
        a.append(newstr)
    print(a)

    运行结果

    [1, 11, 21, 1211, 111221, '312211', '13112221', '1113213211', '31131211131221', '13211311123113112211']
    越努力,越幸运!!! good good study,day day up!!!
  • 相关阅读:
    数据库中表的主键的定义
    软件的三大类型
    常用逻辑公式
    软件开发中常用英文含义
    2017.11.27T19_8zuoye
    2017.11.29T19_B1_9zuoye chihuolianmeng
    2017.12.1T19_B2_1zuoye
    2017.12.6T19_B2_3.4
    2017.12.1T19_B2_2zuoye
    2017.12.6T19_B2_3.2 zuoye
  • 原文地址:https://www.cnblogs.com/canglongdao/p/14879325.html
Copyright © 2011-2022 走看看