2

Here's a function in my code:

def get_weights(Last_scan, Peak_shot):
    Est_Succshots = [x*Peak_shot for x in Last_scan.values()]
    Est_error = [np.sqrt(i)/Peak_shot for i in Est_Succshots]
    Is = [1/m for m in Est_error]
    Weights = [i/sum(Is) for i in Is]
    return Weights

I used 4 list comprehensions to do the calculation. I wonder is there a shorter way or a different approach I can perform such calculations? Thanks for the help:)

3
  • 5
    I would say this is a good case for just using a for loop instead of list comprehensions. There is no reason to be creating a new list at every step when you could just use a for loop and do all the calculations at once while being equally readable. Commented Aug 11, 2021 at 1:16
  • 2
    You can combine all your mapping ops into a single one. Not sure if that's better. Commented Aug 11, 2021 at 1:16
  • 2
    not sure you need a second loop here, id go with Is = [1/(np.sqrt(i)/Peak_shot) for i in Est_Succshots] and drop Est_error Commented Aug 11, 2021 at 1:21

1 Answer 1

4

Assuming that Last_scan.values() is a list of numbers and Peak_shot is a number, this seems to be equivalent to

def get_weights(Last_scan, Peak_shot):
    Is =  np.sqrt(Peak_shot/np.array(Last_scan.values()))
    return Is/Is.sum()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! Yes Last_scan is a dictionary and Peak_shot is a number. It returns TypeError: unsupported operand type(s) for /: 'int' and 'dict_values'
In such case replace Last_scan.values() by list(Last_scan.values()).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.