python基本程序练习

时间:2017-08-13 20:47:21

标签: python list

我正在做一个缺乏训练的课程,我陷入了一次练习。我已经改变了我的代码一千次,但我认为我甚至不接近正确的答案。练习是这样的: 定义一个从1-9和1开始接收一串数字的过程 输出包含以下参数的列表: 字符串中的每个数字都应插入列表中。 如果字符串中的数字x小于或等于 在前面的数字y中,应插入数字x 进入子列表。继续添加以下数字到 子列表直到达到数字z 大于y。 然后将此数字z添加到正常列表并继续。所以如果字符串是'543987',那么输出应该是[5,[4,3],9,[8,7]]。

我的代码是:

string = '543987'

def numbers_in_lists(string):
    result = []
    sublist = []
    counter = 0
    ref = 0
    for e in string:

      if e == string[0]:
        result.append(int(e))

      if int(e) < ref:
        sublist.append(int(e))

      else:
        result.append(sublist)
        sublist = []
        result.append(int(e))
        counter = counter + string.find(e)

      ref = int(string[counter])

    return result

print numbers_in_lists(string)
# [5, [], 5, [4, 3], 9]  which is not what i expected ([5,[4,3],9,[8,7]])

太糟糕了?希望可以有人帮帮我。 谢谢!

2 个答案:

答案 0 :(得分:1)

字符串

中的每个字母只有两个选项
<li ng-repeat="item  in List">
  <a href="" ng-click="clickit(item.name)">{{item.name}}</a>
</li>

然后在您返回结果之前结束时,您想要进行相同的检查

if int(letter) > last_letter:
    if sublist: # if we have any entries in our sublist 
       result.append(sublist) # append them before appending this letter
    sublist = [] # clear sublist
    result.append(int(letter)) # append our letter
else: # it must be lessthan or equal
    sublist.append(int(letter)) # so append to sublist
last_letter = int(letter) # update last_letter

答案 1 :(得分:0)

def numbers_in_lists(string):
    # YOUR CODE

    A = [] #create main list
    B = [] #create sublist
    length = len(string)
    i = 0
    biggest = 0 #initiate biggest number to compare with other number in the string
    while i < length:
        if int(string[i]) > biggest:
            biggest = int(string[i])
            A.append(biggest)
            B = [] #empty sublist to prepare for next round
        else: 
            if B not in A: #prevent adding another sublist B to A
                A.append(B)
            B.append(int(string[i]))

        i += 1    
    return A