title: Find propotional sampling using python
body: <p>I'm given a problem that explicitly asks me not to use numpy and pandas</p>
  
  <p>Prob : Selecting an element from the list A randomly with probability proportional to its magnitude. assume we are doing the same experiment for 100 times with replacement, in each experiment you will print a number that is selected randomly from A.</p>
  
  <pre><code>Ex 1: A = [0 5 27 6 13 28 100 45 10 79]
  let f(x) denote the number of times x getting selected in 100 experiments.
  f(100) &gt; f(79) &gt; f(45) &gt; f(28) &gt; f(27) &gt; f(13) &gt; f(10) &gt; f(6) &gt; f(5) &gt; f(0)
  </code></pre>
  
  <p>Initially, I took the sum of all the elements of list A</p>
  
  <p>I then divided (in order to normaliz) each element of list A by the sum and stored each of these values in another list (d_dash)</p>
  
  <p>I then created another empty list (d_bar), that takes in cumalative sum of all elements of d_dash </p>
  
  <p>created variable r, where r= random.uniform(0.0,1.0), and then for the length of d_dash comapring r to d_dash[k], if r&lt;=d_dash[k], return A[k]  </p>
  
  <p>However, I'm getting the error <code>list index out of range</code> near d_dash[j].append((A[j]/sum)), not sure what is the issue here as I did not exceed the index of either d_dash or A[j].</p>
  
  <p>Also, is my logic correct ? sharing a better way to do this would be appreciated. </p>
  
  <p>Thanks in advance.</p>
  
  <pre><code>import random
  
  A = [0,5,27,6,13,28,100,45,10,79]
  
  def propotional_sampling(A):
      sum=0
      for i in range(len(A)):
          sum = sum + A[i]
  
      d_dash=[]
  
      for j in range(len(A)):
          d_dash[j].append((A[j]/sum))
  
      #cumulative sum
  
      d_bar =[]
      d_bar[0]= 0
  
      for k in range(len(A)):
          d_bar[k] = d_bar[k] + d_dash[k]
  
      r = random.uniform(0.0,1.0)
      number=0
  
      for p in range(len(d_bar)):
          if(r&lt;=d_bar[p]):
              number=d_bar[p]
      return number
  
  def sampling_based_on_magnitued():
      for i in range(1,100):
          number = propotional_sampling(A)
          print(number)
  
  sampling_based_on_magnitued()
  </code></pre>