Elements of a list - python-2.7

Hi please how can I add other elements ie z[i], in z in the last line of this code
z = [2,3,4,5]
my_file.write('%s' % j + 'a' + ':' + str(z[0]) + ',')#z[0] = first element in z
Thanks

smth like that?
z = [2,3,4,5]
with open("output.txt", 'w') as my_file:
my_file.write('a: %s' % ', '.join([str(i) for i in z]))
output.txt:
a: 2, 3, 4, 5

Related

How to get all solutions for an integer program in ortools?

I am trying to get all solutions for a Mixed Integer program through ortools. I have two lists x and y of size 4. I want to get all solutions which satisfy sum(x) = 4 * sum(y). I created a function which takes list of past solutions as input and returns next solution. I am able to get only 2 solutions even though there are more. What am I doing wrong here?
I am expecting the following solutions
Solution 1:
xs1 = [0,0,0,0], ys1 = [0,0,0,0]
Solution 2:
xs2 = [4,0,0,0], ys2 = [1,0,0,0]
Solution 3:
xs3 = [0,4,0,0], ys3 = [1,0,0,0]
Solution 4:
xs4 = [0,0,4,0], ys4 = [0,0,1,0]
and soon on
from ortools.linear_solver import pywraplp
def opt(xs, ys):
solver = pywraplp.Solver.CreateSolver('SCIP')
infinity = solver.infinity()
# x and y are integer non-negative variables.
n = 4
M = 20
x = [0]* n
y = [0]* n
w = [[0]* n]*len(xs)
δ = [[0]* n]*len(xs)
for i in range(0,n):
x[i] = solver.IntVar(0, 20, 'x'+str(i))
y[i] = solver.IntVar(0, 20, 'y'+str(i))
for j in range(len(xs)):
w[j][i] = solver.IntVar(0, 20, 'zp'+str(j)+ '-' + str(i))
δ[j][i] = solver.IntVar(0, 1, 'δ'+str(j)+ '-' + str(i))
for j in (range(len(xs))):
for i in range(0,n):
solver.Add((w[j][i] - x[i] + xs[j][i]) >=0)
solver.Add((w[j][i] - x[i] + xs[j][i]) <= M*(1-δ[j][i]))
solver.Add((w[j][i] + x[i] - xs[j][i]) >=0)
solver.Add((w[j][i] + x[i] - xs[j][i]) <= M*δ[j][i])
for j in range(len(xs)):
solver.Add(solver.Sum([w[j][i] for i in range(0,n)]) >= 1)
solver.Add(solver.Sum([x[i] for i in range(0, n)]) - 4 * solver.Sum([y[i] for i in range(0, n)]) == 0)
solver.Minimize(solver.Sum([x[i] for i in range(0, n)]))
status = solver.Solve()
if status == pywraplp.Solver.OPTIMAL:
solver_x = [0]*n
solver_y = [0]*n
for i in range(0,n):
solver_x[i] = x[i].solution_value()
solver_y[i] = y[i].solution_value()
return ([solver_x, solver_y, solver.Objective().Value()])
else:
print('No Solution')
return ([[0], [0]], -1)
psx = [[0,0,0,0], [0,4,0,0]]
psy = [[0,0,0,0], [1,0,0,0]]
ns = opt(psx, psy)
print(ns)
Output:
No Solution
([[0], [0]], -1)
Reference:
Finding multiple solutions to general integer linear programs
How to write constraints for sum of absolutes
If you have a pure integer programming model, you can use the CP-SAT solver which allows you to print all the solutions [See this].

Add and subtract from two list following if-else condition in Python

Here is what I have tried
c = ['8781' ,'2740', '1413', '3060', '5074']
d = ['8853' ,'2812', '1355', '2986', '5107']
start = map(int, c)
end = map(int, d)
for n,m in zip(start,end):
if n < m:
preS = map(lambda x:x-21, start)
preE = map(lambda x:x+20, end)
print (preS, preE)
else:
preS = map(lambda x:x-20, end)
preE = map(lambda x:x+20, start)
print (preS, preE)
Here my else part of loop is not executing and I got multiple lines of same output. Whats wrong here?
I am expecting in following way:
preS preE
8760 8873
2719 2832
1433 1335
3080 2966
5053 5127
I get the following output:
([8760, 2719, 1392, 3039, 5053], [8873, 2832, 1375, 3006, 5127])
([8739, 2698, 1371, 3018, 5032], [8893, 2852, 1395, 3026, 5147])
([8719, 2678, 1351, 2998, 5012], [8913, 2872, 1415, 3046, 5167])
([8719, 2678, 1351, 2998, 5012], [8913, 2872, 1415, 3046, 5167])
([8718, 2677, 1350, 2997, 5011], [8913, 2872, 1415, 3046, 5167])
I would really appreciate for answers.
You are updating and printing the whole result lists in each iteration. The result from the last iteration "wins", and all elements in the result from the earlier iterations are overwritten.
Instead, you need to handle the elements individually, and only print the result once at the end:
preS = []
preE = []
for n, m in zip(start, end):
if n < m:
preS.append(n - 21)
preE.append(m + 20)
else:
preS.append(n - 20)
preE.append(m + 20)
print preS, preE
The whole thing can be expressed more concisely by a list comprehension:
preS, preE = zip(*[(n - 21, m + 20) if n < m else (n - 20, m + 20)
for n, m in zip(start, end)])
It uses the zip(*list) idiom to transpose the list of pairs.

