How to use while loop inside a function? - while-loop

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]

Related

Sum Up all Numbers before and after an operator Sign in a String user input

i am new to programming and starting up with kotlin . i've been stuck on this problem for a few days and i really need some assistance . i am trying to read a user input of Strings in a format like this 3 + 2 + 1, go through the String and wherever there is an operator , add up the numbers before and after the operator sign . so the above 3 + 2 + 1 should output 6.
Here's a snippet of my code
fun main() {
val userInput = readLine()!!.split(" ")
var sum = 0
for (i in 0 until userInput.size) {
if (userInput.get(i) == "+"){
sum += userInput.get(i-1).toInt() + userInput.get(i+1).toInt()
}
}
println(sum )
}
my code works until the point of adding up the numbers . it repeats the next number after the operator , so using the above example of 3 + 2 + 1 it outputs 8 thus 3 + 2 + 2 + 1. I'm so confused and don't know how to go about this .
Try not to increment the sum value each time, but rewrite the last number which was participated in sum. Just like that:
You have the case: 1 + 2 + 3 + 4
Split them
Now you have the array [1, +, 2, +, 3, +, 4]
Then you iterate this array, stuck with the first plus and sum the values.
Rewrite the second summed value with your sum.
Now you have new array [1, +, 3, +, 3, +, 4]
At the end of the loop, you will have this array [1, +, 3, +, 6, +, 10]
And your sum is the last element of the array
The logic of your code is that for each "+" encountered, it adds the sum of the numbers left and right of the "+" to the sum. For the example "1 + 2 + 3", here's what is happening:
Starting sum is 0.
At first "+", add 1 + 2 to sum, so now sum is 3.
At second "+", add 2 + 3 to sum, so now the sum is 3 + 5 = 8.
So you are adding all the middle numbers to the total twice, because they each appear next to two operators.
One way to do this is start with the first number as your sum. Then add only the number to the right of each "+", so numbers are only counted once.
fun main() {
val userInput = readLine()!!.split(" ")
var sum = userInput[0].toInt()
for (i in userInput.indices) {
if (userInput[i] == "+") {
sum += userInput[i + 1].toInt()
}
}
println(sum)
}
sum += userInput.get(i-1).toInt() + userInput.get(i+1).toInt()
This is only valid for the first iteration, so if the user puts 1 + 2 + 3.
So
userInput[0] is 1
userInput[1] is +...
the first time that line will be triggered sum will be 1 + 2, and that's quite fine, but the second time, in the second +, you will sum i-1 (which is 2 and was in the total sum already) and i+1, that will be 3, so you are doing 1+2+2+3.
You need to understand why this is happening and think of another way to implement it.
Check this is working for me
var sum = 0
readLine()?.split(" ")?.filter { it.toIntOrNull() != null }?.map { sum += it.toInt() }
println(sum)

Lua, how to access an index that uses an array

How can I check an array inside an index? [{4, 8}] to confirm if 'vocation' aka 8 exists?
local outfits = {
[7995] = {
[{1, 5}] = {94210, 1},
[{2, 6}] = {94210, 1},
[{3, 7}] = {94210, 1},
[{4, 8}] = {94210, 1}
}
}
local item = 7995
local vocation = 8
if outfits[item] then
local index = outfits[item]
--for i = 1, #index do
-- for n = 1, #index[i]
-- if index[i]
-- ????
end
You just need to iterate using pairs rather than a basic for loop.
With pairs you get your key value pairs and can then loop over the key to inspect it's contents.
local found = 0
if outfits[item] then
local value = outfits[item]
for k, v in pairs(value) do
for n = 1, #k do
if k[n] == vocation then
found = k
break;
end
end
end
end
print(outfits[item][found][1])
That said this is not the a very efficient method of storing values for look up and wont scale well for larger groups of record.

Calculate time complexity for the following snippet

