|
| 1 | +""" Non-negative 1-sparse recovery problem. This algorithm assumes we have a non negative dynamic stream. |
| 2 | +Given a stream of tuples, where each tuple contains a number and a sign (+/-), it check if the stream is 1-sparse, meaning if the elements |
| 3 | +in the stream cancel eacheother out in such a way that ther is only a unique number at the end. |
| 4 | +
|
| 5 | +Examples: |
| 6 | +#1 |
| 7 | +Input: [(4,'+'), (2,'+'),(2,'-'),(4,'+'),(3,'+'),(3,'-')], |
| 8 | +Output: 4 |
| 9 | +Comment: Since 2 and 3 gets removed. |
| 10 | +#2 |
| 11 | +Input: [(2,'+'),(2,'+'),(2,'+'),(2,'+'),(2,'+'),(2,'+'),(2,'+')] |
| 12 | +Output: 2 |
| 13 | +Comment: No other numbers present |
| 14 | +#3 |
| 15 | +Input: [(2,'+'),(2,'+'),(2,'+'),(2,'+'),(2,'+'),(2,'+'),(1,'+')] |
| 16 | +Output: None |
| 17 | +Comment: Not 1-sparse |
| 18 | +""" |
| 19 | + |
| 20 | +def one_sparse(array): |
| 21 | + sum_signs = 0 |
| 22 | + bitsum = [0]*32 |
| 23 | + sum_values = 0 |
| 24 | + for val,sign in array: |
| 25 | + if sign == "+": |
| 26 | + sum_signs += 1 |
| 27 | + sum_values += val |
| 28 | + else: |
| 29 | + sum_signs -= 1 |
| 30 | + sum_values -= val |
| 31 | + |
| 32 | + _get_bit_sum(bitsum,val,sign) |
| 33 | + |
| 34 | + if sum_signs > 0 and _check_every_number_in_bitsum(bitsum,sum_signs): |
| 35 | + return int(sum_values/sum_signs) |
| 36 | + else: |
| 37 | + return None |
| 38 | + |
| 39 | +#Helper function to check that every entry in the list is either 0 or the same as the |
| 40 | +#sum of signs |
| 41 | +def _check_every_number_in_bitsum(bitsum,sum_signs): |
| 42 | + for val in bitsum: |
| 43 | + if val != 0 and val != sum_signs : |
| 44 | + return False |
| 45 | + return True |
| 46 | + |
| 47 | +# Adds bit representation value to bitsum array |
| 48 | +def _get_bit_sum(bitsum,val,sign): |
| 49 | + i = 0 |
| 50 | + if sign == "+": |
| 51 | + while(val): |
| 52 | + bitsum[i] += val & 1 |
| 53 | + i +=1 |
| 54 | + val >>=1 |
| 55 | + else : |
| 56 | + while(val): |
| 57 | + bitsum[i] -= val & 1 |
| 58 | + i +=1 |
| 59 | + val >>=1 |
| 60 | + |
| 61 | + |
0 commit comments