Selecting only one row at a time for iteration in PANDAS-PYTHON

I have this following code and a text file with 5 (X and Y) values The Image of the text file is here. I need to iterate 1000 times for every X and Y value. How can I achieve this?
import pandas as pd
data = pd.read_csv("test.txt", delim_whitespace=True, skipinitialspace=True,)
for every line in the text document:
for i in range(1, 1001, 1):
z = data["X"] + data["Y"]
z = z + 10
print z
The text file is like
X Y
1 10
2 20
3 30
4 40
5 50
The output must be:
10011
10022
10033
10044
10055
You can select one row at the time using .loc. Please read this documentation to fully understand how this work. Here is your data:
import pandas as pd
df = pd.DataFrame({'X':['1','2','3','4','5'], 'Y': ['10','20','30','40','50']})
This code
print df.loc[0]
will give you the first row (with index=0) as a pandas series (pd.Series), which is essentially like a dataframe with one column only: a vector.
X 1
Y 10
Name: 0, dtype: object
If you want the second row then: df.loc[1] and so on...
If you want to iterate one row at the time, you can select each row in the first for loop and perform your operations 1000 times in the second for loop:
for ix in df.index: # df.index gives [0,1,2,3,4]
for i in xrange(0,1000):
ser = df.loc[ix]
print ser['X'] + ser['Y'] + '10'
Try this,
data = pd.DataFrame({'X': [1, 2, 3, 4, 5], 'Y': [10,20,30,40,50]})
for each_line in data.index:
z = data['X'].loc[each_line] + data['Y'].loc[each_line]
for i in range(1,1001,1):
z +=10
print(z)
Output
10011
10022
10033
10044
10055
if you want to add new column to dataFrame:
data["total"] = sorted(set([(data.loc[ix]['X'].astype(int) + data.loc[ix]['Y'].astype(int)).astype(str) +"10" for ix in data.index for i in range(1,1001)]))
if you want concatenate the 'X' and 'Y' +'10' then:
[data.loc[ix]['X'].astype(str) + data.loc[ix]['Y'].astype(str) +"10" for ix in data.index for i in range(1,1001)]
And if you want to sum of 'X' + 'Y' and concat + '10' then:
final_data = [(data.loc[ix]['X'].astype(int) + data.loc[ix]['Y'].astype(int)).astype(str) +"10" for ix in data.index for i in range(1,1001)]

python: The word in List can't be removed

As you can see, i'm trying to delete the word in a list whose length is 1 or 2, but "P" and "ye" can't be found and removed!
Check out this code:
li = ['of','in','a','bb','abbb']
lii = []
for i in li:
j = len(i)
if j == 1 or j == 2:
lii.append(i)
for i in lii:
li.remove(i)
print li
Output:
['abbb']
You can't modify list while you iterate through it.
But you can do something like this:
L = ['of', 'P', 'representig', 'the', 'subs', 'et', 'ye', 'ti']
result = [i for i in L if len(i) != 1 and len(i) != 2]

Modify fibonacci python in order to print f(0),f(1),.....f(n)

Here is my original function.
def f(n):
if n<0:
print("Error.Bad input")
elif n==0:
return 1
elif n==1:
return 1
else:
return f(n-1)+f(n-2)
Is it possible to modify Fibonacci Python function so that not only does it have to calculate f(n) but also it prints f(0), f(1), f(2),....,f(n) in the function?
Instead of using a recursive function you could do this:
def f(n):
if n < 0:
print("Error.Bad input")
elif n <= 1:
return 1
else:
result = [1, 2]
print(1)
print(2)
for i in range(n - 2):
result = [result[1], result[0] + result[1]]
print(result[1])
return result[1]
def fib(n):
pred, curr = 0, 1
k = 1
while (k<n):
pred, curr = curr, curr + pred
print(curr)
k = k + 1
Probably the optimal "pythonic" way to create a sequence (a list) of fibonacci numbers of arbitraly size n is to define a function which does so, than to call that function with size as an input argument. For example:
def fibonacci_sequence(n):
x = [0, 1]
[x.append(x[-1] + x[-2]) for i in range(n - len(x))]
return x
fibonacci_sequence(15)
The result is:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Bottom-up approach. Complexity is O(n):
def fib(n):
if n in (1, 2):
return 1
i = z = 1
for _ in range(3, n+1):
z, i = i + z, z
return z