优达学城《计算机科学导论》 --列表中的数字

本文介绍了一个将特定格式的数字字符串转换为嵌套列表的算法。该算法遇到小于或等于前一数字的数时,会创建子列表来组织这些数字,直到遇到大于前一数字的数为止。文章详细阐述了实现这一功能的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# Numbers in lists by SeanMc from forums
# define a procedure that takes in a string of numbers from 1-9 and
# outputs a list with the following parameters:
# Every number in the string should be inserted into the list.
# If a number x in the string is less than or equal 
# to the preceding number y, the number x should be inserted 
# into a sublist. Continue adding the following numbers to the 
# sublist until reaching a number z that
# is greater than the number y. 
# Then add this number z to the normal list and continue.

#Hint - "int()" turns a string's element into a number

def numbers_in_lists(string):
    result=[]
    sublist=[]
    result.append(int(string[0]))
    j=0
    for i in range(len(string)-1):
        if j==len(string)-1:
            break
        elif i>=j-1:
            if int(string[i])>=int(string[i+1]):
               reference=int(string[i])
               for j in range(i + 1, len(string)):
                   if reference >= int(string[j]):
                      sublist.append(int(string[j]))
                   elif reference < int(string[j]):
                       break
               result.append(sublist)
               sublist = []
            elif int(string[i])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值