2

I'm having issues determining my maximum value calculated in my for loop. I'm using Python to evaluate an array to determine the maximum delta in a sequence i.e. maximum value i+1-i.

I'm having two issues:

  1. SyntaxError: 'return' outside function
  2. I don't know how to pull the largest calculated iterated value from my for loop

Tried having other variables to compare largest values etc

prices=[7,1,5,3,6,4]
profit_loss=0
for i in range(0,len(prices)-1):
        profit_loss=prices[i+1] - prices[i]
        return(profit_loss)
        print(profit_loss)

Maximum value should be 4 and the results of my print are below:

-6
4
-2
3
-2

This question is unique because I am looking to understand why the return function is not necessary.

Ramy AS
  • 33
  • 4
  • 4
    Possible duplicate of [Finding the largest delta between two integers in a list in python](https://stackoverflow.com/questions/3428769/finding-the-largest-delta-between-two-integers-in-a-list-in-python) – Aaditya Maheshwari Dec 27 '18 at 03:17

2 Answers2

4

You can't return outside a function. In fact, you don't need return here:

prices = [7,1,5,3,6,4]
profit_loss = -float('inf')

for i in range(len(prices)-1):
    change = prices[i+1] - prices[i]
    if change > profit_loss:
        profit_loss = change

print(profit_loss)  # 4

More idiomatic than positional indexing, use zip to iterate elements of prices pairwise:

for i, j in zip(prices, prices[1:]):
    change = j - i
    if change > profit_loss:
        profit_loss = change

More succinctly, use max with a generator comprehension:

profit_loss = max(j - i for i, j in zip(prices, prices[1:]))  # 4

Or use the functional equivalent:

from operator import sub
profit_loss = max(map(sub, prices[1:], prices))  # 4
jpp
  • 159,742
  • 34
  • 281
  • 339
0

This should work:

prices = [7, 1, 5, 3, 6, 4]
profit_loss = 0
for i in range(0, len(prices)-1):
    res = prices[i+1] - prices[i]
    if res > profit_loss:
        profit_loss = res
print(profit_loss)
Partho63
  • 3,117
  • 2
  • 21
  • 39