I have a search algorithm that looks for combinations of add and multiply functions to reach a certain range of number from a certain range of numbers. It is searching for the shortest program, a program being a something like AAMMA where the initial number is added, added, multiplied, multiplied, add where the ending number is in the range r to s. It has to work for every number in the starting range p to q.
The input is a and m, what you are adding and multiplying by(num+a), (num*m) for each function. What I am doing is trying every combination of functions until I find one that works, stopping that branch if it gets too big. If I find "program" that works I try the program on all of the other numbers in the starting range. It does this until either it finds no branches that don't reach the range without going over.
I know the search isn't super typical, but I don't think there is a possibility for duplicates so I didn't include a found list.
It works for smaller ranges and inputs like
Problem3("1 2 2 3 10 20")
but for larger ranges, it just takes forever my test case is
Problem3("8 13 28 91 375383947 679472915")
which I haven't even seen complete. What is my best approach from here, multithreading(hope not), making my inner functions faster somehow or just scraping this approach.
def Problem3(s):
a,m,p,q,r,s = list(map(int, s.split(" ")))
print(str(a) + "-C-" + str(m) + " processor")
print("Input guarenteed between " + str(p) + " and " + str(q))
print("Output is real number between " + str(r) + " and " + str(s))
open_set = queue.Queue()
# curr path depth
open_set.put([p, "", 0])
while not open_set.empty():
subroot = open_set.get()
multiCurr = subroot[0] * m
addCurr = subroot[0] + a
depth = subroot[2] + 1
if r <= addCurr <= s:
truePath = True
#If we find a working path, we need to check if it works for the other things
path = subroot[1] + "A"
for x in range(p, q+1):
for op in path:
if op == "A":
x += a
if op == "M":
x *= m
if r <= x <= s:
pass
else:
truePath = False
break
if truePath:
print("Found " + path + " at depth " + str(depth) + " with starting number " + str(p) + ", output " + str())
if r <= multiCurr <= s:
truePath = True
path = subroot[1] + "M"
for x in range(p, q+1):
for op in path:
if op == "A":
x += a
if op == "M":
x *= m
if r <= x <= s:
pass
else:
truePath = False
break
if truePath:
print("Found " + path + " at depth " + str(depth) + " with starting number " + str(p) + ", output " + str())
if addCurr > s and multiCurr > s:
pass
elif multiCurr > s:
open_set.put([addCurr, subroot[1] + "A", depth])
elif addCurr > s:
open_set.put([multiCurr, subroot[1] + "M", depth])
else:
open_set.put([multiCurr, subroot[1] + "M", depth])
open_set.put([addCurr, subroot[1] + "A", depth])
You don't need to test every value in the range(p, q + 1) sequence. You only need to test for p and q. If it works for the lowest and the highest number, it'll work for all the values in between, because the problem has been reduced to just multiplication and addition. You really only need to test the progress of program(q), keeping it below s, until you have created the shortest program that puts program(p) at or above r.
However, this isn't really a great problem for breath-first search; your second example would require testing 17.6 trillion possible states; the shortest solution is 44 characters long, so a breath-first search would explore 2 ** 44 states, so 17,592,186,044,416 to be exact! Even using a compiled programming language like C would take a long, long time to find the solution using such a search. Instead, you can just generate the string using a bit of math.
You can calculate the maximum number of multiplications needed here with int(math.log(s // q, m)), that's the number of times you can multiply with m when starting at q and still stay below s. You can't ever use more multiplications! With math.ceil(math.log(r / p, m)) you can find the minimum number of multiplications that would put p at or above r. To minimise the program length, pick the lower value of those two numbers.
Then, start fitting in A additions, before each M multiplication. Do so by taking i as the number of M characters that are to follow, then dividing both r and s by m ** i. These inform the number a additions to p and q that together with the subsequent multiplications bring it closest to r and s; the difference with the current p and q let you calculate the minimum number of A characters you can insert here to keep within the [r, s] range. For p, round up, for q, round down.
Repeat this procedure for every subsequent M operation, updating the p and q values with the results each time:
import math
def problem3(s):
a, m, p, q, r, s = map(int, s.split())
p_mult = math.ceil(math.log(math.ceil(r / p), m))
q_mult = int(math.log(s // q, m))
mult = min(p_mult, q_mult)
program = []
for i in range(mult, -1, -1):
p_additions = math.ceil((math.ceil(r / (m ** i)) - p) / a)
q_additions = ((s // (m ** i)) - q) // a
additions = min(p_additions, q_additions)
program += [additions * 'A']
if i:
p, q = (p + (additions * a)) * m, (q + (additions * a)) * m
program += ['M']
return ''.join(program)
This is a closed-form solution, no search needed. The result is guaranteed to be the shortest:
>>> problem3("1 2 2 3 10 20")
'AMM'
>>> problem3("8 13 28 91 375383947 679472915")
'AAAAAAMAAMAAAAAAAAAAAMAAAAAMAAAMAAAAMAAAAAAA'
Related
I want to draw a triangle of asterisks from a given n which is an odd number and at least equal to 3. So far I did the following:
def main():
num = 5
for i in range(num):
if i == 0:
print('-' * num + '*' * (i + 1) + '-' * num)
elif i % 2 == 0:
print('-' * (num-i+1) + '*' * (i + 1) + '-' * (num-i+1))
else:
continue
if __name__ == "__main__":
main()
And got this as the result:
-----*-----
----***----
--*****--
But how do I edit the code so the number of hyphens corresponds to the desirable result:
-----*-----
----***----
---*****---
--*-----*--
-***---***-
*****-*****
There's probably a better way but this seems to work:
def triangle(n):
assert n % 2 != 0 # make sure n is an odd number
hyphens = n
output = []
for stars in range(1, n+1, 2):
h = '-'*hyphens
s = '*'*stars
output.append(h + s + h)
hyphens -= 1
pad = n // 2
mid = n
for stars in range(1, n+1, 2):
fix = '-'*pad
mh = '-'*mid
s = '*'*stars
output.append(fix + s + mh + s + fix)
pad -= 1
mid -= 2
print(*output, sep='\n')
triangle(5)
Output:
-----*-----
----***----
---*****---
--*-----*--
-***---***-
*****-*****
Think about what it is you're iterating over and what you're doing with your loop. Currently you're iterating up to the maximum number of hyphens you want, and you seem to be treating this as the number of asterisks to print, but if you look at the edge of your triforce, the number of hyphens is decreasing by 1 each line, from 5 to 0. To me, this would imply you need to print num-i hyphens each iteration, iterating over line number rather than the max number of hyphens/asterisks (these are close in value, but the distinction is important).
I'd recommend trying to make one large solid triangle first, i.e.
-----*-----
----***----
---*****---
--*******--
-*********-
***********
since this is a simpler problem to solve and is just one modification away from what you're trying to do (this is where the distinction between number of asterisks and line number will be important, as your pattern changes dependent on what line you're on).
I'll help get you started; for any odd n, the number of lines you need to print is going to be (n+1). If you modify your range to be over this value, you should be able to figure out how many hyphens and asterisks to print on each line to make a large triangle, and then you can just modify it to cut out the centre.
I'm struggling to make a Python program that can solve riddles such as:
get 23 using [1,2,3,4] and the 4 basic operations however you'd like.
I expect the program to output something such as
# 23 reached by 4*(2*3)-1
So far I've come up with the following approach as reduce input list by 1 item by checking every possible 2-combo that can be picked and every possible result you can get to.
With [1,2,3,4] you can pick:
[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]
With x and y you can get to:
(x+y),(x-y),(y-x),(x*y),(x/y),(y/x)
Then I'd store the operation computed so far in a variable, and run the 'reducing' function again onto every result it has returned, until the arrays are just 2 items long: then I can just run the x,y -> possible outcomes function.
My problem is this "recursive" approach isn't working at all, because my function ends as soon as I return an array.
If I input [1,2,3,4] I'd get
[(1+2),3,4] -> [3,3,4]
[(3+3),4] -> [6,4]
# [10,2,-2,24,1.5,0.6666666666666666]
My code so far:
from collections import Counter
def genOutputs(x,y,op=None):
results = []
if op == None:
op = str(y)
else:
op = "("+str(op)+")"
ops = ['+','-','*','/','rev/','rev-']
z = 0
#will do every operation to x and y now.
#op stores the last computated bit (of other functions)
while z < len(ops):
if z == 4:
try:
results.append(eval(str(y) + "/" + str(x)))
#yield eval(str(y) + "/" + str(x)), op + "/" + str(x)
except:
continue
elif z == 5:
results.append(eval(str(y) + "-" + str(x)))
#yield eval(str(y) + "-" + str(x)), op + "-" + str(x)
else:
try:
results.append(eval(str(x) + ops[z] + str(y)))
#yield eval(str(x) + ops[z] + str(y)), str(x) + ops[z] + op
except:
continue
z = z+1
return results
def pickTwo(array):
#returns an array with every 2-combo
#from input array
vomit = []
a,b = 0,1
while a < (len(array)-1):
choice = [array[a],array[b]]
vomit.append((choice,list((Counter(array) - Counter(choice)).elements())))
if b < (len(array)-1):
b = b+1
else:
b = a+2
a = a+1
return vomit
def reduceArray(array):
if len(array) == 2:
print("final",array)
return genOutputs(array[0],array[1])
else:
choices = pickTwo(array)
print(choices)
for choice in choices:
opsofchoices = genOutputs(choice[0][0],choice[0][1])
for each in opsofchoices:
newarray = list([each] + choice[1])
print(newarray)
return reduceArray(newarray)
reduceArray([1,2,3,4])
The largest issues when dealing with problems like this is handling operator precedence and parenthesis placement to produce every possible number from a given set. The easiest way to do this is to handle operations on a stack corresponding to the reverse polish notation of the infix notation. Once you do this, you can draw numbers and/or operations recursively until all n numbers and n-1 operations have been exhausted, and store the result. The below code generates all possible permutations of numbers (without replacement), operators (with replacement), and parentheses placement to generate every possible value. Note that this is highly inefficient since operators such as addition / multiplication commute so a + b equals b + a, so only one is necessary. Similarly by the associative property a + (b + c) equals (a + b) + c, but the below algorithm is meant to be a simple example, and as such does not make such optimizations.
def expr_perm(values, operations="+-*/", stack=[]):
solution = []
if len(stack) > 1:
for op in operations:
new_stack = list(stack)
new_stack.append("(" + new_stack.pop() + op + new_stack.pop() + ")")
solution += expr_perm(values, operations, new_stack)
if values:
for i, val in enumerate(values):
new_values = values[:i] + values[i+1:]
solution += expr_perm(new_values, operations, stack + [str(val)])
elif len(stack) == 1:
return stack
return solution
Usage:
result = expr_perm([4,5,6])
print("\n".join(result))
This question already has answers here:
Writing a function that alternates plus and minus signs between list indices
(7 answers)
Closed 2 years ago.
9.Write a program that accepts 9 integers from the user and stores them in a list. Next, compute the alternating sum of all of the elements in the list. For example, if the user enters
1 4 9 16 9 7 4 9 11
then it computes
1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11 = –2
myList = []
value = None
count = 0
while count != 9:
value = int(input("Please enter a number: "))
myList.append(value)
count = count + 1
if count == 9:
break
print(myList)
def newList(mylist):
return myList[0] - myList[1] + myList[2] - myList[3] + myList[4] - myList[5] + myList[6] - myList[7] + myList[8]
x = newList(myList)
print(x)
My code returns the correct answer, but I need it to print out the actual alternating sums as in the example. I have been stuck on this for a while. I am having a mental block on this and havent been able to find anything similar to this online.
I appreciate any help or tips.
Also, this is python 3.
Thank you.
a=[1, 4, 9, 16, 9, 7, 4, 9, 11]
start1=0
start2=1
sum1=0
first_list=[a[i] for i in range(start1,len(a),2)]
second_list=[a[i] for i in range(start2,len(a),2)]
string=''
for i,j in zip(first_list,second_list):
string+=str(i)+'-'+str(j)+'+'
string.rstrip('+')
print('{}={}'.format(string,str(sum(first_list)-sum(second_list))))
Output
1-4+9-16+9-7+4-9+=-2
Try doing this:
positives = myList[::2]
negatives = myList[1::2]
result = sum(positives) - sum(negatives)
print ("%s = %d" % (" + ".join(["%d - %d" % (p, n) for p, n in zip(positives, negatives)]), result))
I'll explain what I'm doing here. The first two lines are taking slices of your list. I take every other number in myList starting from 0 for positives and starting from 1 for negatives. From there, finding the result of the alternating sum is just a matter of taking the sum of positives and subtracting the sum of negatives from it.
The final line is somewhat busy. Here I zip positives and negatives together which produces a list of 2-tuples where of the form (positive, negative) and then I use string formatting to produce the p - n form. From there I use join to join these together with the plus sign, which produces p0 - n0 + p1 - n1 + p2 - n2.... Finally, I use string formatting again to get it in the form of p0 - n0 + p1 - n1 + p2 - n2 ... = result.
You can do as you did but place it in a print statement
print(myList[0] + " - " + myList[1] + " + " + myList[2] + " - " + myList[3] + " + " + myList[4] + " - " + myList[5] + " + " + myList[6] + " - " + myList[7] + " + " + myList[8] + " = " + x)
Its not perfectly clean, but it follows your logic, so your teacher won't know you got your solution from someone else.
Something along the lines of the following would work:
def sumList(theList):
value = 0
count = 0
steps = ""
for i in theList:
if count % 2 == 0:
value += i
steps += " + " + str(i)
else:
value -= i
steps += " - " + str(i)
count += 1
print(steps[3:])
return value
print(sumList(myList))
It alternates between + and - by keeping track of the place in the list and using the modulus operator. Then it calculates the value and appends to a string to show the steps which were taken.
You can also do something like below once your 9 or more numbers list is ready
st = ''
sum = 0
for i, v in enumerate(myList):
if i == 0:
st += str(v)
sum += v
elif i % 2 == 0:
st += "+" + str(v)
sum += v
else:
st += "-" + str(v)
sum -= v
print("%s=%d" % (st, sum))
It prints : 1-4+9-16+9-7+4-9+11=-2
I've written a function that solves a system of equations, it does however not work when I have a square root in my solutions. The code does work for other equations as long as there are no square roots.
I am getting the following error
TypeError: No loop matching the specified signature and casting
was found for ufunc solve1
I could calculate the sqrt and get a decimal number but I don't want that. I need to do my calculations with complete numbers, I would rather have it return sqrt(5) than 2.236067977
I'm currently trying to solve the following recurrence relation
eqs :=
[
s(n) = s(n-1)+s(n-2),
s(0) = 1,
s(1) = 1
];
I've written down my outputs and steps theoratically down here. It does work for equations without square roots. How can I get linalg to work with sqrt or should I use a different approach?
def solve_homogeneous_equation(init_conditions, associated):
# Write down characteristic equation for r
Returns eq_string = r^2-1*r^(2-1)-+1*r^(2-2)
# Find the roots for r
Returns r_solutions = [1/2 + sqrt(5)/2, -sqrt(5)/2 + 1/2]
# Write down general solution (for solver)
Returns two lists, one with variables and one with outcomes
general_solution_variables = [[1, 1], [1/2 + sqrt(5)/2, -sqrt(5)/2 + 1/2]]
general_solution_outcomes = [1, 1]
# Solve the system of equations
THIS IS WHERE THE ERROR OCCURS
solution = np.linalg.solve(general_solution_variables, general_solution_outcomes)
# Write the solution
This is where I rewrite the general solution with found solutions
The raw function is defined here, in case you want to look deeper in the code
def solve_homogeneous_equation(init_conditions, associated):
print("Starting solver")
# Write down characteristic equation for r
eq_length = len(init_conditions)
associated[0] = str('r^' + str(eq_length))
for i in range(eq_length, 0, -1):
if i in associated.keys() :
associated[i] = associated[i] + str('*r^(') + str(eq_length) + str('-') + str(i) + str(')')
print("Associated equation: " + str(associated))
eq_string = ''
for i in range(0, eq_length+1, 1):
if i in associated.keys():
if i < eq_length:
eq_string = eq_string + associated[i] + '-'
else:
eq_string = eq_string + associated[i]
print("Equation: " + eq_string)
# Find the roots for r
r_symbol = sy.Symbol('r')
r_solutions = sy.solve(eq_string, r_symbol)
r_length = len(r_solutions)
print("Solutions: " + str(r_solutions))
print("Eq length: " + str(eq_length) + " ; Amount of solutions: " + str(r_length))
# If equation length is equal to solutions
if eq_length == r_length:
# Write down general solution (for solver)
general_solution_variables = []
general_solution_outcomes = []
for i in range(0, eq_length):
general_solution_variables_single = []
for j in range(0, eq_length + 1):
if j != eq_length:
k = r_solutions[j]**i
general_solution_variables_single.append(k)
if j == eq_length:
k = init_conditions[i]
general_solution_outcomes.append(int(k))
general_solution_variables.append(general_solution_variables_single)
print("General solution variables: " + str(general_solution_variables))
print("General solution outcomes: " + str(general_solution_outcomes))
# Solve the system of equations
solution = np.linalg.solve(general_solution_variables, general_solution_outcomes)
print("Solutions: " + str(solution))
# Write the solution
solution_full = ""
for i in range(0, eq_length):
if i > 0:
solution_full = solution_full + " + "
solution_full = solution_full + str(int(solution[i])) + "*" + str(int(r_solutions[i])) + "^n"
print("Solved equation: " + solution_full)
return(solution_full)
# If equation length is not equal to solutions
elif eq_length > r_length:
print("NonEqual")
return 0
I haven't tried very hard to read your code. I note that you can solve that system symbolically using sympy.
As usual with sympy terms in function definitions and equations must all be moved to one side of equals sign.
The initial conditions are passed in a dict.
>>> from sympy import *
>>> from sympy.solvers.recurr import rsolve
>>> var('n')
n
>>> s = Function('s')
>>> f = s(n) - s(n-1) -s(n-2)
>>> rsolve(f, s(n), {s(0):1, s(1):1})
(1/2 + sqrt(5)/2)**n*(sqrt(5)/10 + 1/2) + (-sqrt(5)/2 + 1/2)**n*(-sqrt(5)/10 + 1/2)
(Python) Given two numbers A and B. I need to find all nested "groups" of numbers:
range(2169800, 2171194)
leading numbers: 21698XX, 21699XX, 2170XX, 21710XX, 217110X, 217111X,
217112X, 217113X, 217114X, 217115X, 217116X, 217117X, 217118X, 2171190X,
2171191X, 2171192X, 2171193X, 2171194X
or like this:
range(1000, 1452)
leading numbers: 10XX, 11XX, 12XX, 13XX, 140X, 141X, 142X, 143X,
144X, 1450, 1451, 1452
Harder than it first looked - pretty sure this is solid and will handle most boundary conditions. :) (There are few!!)
def leading(a, b):
# generate digit pairs a=123, b=456 -> [(1, 4), (2, 5), (3, 6)]
zip_digits = zip(str(a), str(b))
zip_digits = map(lambda (x,y):(int(x), int(y)), zip_digits)
# this ignores problems where the last matching digits are 0 and 9
# leading (12000, 12999) is same as leading(12, 12)
while(zip_digits[-1] == (0,9)):
zip_digits.pop()
# start recursion
return compute_leading(zip_digits)
def compute_leading(zip_digits):
if(len(zip_digits) == 1): # 1 digit case is simple!! :)
(a,b) = zip_digits.pop()
return range(a, b+1)
#now we partition the problem
# given leading(123,456) we decompose this into 3 problems
# lows -> leading(123,129)
# middle -> leading(130,449) which we can recurse to leading(13,44)
# highs -> leading(450,456)
last_digits = zip_digits.pop()
low_prefix = reduce(lambda x, y : 10 * x + y, [tup[0] for tup in zip_digits]) * 10 # base for lows e.g. 120
high_prefix = reduce(lambda x, y : 10 * x + y, [tup[1] for tup in zip_digits]) * 10 # base for highs e.g. 450
lows = range(low_prefix + last_digits[0], low_prefix + 10)
highs = range(high_prefix + 0, high_prefix + last_digits[1] + 1)
#check for boundary cases where lows or highs have all ten digits
(a,b) = zip_digits.pop() # pop last digits of middle so they can be adjusted
if len(lows) == 10:
lows = []
else:
a = a + 1
if len(highs) == 10:
highs = []
else:
b = b - 1
zip_digits.append((a,b)) # push back last digits of middle after adjustments
return lows + compute_leading(zip_digits) + highs # and recurse - woohoo!!
print leading(199,411)
print leading(2169800, 2171194)
print leading(1000, 1452)
def foo(start, end):
index = 0
is_lower = False
while index < len(start):
if is_lower and start[index] == '0':
break
if not is_lower and start[index] < end[index]:
first_lower = index
is_lower = True
index += 1
return index-1, first_lower
start = '2169800'
end = '2171194'
result = []
while int(start) < int(end):
index, first_lower = foo(start, end)
range_end = index > first_lower and 10 or int(end[first_lower])
for x in range(int(start[index]), range_end):
result.append(start[:index] + str(x) + 'X'*(len(start)-index-1))
if range_end == 10:
start = str(int(start[:index])+1)+'0'+start[index+1:]
else:
start = start[:index] + str(range_end) + start[index+1:]
result.append(end)
print "Leading numbers:"
print result
I test the examples you've given, it is right. Hope this will help you
This should give you a good starting point :
def leading(start, end):
leading = []
hundreds = start // 100
while (end - hundreds * 100) > 100:
i = hundreds * 100
leading.append(range(i,i+100))
hundreds += 1
c = hundreds * 100
tens = 1
while (end - c - tens * 10) > 10:
i = c + tens * 10
leading.append(range(i, i + 10))
tens += 1
c += tens * 10
ones = 1
while (end - c - ones) > 0:
i = c + ones
leading.append(i)
ones += 1
leading.append(end)
return leading
Ok, the whole could be one loop-level deeper. But I thought it might be clearer this way. Hope, this helps you...
Update :
Now I see what you want. Furthermore, maria's code doesn't seem to be working for me. (Sorry...)
So please consider the following code :
def leading(start, end):
depth = 2
while 10 ** depth > end : depth -=1
leading = []
const = 0
coeff = start // 10 ** depth
while depth >= 0:
while (end - const - coeff * 10 ** depth) >= 10 ** depth:
leading.append(str(const / 10 ** depth + coeff) + "X" * depth)
coeff += 1
const += coeff * 10 ** depth
coeff = 0
depth -= 1
leading.append(end)
return leading
print leading(199,411)
print leading(2169800, 2171194)
print leading(1000, 1453)
print leading(1,12)
Now, let me try to explain the approach here.
The algorithm will try to find "end" starting from value "start" and check whether "end" is in the next 10^2 (which is 100 in this case). If it fails, it will make a leap of 10^2 until it succeeds. When it succeeds it will go one depth level lower. That is, it will make leaps one order of magnitude smaller. And loop that way until the depth is equal to zero (= leaps of 10^0 = 1). The algorithm stops when it reaches the "end" value.
You may also notice that I have the implemented the wrapping loop I mentioned so it is now possible to define the starting depth (or leap size) in a variable.
The first while loop makes sure the first leap does not overshoot the "end" value.
If you have any questions, just feel free to ask.