Home python Python Problem: A Larger List Item

Python Problem: A Larger List Item

Author

Date

Category

Task: given a list with numbers. Write a program that prints all the items in a list that are larger than the previous one as a separate list. As I understand it, it is necessary, for example, from the given list [1, 5, 1, 5, 1] ​​to output as a result [5, 5]
Tried to solve like this:

a = [1, 5, 1, 5, 1]
for i in range(len(a) - 1):
    n = [a[i]]
    i += 1
    m = [a[i]]
    if m > n:
        n = m
        print(m, end='')

The output is:
[5] [5] and should be [5, 5] because should be displayed as a separate list

Please suggest what needs to be changed in the code?


Answer 1

a = [1, 5, 1, 5, 1]
answer = []
for i in range(len(a)-1):
    if a[i] < a[i+1]:
        answer.append(a[i+1])
print(answer)

You need to create an array, because it is written in the problem statement


Answer 2, authority 200%

a = [1, 5, 1, 5, 1]
m = [j for i, j in zip(a, a[1:]) if j > i]

Answer 3, authority 100%

You can do this

a = [1, 5, 1, 5, 1]
c= []
for i in range(len(a) - 1):
    n = a[i]
    i += 1
    m = a[i]
    if m > n:
        c.append(m)
print(c) 

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions