How to write a cycle for creating numpy arrays? - python-3.x

How to write this in cycle, please?
k1 = np.empty(np.shape(u))
k2 = np.empty(np.shape(u))
k3 = np.empty(np.shape(u))
k4 = np.empty(np.shape(u))
I tried:
k = [k1, k2, k3, k4]
for i in k:
i = np.empty(np.shape(u))
k.append(i)

You can simply use list comprehension to create an arbitrary number of empty numpy arrays
num = 10
result = [np.empty(np.shape(u)) for _ in range(num)]

It is not a good practice to do this, so I would recommend using lists or dictionaries but here's the code to achieve what you asked for-
for x in range(0, n): #Replace n with the value you need
globals()['k%s' % x] = np.empty(np.shape(u))
and then for example:
print(k1)
But again this is a bad practice, use dictionaries instead

Related

How to compute the average of a string of floats

temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"
I am stuck in this assignment and unable to find a relevant answer to help.
I’ve used .split(",") and float()
and I am still stuck here.
temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"
li = temp.split(",")
def avr(li):
av = 0
for i in li:
av += float(i)
return av/len(li)
print(avr(li))
You can use sum() to add the elements of a tuple of floats:
temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"
def average (s_vals):
vals = tuple ( float(v) for v in s_vals.split(",") )
return sum(vals) / len(vals)
print (average(temp))
Admittedly similar to the answer by #emacsdrivesmenuts (GMTA).
However, opting to use the efficient map function which should scale nicely for larger strings. This approach removes the for loop and explicit float() conversion of each value, and passes these operations to the lower-level (highly optimised) C implementation.
For example:
def mean(s):
vals = tuple(map(float, s.split(',')))
return sum(vals) / len(vals)
Example use:
temp = '75.1,77.7,83.2,82.5,81.0,79.5,85.7'
mean(temp)
>>> 80.67142857142858

Intersecting two Dictionaries and getting average scores

I have 2 python dictionaries, and each dictionary has a city name and a score of that city.
I need to compare both the dictionaries in order to find the city with max score.Hence, for this I first take intersection of both the dictionaries to get common cities.This is where I am facing issues.
For example, lets say the two dictionaries are:
d1 = {"delhi": 40, "Jaipur": 50, "Gurgaon": 10}
d2 = {"Jaipur(Rajasthan)": 30, "Gurugram(Gurgaon)": 25}
Here because of brackets or the city has some extra string along with it, the intersection fails.
So my question is , Is there any way where in if a city is present partly in a string, it is taken into the intersection?
Also, in the end I need to give the city an average score.
I want the end result to be:
d3 = {"gurgaon": 17.5((10 + 25) / 2), "jaipur": 40(80 / 2)}
How would I achieve this?
You can create normalized dicts where the keys used for matching are extracted from the original keys. Since names both inside and outside parentheses in the keys of the input dicts can be used for matching, create redundant keys for both names in the normalized dict:
import re
n1, n2 = (
{t.lower(): v for k, v in d.items() for t in re.findall('[^()]+', k)}
for d in (d1, d2)
)
print({k: (n1[k] + n2[k]) / 2 for k in n1.keys() & n2.keys()})
This outputs:
{'gurgaon': 17.5, 'jaipur': 40.0}
If you only have to compare two dicts you can do something like this using the filter function:
def get_avg_scores(d1, d2):
d3 = {}
for key, item in d1.items():
# Get match key d1 vs. d2
d2_similar_key = list(filter(lambda x: key.lower() in x.lower(), d2.keys()))
#Get match key d2 vs. d1
d2_similar_key_rev = list(filter(lambda x: x.lower() in key.lower(), d2.keys()))
# Keep the simplest key (to avoid bracets in d3)
if len(d2_similar_key) > 0:
d3[key] = (item + d2[d2_similar_key[0]])/2
if len(d2_similar_key_rev) > 0:
d3[d2_similar_key_rev[0]] = (item + d2[d2_similar_key_rev[0]])/2
return d3
d3 = get_avg_scores(d1, d2)

How can i optimise my code and make it readable?

