Given a list:

list = [220.32, 205.1, 204.6, 203.2, 203.75, 203.25, 203.75, 203.5] 

It is necessary to compare the elements of the list with each other in the loop and a larger element.
divided by smaller. But do not assign names to each element of the list.

My code does not allow this:

 for i in list: if list[i] > list[i + 1]: a = (list[i] / list[i + 1] ) else: a = (list[i + 1] / list[i] ) print(a) 

Libraries cannot be used.

Throws an exception:

Traceback (most recent call last): File "", line 2, in

TypeError: list indices must be integers or slices, not

float`

  • You have the same brackets are not closed - Xander
  • Fixed, thanks! - SinCap

2 answers 2

 myList = [220.32, 205.1, 204.6, 203.2, 203.75, 203.25, 203.75, 203.5] [ [myList[i-1]/myList[i] if myList[i-1]>myList[i] else myList[i]/myList[i-1]] for i in range(1, len(myList)) ] [[1.0742077035592394], [1.0024437927663734], [1.0068897637795275], [1.0027066929133859], [1.002460024600246], [1.002460024600246], [1.0012285012285012]] 

or so:

 for i in range(1, len(myList)): if myList[i-1]>myList[i]: a = myList[i-1]/myList[i] else: a = myList[i]/myList[i-1] print(a) 1.0742077035592394 1.0024437927663734 1.0068897637795275 1.0027066929133859 1.002460024600246 1.002460024600246 1.0012285012285012 
  • I don't need to import libraries, the code should be without using them - SinCap
  • @SinCap Please, no import) - S. Nick
  • Everything seems to be ALMOST the same thing, only plus with a minus is misaligned in comparison and the object that will process the cycle is not quite right. Poorly understood similar algorithms. Can you advise something? - SinCap
  • one
    @SinCap We compare the read list item with the previous one, so we start with the index 1, not 0. That's all. - S. Nick
  • one
    @SinCap If my answer helped you with something, do not forget to mark it as useful. - S. Nick
 # a = [((a / b) if (a > b) else (b / a)) for (a, b) in zip(myList, myList[1:])] # import operator, itertools # a = list(itertools.starmap(operator.truediv, map(reversed, map(sorted, zip(myList, myList[1:]))))) myList = [220.32, 205.1, 204.6, 203.2, 203.75, 203.25, 203.75, 203.5] a = list(next(i)/next(i) for i in map(iter, map(reversed, map(sorted, zip(myList, myList[1:]))))) print(a) # [1.0742077035592394, 1.0024437927663734, 1.0068897637795275, 1.0027066929133859, 1.002460024600246, 1.002460024600246, 1.0012285012285012] 
  • The author pointed out that you can not use the library - Let's say Pie