简体   繁体   中英

Hey everyone, I was just wondering what was wrong with my code?

Im trying to create a function that records the amount of times a value in a list is repeated in a row. After about an hour of deliberation, I was able to reach a stable-looking conclusion, yet i am unable to receive the desired outcome

lst = [1,2,2,2,3,1,1]

def compress(numlist):
    intervals,x=0,0
    for i in numlist:   
        if i == numlist[x]:
            intervals+=1   
        elif i != numlist[x]:
            print((intervals,numlist[x]), end=" ")
            x+=intervals
            intervals=1

    
    
compress(lst)

Here, I was trying to get the function to "compress" the list of integers When I run the code, the outcome is:

(1, 1) (3, 2) (1, 3)

While the desired outcome is:

(1, 1) (3, 2) (1, 3) (2,1)

You only show a run when you find a value that is not equal to the previous one. There is no value after the last value, of course, so the last run is never printed. Just add a line after the loop to print the last run.

if intervals != 0:
    print((intervals,numlist[x]))

By the way, you don't need the elif conditional. All you need there is an else , since if i == numlist[x] , then the only other thing possible is i != numlist[x] .

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