How can I iterate this list over a loop? I am a beginner and python is my first language

139 views Asked by At

Zybooks Instructions

List data_list contains integers read from input, representing a sequence of data values. For each index i of data_list from 1 through the second-to-last index:

The element at index i is a hunch if the element is greater than both the preceding element and the following element. If the element at index i is a hunch, then output 'Hunch: ', followed by the preceding element, the current element, and the following element, separating each element by a space.

Example

Ex: If the input is 12 14 72 52, then the output is:

  • Sequence: [12, 14, 72, 52]
  • Hunch: 14 72 52

Zybooks code

tokens = input().split()

data_list = []
for token in tokens:
    data_list.append(int(token))

print(f'Sequence: {data_list}')

My Code to complete zybooks code

for i, data in enumerate(data_list[1: -2]):
    if data_list[i] > data_list[i - 1] and data_list[i] > data_list[i + 1]:
        print(f"Hunch: {data_list[i - 1]} {data_list[i]} {data_list[i + 1]}")

The output with 12, 14, 72, 52##

  • Sequence: [12, 14, 72, 52]
5

There are 5 answers

0
no comment On

Shorter input way, and four solutions.

seq = list(map(int, input().split()))

for a, b, c in zip(seq, seq[1:], seq[2:]):
    if a < b > c:
        print('Hunch:', a, b, c)

a, b = seq[:2]
for c in seq[2:]:
    if a < b > c:
        print('Hunch:', a, b, c)
    a, b = b, c

a = b = None
for c in seq:
    if None is not a < b > c:
        print('Hunch:', a, b, c)
    a, b = b, c

b = float('nan')
for c in seq:
    if c < b > a:
        print('Hunch:', a, b, c)
    a, b = b, c

Attempt This Online!

0
OneCricketeer On

enumerate always starts counting at zero unless given start parameter, so after you slice the list, the index is not representing the original position

Since you're not using the data variable, just use range

for i in range(1, len(data_list) - 1):
    if data_list[i - 1] < data_list[i] > data_list[i + 1] :
        print("Hunch: " + ' '.join(tokens[i-1:i+2]))
11
Suramuthu R On

You have not mentioned in your question about how many sets of huches will be there in the list. i.e just one set of hunches or more than one set of hunches. Assuming that the list will have multiple sets or hunches hunches, I'he given the solution. You can modify the code according to your requirement. Understand how to use the f-string and change the code accordingly.

l = [12, 14, 72, 52, 22, 78, 33] 
hunches = []

# Index based iteration till the last but one element
for i in range(1,len(l)-1):

    #if the number is greater than both previous and next number, make a list
    if l[i-1] < l[i] > l[i + 1]:
        sub = f'{l[i-1]} {l[i]} {l[i+1]}'

        # append this list to the list hunches
        hunches.append(sub)

print(f'Hunches: {hunches}') #Output: Hunches: ['14 72 52', '22 78 33']
0
Bhagyadev kp On

Define a list

my_list = [1, 2, 3, 4, 5]

Iterate over the list using a for loop

for item in my_list: print(item) # This will print each item in the list on a new line

0
SIGHUP On

For the core part of your code to run reliably you really need to do some input validation.

I suggest:

while data := input("Enter at least 3 integers or press <Return> to exit: "):
    try:
        if len(nlist := list(map(int, data.split()))) < 3:
            print("\aNot enough values")
        else:
            for a, b, c in zip(nlist, nlist[1:], nlist[2:]):
                if a < b > c:
                    print("Hunch:", a, b, c)
                    break
            else:
                print("No hunch found")
    except ValueError as e:
        print(f"\a{e}")