Convert tuple of tuples of floats to ints - python-3.x

Convert
((2.0,3.1),(7.0,4.2),(8.9,1.0),(-8.9,7))
to
((2,3),(7,4),(8,1),(-8,7))
It works to convert the tuple to a numpy array, and then apply .astype(int), but is there a more direct way? Also my 'solution' seems too special.
It works to use numpy
import numpy
data = ((2.0,3.1),(7.0,4.2),(8.9,1.0),(-8.9,7))
data1 = numpy.array(data)
data2 = data1.astype(int)
data3 = tuple(tuple(row) for row in data2)
data3 # ((2, 3), (7, 4), (8, 1), (-8, 7))
((2, 3), (7, 4), (8, 1), (-8, 7))
as expected and desired

In [16]: t = ((2.0,3.1),(7.0,4.2),(8.9,1.0),(-8.9,7))
In [17]: tuple(tuple(map(int, tup)) for tup in t)
Out[17]: ((2, 3), (7, 4), (8, 1), (-8, 7))

Using a simple list comprehension:
result = [(int(element[0]), int(element[1])) for element in t]
If you need it back as a tuple, just convert the list into a tuple:
result = tuple([(int(element[0]), int(element[1])) for element in t])

Related

MILP: Formulating a sorted list for a constraint

For a MILP project planning problem I would like to formulate the constraint that activity i must be finished before activity j starts. The activities are to be ordered by duration p and the one of three modes m per activity is to be used which takes the shortest time.
So I created a dictionary with the minimum durations of activity i in mode m.
p_im_min = {i: np.min([p[i,m] for m in M_i[i]]) for i in V}
Then I sorted the durations by size:
p_sort = (sorted(p_im_min.items(), key = lambda kv: kv[1]))
Which gives (i,p) in the right order:
p_sort = [(0, 0),
(3, 1),
(4, 1),
(5, 1),
(7, 1),
(13, 1),
(14, 1),
(15, 1),
(19, 1),
(1, 2),
(2, 2),
(8, 2),
(16, 2),
(17, 2),
(18, 2),
(20, 2),
(6, 3),
(10, 3),
(9, 4),
(12, 4),
(11, 5)]
But now I want a list with (i,j), where i must always be finished before j starts. Since I could not find the function, I created this list manually, thus
order_act = [(0,3),
(3,4),
(4,5),
(5,7), etc.
And finally (after formulating the parameters, variables and sets) added the following constraint:
mdl.addConstrs(y[i,j] == 1
for (i,j) in order_act)
My question:
Is there any way to use a formula/command in Python to create the list (i,j)? Because as it is now, it is not ideal and the solution is not satisfactory.

I have an issue in Python Lists,how to solve it?

I want a code in Python lists,to get all the possibility in a given list without using any built in functions.
example = [1,2,3]
def expandList(ex):
rslt = []
for i in range(len(ex)):
for j in range(len(ex)):
rslt.append((ex[i], ex[j]))
return rslt
expandList(example)
Yields:
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
If you are going for each permutation, you would use nested for loops. Example:
permutations = list()
for item in myList:
for item2 in myList:
permutations.append((item, item2))
This code will create a list of permutations.

W0640: Cell variable month_ defined in loop (cell-var-from-loop) - pylint

I have some code like this but I got error from pylint and I don't know what's wrong with it and what should I do
tuples = ((1, 2), (4, 5), (7, 8))
for tuple_ in tuples:
df[df["date"].apply(lambda d:(d.month==tup[1]) & (d.year==tup[0]))].count()[0]
df is a pandas dataframe and "date" column is pandas datetime
code works well but there is error message from pylint
Update:
I just created small function that could remove pylint error but I want to know if my approach is a right one!
tuples = ((1, 2), (4, 5), (7, 8))
def _group_date(df_, tup_):
return df[df["date"].apply(lambda d:(d.month==tup[1]) & (d.year==tup[0]))].count()[0]
dict_ = {}
for tuple_ in tuples:
dict_[f"{tuple_ }"] = _group_date(df, tuple_ )

Check if the product of two consecutive list numbers equals another number

The code prints out 2 and 3 because their product equals the variable num. But what if l=[1,3,4,5,6,7,8,9,10]? No numbers in the list multiplied equal 6,so I'd like to print the two closest ones.
l=[1,2,3,4,5,6,7,8,9,10]
num=6
index=0
while index+1<len(l):
if l[index]*l[index+1]==num:
print(l[index],l[index+1])
index+=1
You can do this with an easy expression with min:
First we use zip to build an iterator for consecutive elements: zip(l, l[1:])
Then we use min with the key being the distance from num:
min(zip(l, l[1:]), key = lambda x: abs(x[0]*x[1]-num))
If l = [1,2,3,4,5,6,7,8,9,10]
Output:
(2, 3)
If l = [1,3,4,5,6,7,8,9,10]
Output:
(1, 3)
If you want to get more outputs consider using sorted in the same manner to get a ranking:
sorted(zip(l, l[1:]), key = lambda x: abs(x[0]*x[1]-num))
If l = [1,3,4,5,6,7,8,9,10]
Output:
[(1, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
If l = [1,2,3,4,5,6,7,8,9,10]
Output:
[(2, 3), (1, 2), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
To find the index for the pair whose product is closest to num you can do:
Code:
min((abs(x*y - num), i) for i, (x, y) in enumerate(zip(l, l[1:])))[1]
Say what?
This uses a generator expression and min() to find the pair whose product is closest to num. In that chain is:
zip(l, l[1:])
which produces a tuple for each neighbor pair. Then enumerate is used to also produce the index. Then the absolute value of the product - num is passed to min()

Connectivity between two items having an intermediate item as the connection in python

This is the code that i have written which basically describes the flight connectivity having one city in common between the source and the destination. It seems right for most of the test cases but isn't satisfying this particular one.
def onehop(lis):
hop=[]
for (i,j) in lis:
for (k,l) in lis:
if i==k and j!=l:
return sorted(lis)
if (i!=k and j!=l)and(i==l or j==k) and (((i,j) not in hop) and ((k,l) not in hop)):
m=lis.pop(lis.index((i,j)))
n=lis.pop(lis.index((k,l)))
hop.extend([m,n])
for i in range(len(hop)):
if hop[i][0]>hop[i][1]:
hop[i]=(hop[i][1],hop[i][0])
ans=sorted(hop,key=lambda item: (item[0],item[1]))
return ans
onehop([(2,3),(1,2),(3,1),(1,3),(3,2),(2,4),(4,1)])
Output I expected:
[(1, 2), (1, 3), (1, 4), (2, 1), (3, 2), (3, 4), (4, 2), (4, 3)]
Output I obtained:
[(1, 2), (1, 3), (2, 3), (2, 4), (3, 1), (3, 2), (4, 1)]
def onehop(lis):
hop=[]
for (i,j) in lis:
for (k,l) in lis:
if j==k and i!=l :
hop.append([i,l])
unique = [list(x) for x in set(tuple(x) for x in hop)]
ans=sorted(unique,key=lambda item: (item[0],item[1]))
ans1 = [tuple(l) for l in ans]
return(ans1)

Resources