-1

I have an exchange data stream coming in that sets symbol to a random letter of the alphabet every like 10 ms in an infinite while loop that is calling func(pair, time). Symbol is the trading pair for simplification here. I have used A and Z to show the range.

Using the method below, I have to create a lot of if-statements when I want to count i for each letter. IE, I have to create iA, iB, iC, .. iZ. In reality, there is about 20 lines code to execute instead of the i-iteration shown here. This is very messy.

I am a beginner in coding and stuck with finding a more elegant and perhaps computationally faster way to do this.

def func(symbol, cur_time):

    if future_timeA > cur_timeA and symbol = A:
        iA += iA
    return -1


    if future_timeA < cur_timeA and symbol = A:
        future_timeA = cur_timeA + 1
        valueA = iA
    return valueA


    if future_timeZ > cur_timeZ and symbol = Z:
        iZ += iZ
    return -1


    if future_timeZ < cur_timeZ and symbol = Z:
        future_timeZ = cur_timeZ + 1
        value = iZ
    return valueZ 
nolimits
  • 43
  • 1
  • 3
  • 16

3 Answers3

1

Since you need to check for each of the 26 letters, at least this much code would be there. This is available in Python 3.10.

match symbol:
      case "A":
       do whatever for A 
      case "B":
       do whatever for B
      ....
      case "Z":
       do whatever for Z  
Devang Sanghani
  • 731
  • 5
  • 14
  • Interesting! So if I run this for A and the next letter is B and A and B have i as variable, then i would iterate every time regardless A or B right? Thats my problem :D – nolimits Feb 22 '22 at 09:21
  • You would need to put in the code for A,B,...,Z, to process whatever you want to, yes. What iteration are you referring to here? – Devang Sanghani Feb 22 '22 at 09:23
0

Instead of symbol, use a number between 0 and 25 to represent all possible letters. This way you can create an array with 26 inputs to calculate the amount of all letters, and put this in a loop for cleaner code.

Hope that helps you further!

Mark
  • 45
  • 5
  • You could also create a list ['A','B','C',...,'Z'] to loop through all letters. – Mark Feb 22 '22 at 08:01
  • And 'return' statements should be inside the if statement (so one tab further) - after the return statement, the function is terminated. – Mark Feb 22 '22 at 08:02
  • Oh and one more thing: perhaps write code first (build it up step by step) to see what it does. Only when it is fully functioning, replace part of your code by a function. This is way easier, and error proof! – Mark Feb 22 '22 at 08:03
0

Python3.10 introduced a match case statement for that kind of problem: See this answer.

Jonathan Scholbach
  • 4,925
  • 3
  • 23
  • 44