So I made a recursive function that gives me all the subarrays , I want to apply a condition on those sub-arrays and then keep a count of subarrays that satisfy the condition. But Initialization of count variable has been bothering me ,please help!
here is my code:
def printSubArrays(arr, start, end):
if end == len(arr):
return
elif start > end:
return printSubArrays(arr,0,end+1)
else:
dictio = arr[start:end + 1]
print(dictio)
if len(dictio)!=1:
for i in range(len(dictio)):
aand =1
aand =aand & dictio[i]
if aand %2 !=0:
count=count+1
return printSubArrays(arr,start+1,end)
arr=[1,2,5,11,15]
dictio=[]
count = 0
printSubArrays(arr,0,0)
print(count)
The most common technique to keep a count is to use a helper function. So you'd have your principal function call a helper like this:
def printSubArrays(arr, start, end):
return _printSubArrays(arr, start, end, 0)
The 0 at the end is the count.
Then each time you recurse you increment:
def _printSubArrays(arr, start, end, count):
if end == len(arr):
return count
elif start > end:
return _printSubArrays(arr,0,end+1, count + 1)
else:
dictio = arr[start:end + 1]
print(dictio)
if len(dictio)!=1:
for i in range(len(dictio)):
aand =1
aand =aand & dictio[i]
if aand %2 !=0:
count=count+1
return _printSubArrays(arr,start+1,end, count+1)
Related
The helper retrieves value to be compared in the search function. here mem is an object.
def get_val(mem, c):
if c == "n":
return mem.get_name()
elif c == "z":
return mem.get_zip()
In the function below the helper function above is called in each iteration. Will this impact the time-complexity of the binary search or will it still be O(log n)
def bin_search(array, c, s):
first = 0
last = len(array)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
val = get_val(array[mid], criteria)
if val == s:
return array[mid]
else:
if s < val:
last = mid - 1
else:
first = mid + 1
return None
Since you are calling get_val() once per iteration of your binary search, the total time complexity should be
O(log n * f(x)),
where f(x) is the time complexity of get_val(). If this is constant (does not depend on the input, such as the contents of array), then indeed your total time complexity is still O(log n).
Why doesn't this return the tuple and instead returns nonetype? I've tried removing everything I could think of to get it to return the tuple. I either have mistyped something which i have spent an hour or so checking, or i am missing something bigger..
Thanks!!
import time
def BONGO_BONGO(item, num=1, wait_time=4):
time.sleep(.99)
list_of_positions = []
if item in list_of_positions:
result = (1, 333)
return result
elif num >= wait_time:
print(str(wait_time) + " seconds have passed.. ")
print("test")
result = (2, 9)
print(result)
return result
else:
print(str(item) + " execution checked: " + str(num))
num += 1
BONGO_BONGO(item=item, num=num)
y = BONGO_BONGO("ITEM444")
if __name__ == "__main__":
print(y)
Okay the answer is that the nested bongo_bongo function under the "else" is the function that in the end will return the desired tuple from the "elif". So you need to return that last bongo_bongo function under the "else".
import time
def BONGO_BONGO(item, num=1, wait_time=4):
time.sleep(.99)
list_of_positions = []
if item in list_of_positions:
result = (1, 333)
return result
elif num >= wait_time:
print(str(wait_time) + " seconds have passed.. ")
print("test")
result = (2, 9)
print(result)
return result
else:
print(str(item) + " execution checked: " + str(num))
num += 1
result = BONGO_BONGO(item=item, num=num)
return result
y = BONGO_BONGO("ITEM444")
if __name__ == "__main__":
print("Y=", y)
Suppose x,y,z are int variables and A is a matrix, I want to express a constraint like:
z == A[x][y]
However this leads to an error:
TypeError: object cannot be interpreted as an index
What would be the correct way to do this?
=======================
A specific example:
I want to select 2 items with the best combination score,
where the score is given by the value of each item and a bonus on the selection pair.
For example,
for 3 items: a, b, c with related value [1,2,1], and the bonus on pairs (a,b) = 2, (a,c)=5, (b,c) = 3, the best selection is (a,c), because it has the highest score: 1 + 1 + 5 = 7.
My question is how to represent the constraint of selection bonus.
Suppose CHOICE[0] and CHOICE[1] are the selection variables and B is the bonus variable.
The ideal constraint should be:
B = bonus[CHOICE[0]][CHOICE[1]]
but it results in TypeError: object cannot be interpreted as an index
I know another way is to use a nested for to instantiate first the CHOICE, then represent B, but this is really inefficient for large quantity of data.
Could any expert suggest me a better solution please?
If someone wants to play a toy example, here's the code:
from z3 import *
items = [0,1,2]
value = [1,2,1]
bonus = [[1,2,5],
[2,1,3],
[5,3,1]]
choices = [0,1]
# selection score
SCORE = [ Int('SCORE_%s' % i) for i in choices ]
# bonus
B = Int('B')
# final score
metric = Int('metric')
# selection variable
CHOICE = [ Int('CHOICE_%s' % i) for i in choices ]
# variable domain
domain_choice = [ And(0 <= CHOICE[i], CHOICE[i] < len(items)) for i in choices ]
# selection implication
constraint_sel = []
for c in choices:
for i in items:
constraint_sel += [Implies(CHOICE[c] == i, SCORE[c] == value[i])]
# choice not the same
constraint_neq = [CHOICE[0] != CHOICE[1]]
# bonus constraint. uncomment it to see the issue
# constraint_b = [B == bonus[val(CHOICE[0])][val(CHOICE[1])]]
# metric definition
constraint_sumscore = [metric == sum([SCORE[i] for i in choices ]) + B]
constraints = constraint_sumscore + constraint_sel + domain_choice + constraint_neq + constraint_b
opt = Optimize()
opt.add(constraints)
opt.maximize(metric)
s = []
if opt.check() == sat:
m = opt.model()
print [ m.evaluate(CHOICE[i]) for i in choices ]
print m.evaluate(metric)
else:
print "failed to solve"
Turns out the best way to deal with this problem is to actually not use arrays at all, but simply create integer variables. With this method, the 317x317 item problem originally posted actually gets solved in about 40 seconds on my relatively old computer:
[ 0.01s] Data loaded
[ 2.06s] Variables defined
[37.90s] Constraints added
[38.95s] Solved:
c0 = 19
c1 = 99
maxVal = 27
Note that the actual "solution" is found in about a second! But adding all the required constraints takes the bulk of the 40 seconds spent. Here's the encoding:
from z3 import *
import sys
import json
import sys
import time
start = time.time()
def tprint(s):
global start
now = time.time()
etime = now - start
print "[%ss] %s" % ('{0:5.2f}'.format(etime), s)
# load data
with open('data.json') as data_file:
dic = json.load(data_file)
tprint("Data loaded")
items = dic['items']
valueVals = dic['value']
bonusVals = dic['bonusVals']
vals = [[Int("val_%d_%d" % (i, j)) for j in items if j > i] for i in items]
tprint("Variables defined")
opt = Optimize()
for i in items:
for j in items:
if j > i:
opt.add(vals[i][j-i-1] == valueVals[i] + valueVals[j] + bonusVals[i][j])
c0, c1 = Ints('c0 c1')
maxVal = Int('maxVal')
opt.add(Or([Or([And(c0 == i, c1 == j, maxVal == vals[i][j-i-1]) for j in items if j > i]) for i in items]))
tprint("Constraints added")
opt.maximize(maxVal)
r = opt.check ()
if r == unsat or r == unknown:
raise Z3Exception("Failed")
tprint("Solved:")
m = opt.model()
print " c0 = %s" % m[c0]
print " c1 = %s" % m[c1]
print " maxVal = %s" % m[maxVal]
I think this is as fast as it'll get with Z3 for this problem. Of course, if you want to maximize multiple metrics, then you can probably structure the code so that you can reuse most of the constraints, thus amortizing the cost of constructing the model just once, and incrementally optimizing afterwards for optimal performance.
I decide to modify the following while loop and use it inside a function so that the loop can take any value instead of 6.
i = 0
numbers = []
while i < 6:
numbers.append(i)
i += 1
I created the following script so that I can use the variable(or more specifically argument ) instead of 6 .
def numbers(limit):
i = 0
numbers = []
while i < limit:
numbers.append(i)
i = i + 1
print numbers
user_limit = raw_input("Give me a limit ")
numbers(user_limit)
When I didn't use the raw_input() and simply put the arguments from the script it was working fine but now when I run it(in Microsoft Powershell) a cursor blinks continuously after the question in raw_input() is asked. Then i have to hit CTRL + C to abort it. Maybe the function is not getting called after raw_input().
Now it is giving a memory error like in the pic.
You need to convert user_limit to Int:
raw_input() return value is str and the statement is using i which is int
def numbers(limit):
i = 0
numbers = []
while i < limit:
numbers.append(i)
i = i + 1
print numbers
user_limit = int(raw_input("Give me a limit "))
numbers(user_limit)
Output:
Give me a limit 8
[0, 1, 2, 3, 4, 5, 6, 7]
How can I find out the max occurrences of consecutive character in a string and return the result as an array in sorted order.
Example:
input = “abcccdddeee”
output = [“c”,”d”,”e”]
This is crude and likely can be improved, but you're basically looking at a simple state machine, where the current state is the previous character, and the next state is either a reset or an incrementation of a counter.
str = "abcccdddeee"
state = nil
current_count = 0
counts = {}
str.each_char do |char|
if state == char
current_count += 1
counts[char] ||= 0
counts[char] = current_count if current_count > counts[char]
else
current_count = 0
end
state = char
end
p counts.to_a.sort {|a, b| b[1] <=> a[1] }.map(&:first)
Since this only counts and stores counts when the current input causes the FSM to remain in the counting state, you don't get non-repeating characters in your output.
However, since this is Ruby, we can cheat and use regexes:
"abccdddeee".scan(/((.)\2{1,})/).map(&:first).sort_by(&:length).map {|s| s[0] }