Can someone please calculate the the no. of steps it will take to execute the above code?
And verify the solution, with some input values of n.
(found some relevant question, but not helping)
int count=0;
for(int i=1; i<=n ;i=i*2)
{
for(int j=1; j<=i; j=j*2)
{
count++;
}
}
We can make a table:
i = 1: j = 1 --> 1 count
i = 2: j = 1,2 --> 2 counts
i = 4: j = 1,2,4 --> 3 counts
i = 8: j = 1,2,4,8 --> 4 counts
The pattern should be clear from here. We can reimagine the pattern such that i = 1, 2, 3, 4, ..., and instead of going from 1 to n, let's just say it goes from 1 to log n. This means that the total count should be the sum from i = 1 to log (base 2) n of i. The sum from i = 1 to x of i is simply x(x+1)/2, so if x = log_2(n), then this sum is simply (log_2(n) * log_2(n)+1)/2
EDIT: It seems like I made a mistake somewhere, and what I wrote is actually f(n/2) based on empirical tests. Thus, the correct answer is actually (log_2(2n) * log_2(2n)+1)/2. Nevertheless, this is the logic I would follow to solve a problem like this
EDIT 2: Caught my mistake. Instead of saying "let's just say it goes from 1 to log n", I should have said "let's just say it goes from 0 to log n" (i.e., I need to take the log of every number in the series)
inner-loop
i = 1 --> log(1) = 0
i = 2 --> log(2) = 1
i = 4 --> log(4) = 2
i = 8 --> log(8) = 3
i = 16 -> log(16) = 4
i = 32 -> log(32) = 5
i = 64 -> log(64) = 6
.
.
.
i = n -> log(n) = log(n)
That is the amount of work and it will stop after log(n) iterations as i hits n.
1 + 2 + 3 + 4 +...+ log(n) = [(1+log(n))*log(n)]/2 = O(log^2(n))

How to declare constraints with variable as array index in Z3Py?

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.

How do I sum the coefficients of a polynomial in Maxima?

I came up with this nice thing, which I am calling 'partition function for symmetric groups'
Z[0]:1;
Z[n]:=expand(sum((n-1)!/i!*z[n-i]*Z[i], i, 0, n-1));
Z[4];
6*z[4]+8*z[1]*z[3]+3*z[2]^2+6*z[1]^2*z[2]+z[1]^4
The sum of the coefficients for Z[4] is 6+8+3+6+1 = 24 = 4!
which I am hoping corresponds to the fact that the group S4 has 6 elements like (abcd), 8 like (a)(bcd), 3 like (ab)(cd), 6 like (a)(b)(cd), and 1 like (a)(b)(c)(d)
So I thought to myself, the sum of the coefficients of Z[20] should be 20!
But life being somewhat on the short side, and fingers giving trouble, I was hoping to confirm this automatically. Can anyone help?
This sort of thing points a way:
Z[20],z[1]=1,z[2]=1,z[3]=1,z[4]=1,z[5]=1,z[6]=1,z[7]=1,z[8]=1;
But really...
I don't know a straightforward way to do that; coeff seems to handle only a single variable at a time. But here's a way to get the list you want. The basic idea is to extract the terms of Z[20] as a list, and then evaluate each term with z[1] = 1, z[2] = 1, ..., z[20] = 1.
(%i1) display2d : false $
(%i2) Z[0] : 1 $
(%i3) Z[n] := expand (sum ((n - 1)!/i!*z[n - i]*Z[i], i, 0, n-1)) $
(%i4) z1 : makelist (z[i] = 1, i, 1, 20);
(%o4) [z[1] = 1,z[2] = 1,z[3] = 1,z[4] = 1,z[5] = 1,z[6] = 1,z[7] = 1, ...]
(%i5) a : args (Z[20]);
(%o5) [121645100408832000*z[20],128047474114560000*z[1]*z[19],
67580611338240000*z[2]*z[18],67580611338240000*z[1]^2*z[18],
47703960944640000*z[3]*z[17],71555941416960000*z[1]*z[2]*z[17], ...]
(%i6) a1 : ev (a, z1);
(%o6) [121645100408832000,128047474114560000,67580611338240000, ...]
(%i7) apply ("+", a1);
(%o7) 2432902008176640000
(%i8) 20!;
(%o8) 2432902008176640000