The task is:
User enters a number, you take 1 number from the left, one from the right and sum it. Then you take the rest of this number and sum every digit in it. then you get two answers. You have to sort them from biggest to lowest and make them into a one solid number. I solved it, but i don't like how it looks like. i mean the task is pretty simple but my code looks like trash. Maybe i should use some more built-in functions and libraries. If so, could you please advise me some? Thank you
a = int(input())
b = [int(i) for i in str(a)]
closesum = 0
d = []
e = ""
farsum = b[0] + b[-1]
print(farsum)
b.pop(0)
b.pop(-1)
print(b)
for i in b:
closesum += i
print(closesum)
d.append(int(closesum))
d.append(int(farsum))
print(d)
for i in sorted(d, reverse = True):
e += str(i)
print(int(e))
input()
You can use reduce
from functools import reduce
a = [0,1,2,3,4,5,6,7,8,9]
print(reduce(lambda x, y: x + y, a))
# 45
and you can just pass in a shortened list instead of poping elements: b[1:-1]
The first two lines:
str_input = input() # input will always read strings
num_list = [int(i) for i in str_input]
the for loop at the end is useless and there is no need to sort only 2 elements. You can just use a simple if..else condition to print what you want.
You don't need a loop to sum a slice of a list. You can also use join to concatenate a list of strings without looping. This implementation converts to string before sorting (the result would be the same). You could convert to string after sorting using map(str,...)
farsum = b[0] + b[-1]
closesum = sum(b[1:-2])
"".join(sorted((str(farsum),str(closesum)),reverse=True))

Replacing list in list of list , gives only zeros

I have a matrice (list of list) say a and I want to normalize each "row" such that each element corresponds to the fraction of the corresponding row, i.e [p/sum(p) for p in row].
I have the following code
a_norm[:] = a
for i,row in enumerate(a_norm):
b = [p/sum(row) for p in row]
print(b)
a_norm[i] = b
the rows being printed (print(b)) are completely fine but a_norm consists of purely zeros for some reason.
EDIT: Adding an example.
a=np.array([[1,2,3], [20,22,13]]) should give a_norm=[[0.16,0.33,0.5],[0.36,0.4,0.24]]
try this one:
a_norm = [[i / sum(row) for i in row] for row in a]
Mistake you did in making list copy.
use a_norm = a[:] instead of a_norm[:] = a
You can try:
a_norm = a[:]
for i, row in enumerate(a_norm):
b = [p/sum(row) for p in row]
print(b)
a_norm[i] = b
print(a_norm)

How to apply multiprocessing in python3.x for the following nested loop

for i in range(1,row):
for j in range(1,col):
if i > j and i != j:
x = Aglo[0][i][0]
y = Aglo[j][0][0]
Aglo[j][i] = offset.myfun(x,y)
Aglo[i][j] = Aglo[j][i]
Aglo[][] is a 2D array, which consists of lists in the first row
offset.myfun() is a function defined elsewhere
This might be a trivial question but i couldn't understand how to use multiprocessing for these nested loops as x,y (used in myfun()) is different for each process(if multiprocessing is used)
Thank you
If I'm reading your code right, you are not overwriting any previously calculated values. If that's true, then you can use multiprocessing. If not, then you can't guarantee that the results from multiprocessing will be in the correct order.
To use something like multiprocessing.Pool, you would need to gather all valid (x, y) pairs to pass to offset.myfun(). Something like this might work (untested):
pairs = [(i, j, Aglo[0][i][0], Aglo[j][0][0]) for i in range(1, row) for j in range(1, col) if i > j and i != j]
# offset.myfun now needs to take a tuple instead of x, y
# it additionally needs to emit i and j in addition to the return value
# e.g. (i, j, result)
p = Pool(4)
results = p.map(offset.myfun, pairs)
# fill in Aglo with the results
for pair in pairs:
i, j, value = pair
Aglo[i][j] = value
Aglo[j][i] = value
You will need to pass in i and j to offset.myfun because otherwise there is no way to know which result goes where. offset.myfun should then return i and j along with the result so you can fill in Aglo appropriately. Hope this helps.

Resources