How to take input into python 2d array using map and split because in competitive coding competition the inputs are given with space?
Is it the correct way to use?
a = numpy.empty((N,M))
for i in range(N):
b=list(map(int,input().split()))
a.append(b)
a.append('\n')
The original question is a bit confused. If you want to store it in a numpy array, I'd be inclined to use np.genfromtxt:
import io
import numpy as np
input = b"""\
1 2 3 4
5 6 7 8"""
if __name__ == '__main__':
print(np.genfromtxt(io.BytesIO(input)))
If, on the other hand, you want to store it in a list of list (although I can't see why this is preferable to a numpy array), this sort of approach should work:
import io
input = b"""\
1 2 3 4
5 6 7 8"""
if __name__ == '__main__':
list_of_lists = [[int(elt) for elt in line.split()] for line in io.BytesIO(input)]
print(list_of_lists)
Related
I'd like to produce a boxplot similar to that which is found here. Instead of by indexing by the month I'd like to index by the Question, that is, for each of the 12 Questions produced I'd like to have each question shown along with it's particular possible classes (similar to value_vars=["A", "B"] in the linked example). However, instead of just having the two possible classes, "A" and "B" for each of the Questions, I'd like to have each of the classes being "1" through "5" in which each class has the number of occurrences of each of the possible question values e.g. the number of 1's, 2's etc. for each question. To try to be a little more clear, I've included a picture of what I'm trying to achieve:
The issue that I'm having is that I don't know how to create the correct index scheme and how to melt the classes together.
import random
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def SeverityvsFives(df):
df['question']= df.index.???
df_plot = df.melt(id_vars='question', value_vars=["1","2","3","4","5"])
sns.boxplot(x='question', y='value', hue='variable', data=df_plot)
plt.show()
n = 500
m = 12
columnnames = [str("Question_"+ str(j+1)) for j in range(m)]
a = [[random.randint(1, 5) for j in range(m)] for i in range(n)]
df = pd.DataFrame(data = a, columns = columnnames, index= ???)
SeverityvsFives(df)
I need some help regarding the coding using python.
Here is the problem.
Let say I have an array (size = (50,50)) containing float numbers. I would like to find the minimum value for every cluster of cells (size = (10,10)). So in total, I will have 25 values.
This is what I did so far, maybe there is another way to do it so that the program could run faster since I need it to handle a quite big array (let say 1 mil x 1 mill of cells).
import numpy as np
import random
def mini_cluster(z,y,x):
a = []
for i in range(y,y+10):
for j in range(x,x+10):
a.append(z[i,j])
return min(a)
z = np.zeros(shape=(50,50))
for i in range (len(z)):
for j in range(len(z)):
z[i,j] = random.uniform(10,12.5)
mini = []
for i in range(0,len(z),10):
for j in range(0,len(z),10):
mini.append(mini_cluster(z,i,j))
I am not sure of its speed but using numpy slicing should simplify your work.
you can avoid all those for loops.
here is some sample code
import numpy as np
arr=[[1,2,3,8],[4,5,6,7],[8,9,10,11],[0,3,5,9]]
arr_np = np.array(arr)
print(arr_np)
cluster= arr_np[:3,:3]
print('\n')
print(cluster)
print('\n')
print(np.amin(cluster))
[[ 1 2 3 8]
[ 4 5 6 7]
[ 8 9 10 11]
[ 0 3 5 9]]
[[ 1 2 3]
[ 4 5 6]
[ 8 9 10]]
1
you can also check this tutorial
I'm trying to generate the initial population for a genetic algorithm. I need to generate 20 random binary strings of length 18. I have been able to generate just one chain. My question is: How do I use another loop in order to generate the 20 strings that I need?
I think that this could solved using nested loops. I've tried to do that but I don't know how to use them correctly.
import random
binaryString = []
for i in range(0, 18):
x = str(random.randint(0, 1))
binaryString.append(x)
print (''.join(binaryString))
import numpy as geek
num_bits = 18
individualsPer_pop = 20
#Defining the population size
pop_size = (individualsPer_pop,num_bits) # The population will have
individualsPer-pop chromosome where each chromosome has num_bits genes.
#Creating the initial population.
new_population = geek.random.randint(low = 0, high = 2, size = pop_size)
print(new_population)
I have 2 pandas data Series that I know are the same length. Each Series contains sets() in each element. I want to figure out a computationally efficient way to get the element wise union of these two Series' sets. I've created a simplified version of the code with fake and short Series to play with below. This implementation is a VERY inefficient way of doing this. There has GOT to be a faster way to do this. My real Series are much longer and I have to do this operation hundreds of thousands of times.
import pandas as pd
set_series_1 = pd.Series([{1,2,3}, {'a','b'}, {2.3, 5.4}])
set_series_2 = pd.Series([{2,4,7}, {'a','f','g'}, {0.0, 15.6}])
n = set_series_1.shape[0]
for i in range(0,n):
set_series_1[i] = set_series_1[i].union(set_series_2[i])
print set_series_1
>>> set_series_1
0 set([1, 2, 3, 4, 7])
1 set([a, b, g, f])
2 set([0.0, 2.3, 15.6, 5.4])
dtype: object
I've tried combining the Series into a data frame and using the apply function, but I get an error saying that sets are not supported as dataframe elements.
pir4
After testing several options, I finally came up with a good one... pir4 below.
Testing
def jed1(s1, s2):
s = s1.copy()
n = s1.shape[0]
for i in range(n):
s[i] = s2[i].union(s1[i])
return s
def pir1(s1, s2):
return pd.Series([item.union(s2[i]) for i, item in enumerate(s1.values)], s1.index)
def pir2(s1, s2):
return pd.Series([item.union(s2[i]) for i, item in s1.iteritems()], s1.index)
def pir3(s1, s2):
return s1.apply(list).add(s2.apply(list)).apply(set)
def pir4(s1, s2):
return pd.Series([set.union(*z) for z in zip(s1, s2)])
from random import randint
List = [randint(0,99)*20]
print(List)
How could i go along the lines of make it into a list for 20 different random numbers between 0 and 99? The code i have ends up multiplying one random number 20 times.
You can use list comprehension:
List = [randint(0,99) for i in range(20)]
from random import randint
List = [randint(0,99) for i in range(20)]
print("%3s" % List)
List.sort()
print("%3s" % List)
My primary is Java. I hope this helps!