简体   繁体   中英

Python - Removing all numbers that are now smaller than the number behind them

I made a function for this in my functions file:

def removeNum(myList):
    listSize = len(myList) -1
    loop = 0
    while loop < listSize:
        if myList[loop] > myList[loop + 1]:
            myList.remove(myList[loop + 1])
            listSize = listSize - 1
        loop = loop + 1

    return myList

My main program looks like: ( I use the removeNum function i'm having issues with towards the bottom of the code. )

import functionsFile




finalDataList = []
openFinalData = open("FinalData.data")
for entry in openFinalData:
    entry = entry.strip()
    entry = int(entry)
    finalDataList.append(entry)


print("The file has been read")

listSum = 0
for numb in finalDataList:
    listSum = listSum + numb

listAvg = listSum / len(finalDataList)
listAvg = round(listAvg,2)

print("The sum of all the numbers:--> "+str(listSum))

print("The average of the numbers is:--> "+str(listAvg))



functionsFile.firstTen(finalDataList)
functionsFile.lastTen(finalDataList)

finalDataList.sort()
finalDataList.reverse()

print("After sorting the numbers")

functionsFile.firstTen(finalDataList)
functionsFile.lastTen(finalDataList)

oddNumList = []
for numb in finalDataList:
    oddNumList.append(functionsFile.makeOdd(numb))

finalDataList = oddNumList

newListSum = 0
for numb in finalDataList:
    newListSum = newListSum + numb

newListAvg = newListSum / len(finalDataList)
newlistAvg = round(newListAvg,2)


print("After replacing the list with all the answers,"
      +"here are the new totals")


print(" The new sum of all the numbers will be: "+str(newListSum))

print("The new average of all the numbers will be:"+str(newListAvg))

print(" ")

functionsFile.firstTen(finalDataList)
functionsFile.lastTen(finalDataList)

print(" ")
print(" ")


functionsFile.removeNum(finalDataList)


print(finalDataList)

openFinalData.close()

When I run the program it doesn't print out the new list that's been modified from the removeNum function above, is there something wrong with my function or in my main program? I'm not getting any errors. Any thoughts would be appreciated. Thank you.

One way to approach the problem is to zip the list with a copy of itself offset by 1 and then filter using a list comprehension as follows:

ls = [1, 3, 0, 7, 9, 4]
zipped = zip(ls, ls[0:1] + ls[:-1])
ls_filtered = [p[0] for p in zipped if p[0] >= p[1]]
# ls_filtered is now [1, 3, 7, 9]

your function is broken, look

>>> removeNum([9, 7, 4, 3, 1, 0])
[9, 4, 1]    

it skip number, the reason is simple

def removeNum(myList):
    listSize = len(myList) -1
    loop = 0
    while loop < listSize:
        if myList[loop] > myList[loop + 1]:
            myList.remove(myList[loop + 1])
            listSize = listSize - 1
        loop = loop + 1  #<-- here is the problem

    return myList

you advance loop regardless of the situation, when you should not do it when you remove a element, to fix this just do

def removeNum(myList):
    listSize = len(myList) -1
    loop = 0
    while loop < listSize:
        if myList[loop] > myList[loop + 1]:
            myList.pop(loop + 1) # as the position is know, use pop
            listSize = listSize - 1
        else: 
            loop = loop + 1

    return myList

now it produce the expected outcome

>>> removeNum([9, 7, 4, 3, 1, 0])
[9]
>>> 

I don't recommend modify the list in place, but rather make a new one with the result like for example

def make_always_growing(iterable):
    current_max = None
    result = []
    for x in iterable:
        if current_max is None or x > current_max:
            current_max = x
            result.append(x)
    return result

the advantage of this is that don't depend in iterable being a list, which make it more generic and allow it to work with tuple, generator, and anything else


also some line of your cade are unneeded like

listSum = 0
for numb in finalDataList:
    listSum = listSum + numb

you can use the build-in sum for this

listSum = sum(finalDataList)

or

functionsFile.firstTen(finalDataList)
functionsFile.lastTen(finalDataList)

if they do what it name suggest, then you can use a slice to get that

 firstTen = finalDataList[:10]
 lastTen  = finalDataList[-10:]

but as you don't assign it result to anything, then you print it?

my_list = [1, 0, 5, 9, 3, 8, 4]
return [item for index, item in enumerate(my_list) if index == 0 or my_list[index] >= my_list[index - 1]]

this code will iterate over my_list comparing current item to previous taking only ones which are greater then previous.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM