Generate 2 random integer list of different size - python-3.x

I am trying to generate 2 list with different size consisting with random numbers. I can generate 2 list with random numbers, but how to achieve 2 different length of lists?
import random
list1 = random.sample(xrange(100), 10)
list2 = random.sample(xrange(100), 10)
print(list1)
print(list2)
Need to generate the lists with 2 random different sizes as well, as if both the lists are completely random.

Try the below code. Hope this would help.
If you want to create random number list of two different sizes. Then you can explicitly, pass the size of the list as a second argument, as given below.
import random
list1 = random.sample(xrange(100), 100)
list2 = random.sample(xrange(100), 10)
print(list1)
print(list2)
Ouput will be :
[46, 73, 13, 89, 44, 23, 74, 8, 19, 79, 36, 80, 85, 42, 82, 39, 61, 15, 27, 68, 67, 30, 11, 21, 86, 16, 63, 95, 17, 90, 37, 81, 20, 71, 93, 99, 40, 6, 47, 92, 58, 35, 12, 2, 10, 98, 87, 50, 51, 97, 70, 65, 78, 22, 72, 45, 59, 0, 52, 14, 1, 84, 43, 24, 54, 31, 18, 69, 7, 75, 53, 25, 57, 94, 83, 66, 3, 5, 88, 32, 4, 28, 29, 55, 9, 77, 60, 62, 41, 76, 48, 56, 34, 91, 33, 96, 49, 38, 26, 64]
[82, 58, 74, 61, 21, 77, 53, 35, 44, 59]
Now if you want to randomly decide the size of the list, the pass a random number as a second argument, by using randint function
import random
list1 = random.sample(range(100), random.randint(1,101))
list2 = random.sample(range(100), random.randint(1,101))
print(list1)
print(list2)
Output would be:
[93, 60, 82, 53, 16, 42, 0, 68, 88, 11, 89, 62, 38, 14, 27, 8, 45, 25, 83, 97, 94]
[30, 5, 19, 11, 14, 6, 7, 86, 16, 53, 71, 12, 90, 32]

You can try something like this, which would randomly generate the size between 1 and 10.
import random
list1 = random.sample(range(100), random.randint(1,10))
list2 = random.sample(range(100), random.randint(1,10))
print(list1)
print(list2)
This will generate random length of the lists. Hope it helps !

You need to randomize the second Parameter as well to become lists of random size:
import random
list1 = random.sample(range(100), random.randint(1,10))
list2 = random.sample(range(100), random.randint(1,10))
print(list1)
print(list2)

Related

How to divide data in excel into 4 columns whose sum is almost equal to 1/4 of the sum of all values/

I have this set of numbers.
74, 15, 60, 5, 61, 56, 4, 23, 47, 66, 20, 54, 39, 9, 34, 37, 45, 93, 85, 79, 4, 76, 85, 51, 78, 60, 95, 50, 79, 62, 21, 75, 18, 5, 79, 46, 76, 92, 11, 100, 51, 39, 80, 92, 95, 20, 62, 1, 22, 69, 65, 45, 34, 42, 40, 8, 29, 82, 38, 9, 100, 78, 22, 11, 57, 71, 38, 35, 37, 32, 19, 58, 91, 90, 91, 26, 38, 85, 96, 3, 80, 18, 32, 74, 97, 60, 65, 85, 92, 38, 12, 31, 37, 76, 84, 9, 17, 33, 20, 19
I would like to divide this set of numbers into 4 parts/columns in excel so that their sum is as close as possible to 1/4 of the value of all numbers
Total of all numbers is 5049. 1/4 equals 1262.25 .
Is the sort of thing you're after?
All those numbers, sorted numerically, then added to columns, the totals almost matching to a quarter of the total...

Showing a list empty despite performing operations on it

Actually i need to plot all the variations occured only in the october month of 2012 so for that i am counting the 30 rows so that i can use them in xlim for plotting.
import pandas as pd
from pandas import Series,DataFrame
import numpy as np
poll_df=pd.read_csv('http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama.csv')
row_in=0
xlimit=[]
poll_df=poll_df[poll_df['Start Date'].str[:7] == '2012-10']
for date in poll_df['Start Date']:
if date[0:7] == '2012-10':
xlimit.append(row_in)
row_in += 1
else:
row_in+=1
print(min(xlimit))
print(max(xlimit))
But i don't understand why xlimit is coming out empty despite performing operations on it.
With a download of that URL I can load it with np.genfromtxt:
In [232]: data = np.genfromtxt('../Downloads/2012-general-election-romney-vs-oba
...: ma.csv',dtype=None,delimiter=',',names=True,invalid_raise=False,encodi
...: ng=None)
/usr/local/bin/ipython3:1: ConversionWarning: Some errors were detected !
Line #77 (got 13 columns instead of 17)
Line #238 (got 13 columns instead of 17)
Line #460 (got 18 columns instead of 17)
Line #488 (got 18 columns instead of 17)
Line #493 (got 13 columns instead of 17)
Line #507 (got 18 columns instead of 17)
Line #515 (got 18 columns instead of 17)
Line #538 (got 18 columns instead of 17)
Line #550 (got 18 columns instead of 17)
#!/usr/bin/python3
It's not quite as forgiving as pandas when dealing with shorter/longer length lines.
In [233]: data.shape
Out[233]: (577,)
In [234]: data.dtype
Out[234]: dtype([('Pollster', '<U56'), ('Start_Date', '<U10'), ('End_Date', '<U10'), ('Entry_DateTime_ET', '<U20'), ('Number_of_Observations', '<i8'), ('Population', '<U26'), ('Mode', '<U15'), ('Obama', '<f8'), ('Romney', '<f8'), ('Undecided', '<f8'), ('Other', '<f8'), ('Pollster_URL', '<U113'), ('Source_URL', '<U189'), ('Partisan', '<U11'), ('Affiliation', '<U5'), ('Question_Text', '?'), ('Question_Iteration', '<i8')])
The start_date field looks like:
In [235]: data['Start_Date'][:10]
Out[235]:
array(['2012-11-04', '2012-11-03', '2012-11-03', '2012-11-03',
'2012-11-03', '2012-11-03', '2012-11-03', '2012-11-01',
'2012-11-02', '2012-11-02'], dtype='
I can search it with where. I'm using astype to restrict the field to 7 characters.
In [236]: np.where(data['Start_Date'].astype('U7')=='2012-10')[0]
Out[236]:
array([18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86,
87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])
I can use usecols to get around the variable line lengths - assuming the 'bad' lines just differ in the latter fields.
In [237]: data = np.genfromtxt('../Downloads/2012-general-election-romney-vs-oba
...: ma.csv',dtype=None,delimiter=',',names=True,invalid_raise=False,encodi
...: ng=None,usecols=range(10))
In [238]: data.shape
Out[238]: (586,)
In [239]: np.where(data['Start_Date'].astype('U7')=='2012-10')[0]
Out[239]:
array([ 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 99, 100])
I can get the same list with an iterative search like yours:
In [244]: alist = []
In [245]: for i,date in enumerate(data['Start_Date']):
...: if date[:7] == '2012-10':
...: alist.append(i)
...:
In [246]: len(alist)
Out[246]: 82
In [247]: np.array(alist)
Out[247]:
array([ 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 99, 100])

Identifying edges in a connected component - Python

I have a set of connected components obtained from a tree Tas follows.
To get all the connected components, I'm using the following code sample:
connectedcomponents = sorted(nx.connected_components(T), key = len,reverse=True)
This is what I'm getting;
[{66, 98, 68, 37, 7, 8, 73, 75, 44, 47, 81, 51, 19, 23, 55, 56, 58, 62, 63}, {97, 3, 6, 71, 39, 11, 77, 17, 60, 95}, {99, 5, 10, 43, 15, 20, 90, 92, 93}, {96, 4, 76, 80, 84, 53, 52}, {34, 74, 46, 18, 24, 61, 30}, {36, 9, 41, 83, 88, 57}, {65, 69, 40, 78, 21, 54}, {1, 2, 12, 13}, {89, 26, 70, 31}, {0, 42, 28, 79}, {32, 85, 86}, {59, 45, 94}, {82, 50, 22}, {64, 72}, {33, 14}, {16}, {87}, {48}, {91}, {49}, {67}, {29}, {35}, {25}, {38}, {27}]
I need to get the edges in each of these components. For an example, for the first component {66, 98, 68, 37, 7, 8, 73, 75, 44, 47, 81, 51, 19, 23, 55, 56, 58, 62, 63} I need a separate list of edges as [(37,47),(47,7),(7,62),...].
I tried it as follows:
def nodes_connected(u, v):
if u in T.neighbors(v):
return True
else:
return False
for i in connectedcomponents:
print(i)
for u,v in i:
nodes_connected("u", "v")
edges.append((u,v))
But didn't work!!!
Can someone please help me with this?

code execution using if elif statement

interface port-channel 1
ALLOWED_VLAN 2,4-7,27,30-31,38-39,41-42,48-50
ALLOWED_VLAN 74,678,1101-1102,1201-1202
interface port-channel 2
ALLOWED_VLAN 37,51-73,75-76,1051-1052,2001
interface port-channel 101
ALLOWED_VLAN 10,18-19,37,39,51-52,75-76,901-902
ALLOWED_VLAN 2901-2902,3204,3305
import re
import itertools
fileOpen3 = open('C:\\Python36\\execrice\\inter.txt')
list3 = []
for line in fileOpen3.readlines():
if line.startswith('ALLOWED_VLAN'):
allowedVlan = re.compile(r'\d+\S+')
list1 = allowedVlan.findall(line)
st1 = list1[0]
pv1 = st1.split(',')
list3.append(pv1)
merged = list(itertools.chain.from_iterable(list3))
singleVlanDigit = []
expandedVlan1 = []
for i in merged:
rangeOfVlan = []
if '-' in i:
rangeOfVlan.append(i)
else:
singleVlanDigit.append(i)
singleVlanDigit = list(map(int,singleVlanDigit))
for j in rangeOfVlan:
l = j.split('-')
startVlan = int(l[0])
endVlan = int(l[1])
for k in range(startVlan,endVlan):
expandedVlan1.append(k)
vlanallowed = singleVlanDigit + expandedVlan1
vlanallowed = list(map(int,vlanallowed))
print (vlanallowed)
elif line.startswith('interface port-channel'):
list3=[]
print ("interface port-channel")
fileOpen3.close()
my program combines all the digits in one single list where as i want it to stop when it reads the "interface port-channel 2" and so on
i want the output of this program to be as below
interface port-channel
[2, 27, 4, 5, 6, 30, 38, 41, 48, 49, 74, 678, 1101, 1201]
interface port-channel
[37, 2001, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 75, 1051]
interface port-channel
[10, 37, 39, 18, 51, 75, 901, 3204, 3305, 2901]
but it produces the below output
interface port-channel
[2, 27, 4, 5, 6, 30, 38, 41, 48, 49]
[2, 27, 74, 678, 4, 5, 6, 30, 38, 41, 48, 49, 1101, 1201]
interface port-channel
[2, 27, 74, 678, 37, 2001, 4, 5, 6, 30, 38, 41, 48, 49, 1101, 1201, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 75, 1051]
interface port-channel
[2, 27, 74, 678, 37, 2001, 10, 37, 39, 4, 5, 6, 30, 38, 41, 48, 49, 1101, 1201, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 75, 1051, 18, 51, 75, 901]
[2, 27, 74, 678, 37, 2001, 10, 37, 39, 3204, 3305, 4, 5, 6, 30, 38, 41, 48, 49, 1101, 1201, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 75, 1051, 18, 51, 75, 901, 2901]
after reinitialising the list3 in elif block as suggested by Boar i got the below results which is very to my end results
interface port-channel
[2, 27, 4, 5, 6, 30, 38, 41, 48, 49]
[2, 27, 74, 678, 4, 5, 6, 30, 38, 41, 48, 49, 1101, 1201]
interface port-channel
[37, 2001, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 75, 1051]
interface port-channel
[10, 37, 39, 18, 51, 75, 901]
[10, 37, 39, 3204, 3305, 18, 51, 75, 901, 2901]
but i want the results to be like this
interface port-channel
[2, 27, 74, 678, 4, 5, 6, 30, 38, 41, 48, 49, 1101, 1201]
interface port-channel
[37, 2001, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 75, 1051]
interface port-channel
[10, 37, 39, 3204, 3305, 18, 51, 75, 901, 2901]
I've had to guess at where the line breaks fall in your data but I think I have it right.
The repeated data is because you are initializing list3 in the wrong place. It should be after if line.startswith('ALLOWED_VLAN'):
With that fix, your program does this:
interface port-channel
[2, 27, 4, 5, 6, 30, 38, 41, 48, 49]
[74, 678, 1101, 1201]
interface port-channel
[37, 2001, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 75, 1051]
interface port-channel
[10, 37, 39, 18, 51, 75, 901]
[3204, 3305, 2901]
which is close to what you want. You just need to combine the lists of integers before printing them. Combine the values of vnlanallowed in the if part of the loop, then print it out and reinitialize it in the elif part.
To get the exact format of the output you want, you need to wait until you know you have all of the lists of port-channel numbers before printing them. You only know that when you see a new list start, or you reach end-of-file.
import re
import itertools
fileOpen3 = open(r'E:\...\inter.txt')
channel_list = []
for line in fileOpen3.readlines():
if line.startswith('ALLOWED_VLAN'):
list3 = []
allowedVlan = re.compile(r'\d+\S+')
list1 = allowedVlan.findall(line)
st1 = list1[0]
pv1 = st1.split(',')
list3.append(pv1)
merged = list(itertools.chain.from_iterable(list3))
singleVlanDigit = []
expandedVlan1 = []
for i in merged:
rangeOfVlan = []
if '-' in i:
rangeOfVlan.append(i)
else:
singleVlanDigit.append(i)
singleVlanDigit = list(map(int,singleVlanDigit))
for j in rangeOfVlan:
l = j.split('-')
startVlan = int(l[0])
endVlan = int(l[1])
for k in range(startVlan,endVlan):
expandedVlan1.append(k)
vlanallowed = singleVlanDigit + expandedVlan1
vlanallowed = list(map(int,vlanallowed))
#print (vlanallowed)
channel_list.extend(vlanallowed)
elif line.startswith('interface port-channel'):
if channel_list:
print ("interface port-channel", channel_list)
channel_list = []
print("interface port-channel", channel_list)
fileOpen3.close()

Percent groovy list slicing

my code:
def originalList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
def newList = orginalList.percent(0.05,0.95) //I have no idea what I'm doing here
println newList
I have an original list of numbers, they are 1 - 100 and i want to make a new list from the original list however the new list must only have data that belongs to the sub-range 5%- 95% of the original list
so the new list must be like [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18....95]. How do i do that? i know my newList code is wrong
You mean like:
originalList[ 4..94 ] // zero starting pos
Or do you need percentages?
You could do:
originalList[ (originalList.size() * 0.05 - 1)..<(originalList.size() * 0.95) ]
You could also use the metaClass:
List.metaClass.percent { double lower, double upper ->
int d = lower * delegate.size() - 1
int t = upper * delegate.size()
delegate.take( t ).drop( d )
}
originalList.percent( 0.05, 0.95 )

Resources