Related
if I have a Series
s = pd.Series(1, index=[1,2,3,5,6,9,10])
But, I need a standard index = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], with index[4, 7, 8] values equal to zeros.
So I expect the updated series will be
s = pd.Series([1,1,1,0,1,1,0,0,1,1], index=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
How should I update the series?
Thank you in advance!
Try this:
s.reindex(range(1,s.index.max() + 1),fill_value=0)
Output:
1 1
2 1
3 1
4 0
5 1
6 1
7 0
8 0
9 1
10 1
a matrix is given:
1 2 3 4 5 6 7 8,
8 7 6 5 4 3 2 1,
2 3 4 5 6 7 8 9,
9 8 7 6 5 4 3 2,
1 3 5 7 9 7 5 3,
3 1 5 3 2 6 5 7,
1 7 5 9 7 3 1 5,
2 6 3 5 1 7 3 2.
Define a structure for storing the matrix.
Write code that swaps the first and last rows of the matrix.
Write the code for creating a matrix of any size, filled with zeros (the size is set via the console).
Write a code that will count how many times the number 3 occurs in the matrix.
I tried solving this but My teacher says the following code is wrong. Where is my mistake??
matr = [[1, 2, 3, 4, 5, 6, 7, 8],
[8, 7, 6, 5, 4, 3, 2, 1],
[2, 3, 4, 5, 6, 7, 8, 9],
[9, 8, 7, 6, 5, 4, 3, 2],
[1, 3, 5, 7, 9, 7, 5, 3],
[3, 1, 5, 3, 2, 6, 5, 7],
[1, 7, 5, 9, 7, 3, 1, 5],
[2, 6, 3, 5, 1, 7, 3, 2]]
def will_swap_first_and_last_rows(matr):
matr[len(matr) - 1], matr[0] = matr[0], matr[len(matr) - 1]
return matr
def will_craete_matrix_of_any_size_filled_with_zeros():
m = int(input('Enter the number of rows of the matrix '))
n = int(input('enter the number of columns of the matrix '))
return [[0] * m for i in range(n)]
def will_count_how_many_times_the_number_3_occurs_in_the_matrix(matr):
s = 0
for row in matr:
for elem in row:
if elem == 3:
s += 1
return s
print(*will_swap_first_and_last_rows(matr), sep='\n')
print(will_craete_matrix_of_any_size_filled_with_zeros())
print(will_count_how_many_times_the_number_3_occurs_in_the_matrix(matr))
Your code has rows (m) and columns (n) swapped. Do it like this:
return [[0] * n for i in range(m)]
How do I arrange a list A such that the maximum number of elements of list A are greater than another list B?
EXAMPLE:
A='3 6 7 5 3 5 6 2 9 1'
B='2 7 0 9 3 6 0 6 2 6'
answer=7..................If I sort the lists,
sListA = [1, 2, 3, 3, 5, 5, 6, 6, 7, 9]
sListB = [0, 0, 2, 2, 3, 6, 6, 6, 7, 9]
#if sListA[i]>sListB[j]: count +=1
There are 5 instances where sListA[i] > sListB[j]
but we need to maximize instances where sListA[i] > sListB[j].., ie, 7
If sListA was [1, 2, 3, 3, 5, 7, 9, 5, 6, 6]
and slistB was[0, 0, 2, 2, 3, 6, 6, 6, 7, 9]
then 7 instances of sListA[i] > sListB[j] will be possible..
Heres my code:
def main():
listA=list(map(int,A.rstrip().split()))
listB=list(map(int,B.rstrip().split()))
sListA=sorted(listA)
sListB=sorted(listB)
count=0
for (i,j) in map(sListA,sListB):
if sListA[i]>sListB[j]:
count+=1
print(count)
main()
But this only counts from sorted lists, I need to find a way to swap elements with the next largest element in sListA when sListA[i]<sListB[j]
to maximize instances where sListA[i]>sListB[j]
maybe not the most efficient but you can try
a = [1, 2, 3, 3, 5, 5, 6, 6, 7, 9]
b = [0, 0, 2, 2, 3, 6, 6, 6, 7, 9]
b.sort()
a.sort()
new_a = []
for bb in b:
idx_v = np.where(np.array(a) > bb)
if idx_v[0].size == 0:
break
else:
e = a.pop(np.min(idx_v[0]))
new_a.append(e)
new_a.extend(a)
you'll find that
np.sum([new_a[n] > b[n] for n in range(len(b))])
is 7, and
new_a
[1, 2, 3, 3, 5, 7, 9, 5, 6, 6]
So in theory this should do what you wanted:
A='3 6 7 5 3 5 6 2 9 1'
B='2 7 0 9 3 6 0 6 2 6'
def main():
listA = sorted(list(map(int,A.rstrip().split())))
listB = sorted(list(map(int,B.rstrip().split())))
j = 0
for i in range(len(listA)):
if listA[i] <= listB[j]:
i += 1
else:
listA[i], listA[j] = listA[j], listA[i]
j += 1
return listA
print(main())
Returns:
[1, 2, 3, 3, 5, 7, 9, 6, 5, 6]
In essence, all I did was add an else to your if structure to keep i counting and swap elements over in listA
Previous answer (if you are interested in the outcome of 7 specifically):
A='3 6 7 5 3 5 6 2 9 1'
B='2 7 0 9 3 6 0 6 2 6'
def main():
listA = sorted(list(map(int,A.rstrip().split())))
listB = sorted(list(map(int,B.rstrip().split())))
cnt = 0
j = 0
for i in range(len(listA)):
if listA[i] > listB[j]:
cnt += 1
j += 1
else:
i += 1
return cnt
print(main())
To do this for multiple lists of A and B maybe try to apply something like:
Alist=['3 6 7 5 3 5 6 2 9 1', '9 5 3 1 0']
Blist=['2 7 0 9 3 6 0 6 2 6', '5 4 3 4 6']
def main():
cnt = 0
for x in range(len(Alist)):
listA = sorted(list(map(int,Alist[x].rstrip().split())))
listB = sorted(list(map(int,Blist[x].rstrip().split())))
j = 0
for i in range(len(listA)):
if listA[i] > listB[j]:
cnt += 1
j += 1
else:
i += 1
return cnt
print(main())
I wonder if there is a nicer way in pandas to achieve the same:
x = [1, 1, 1, 2, 2, 2, 3, 3, 3, 5, 5, 1, 1, 2, 2]
x = np.asarray(x)
df = pd.DataFrame(columns=['id', 'start', 'end'])
if len(x) > 1:
i = 0
for j in range(1, len(x)):
if x[j] == x[j-1]:
continue
else:
df.loc[len(df)] = [x[i], i, j-1]
i = j;
df.loc[len(df)] = [x[i], i, j]
else:
df.loc[len(df)] = [x[0], 0, 0]
The output looks like this
[1 1 1 2 2 2 3 3 3 5 5 1 1 2 2]
id start end
0 1 0 2
1 2 3 5
2 3 6 8
3 5 9 10
4 1 11 12
5 2 13 14
Thanks for helpful hints.
Here's a way you could do it using numpy:
x = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 5, 5, 1, 1, 2, 2])
# Search for all consecutive non equal values in the array
vals = x[x != np.roll(x, 1)]
# array([1, 2, 3, 5, 1, 2])
# Indices where changes in x occur
d = np.flatnonzero(np.diff(x) != 0)
# array([ 2, 5, 8, 10, 12])
start = np.hstack([0] + [d+1])
# array([ 0, 3, 6, 9, 11, 13])
end = np.hstack([d, len(x)-1])
# array([ 2, 5, 8, 10, 12, 14])
pd.DataFrame({'id':vals, 'start':start, 'end':end})
id start end
0 1 0 2
1 2 3 5
2 3 6 8
3 5 9 10
4 1 11 12
5 2 13 14
Another solution:
df= pd.DataFrame(data=[1, 1, 1, 2, 2, 2, 3, 3, 3, 5, 5, 1, 1, 2, 2],columns=['id'])
g=df.groupby((df.id!=df.id.shift()).cumsum())['id']
df_new=pd.concat([g.first(),g.apply(lambda x: x.duplicated(keep='last').idxmax()),\
g.apply(lambda x: x.duplicated(keep='last').idxmin())],axis=1)
df_new.columns=['id','start','end']
print(df_new)
id start end
id
1 1 0 2
2 2 3 5
3 3 6 8
4 5 9 10
5 1 11 12
6 2 13 14
You could do the following, using only pandas:
import numpy as np
import pandas as pd
x = [1, 1, 1, 2, 2, 2, 3, 3, 3, 5, 5, 1, 1, 2, 2]
s = pd.Series(x)
# store group-by to avoid repetition
groups = s.groupby((s != s.shift()).cumsum())
# get id and size for each group
ids, size = groups.first(), groups.size()
# get start
start = size.cumsum().shift().fillna(0).astype(np.int32)
# get end
end = (start + size - 1)
df = pd.DataFrame({'id': ids, 'start': start, 'end': end}, columns=['id', 'start', 'end'])
print(df)
Output
id start end
1 1 0 2
2 2 3 5
3 3 6 8
4 5 9 10
5 1 11 12
6 2 13 14
using itertools.groupby
import pandas as pd
from itertools import groupby
x = [1, 1, 1, 2, 2, 2, 3, 3, 3, 5, 5, 1, 1, 2, 2]
l = []
for i in [list(g) for _,g in groupby(enumerate(x), lambda x:x[1])]:
l.append( (i[0][1], i[0][0], i[-1][0]) )
print (pd.DataFrame(l, columns=['id','start','end']))
Output:
id start end
0 1 0 2
1 2 3 5
2 3 6 8
3 5 9 10
4 1 11 12
5 2 13 14
I am supposed to write a recursive function counting(5) that prints 5 4 3 2 1 0 1 2 3 4 5.
I have made two functions down below that do half part each but I need them to be put together.
def countdown(n):
if n == 0:
print 0
else:
print n,
countdown(n-1)
def countup(n):
if n >= 1:
countup(n - 1)
print n,
I suppose the trick is to understand the recursion point does not end execution:
def count_down_up(n):
if not n:
print n # prints 0 and terminates recursion
return
print n # print down 5, 4, 3, 2, 1
count_down_up(n-1) # recursion point
print n # prints up 1, 2, 3, 4, 5
You can see each step print n, <RECURSION>, n, which unfolds to:
5, <count_up_down 4>, 5
5, 4, <count_up_down 3>, 4, 5
# ...
5 ,4, 3, 2, 1, <count_up_down 0>, 1, 2, 3, 4, 5 # recursion stops ...
5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5
#Reut_Sharabani solution is fine but I think this is simpler to read :
def countdown(N,n):
if abs(n) > N:
return
else:
print(abs(n))
countdown(N,n-1)
Call like this :
countdown(5,5)
One way to do it is by keeping track of 2 lists during the recursion and then stiching them together at return at the end.
def countdown_up(n, i=0, down=[], up=[] ):
if n >i:
return countdown_up(n-1, i, down+[n], [n]+up)
else:
# stich the 2 lists together with the low point [i]
return down+[i]+up
# by default it counts down to 0.
>>>countdown_up(5)
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5]
# you can run with any arbitrary high and low numbers.
>>>countdown_up(10, 3)
[10, 9, 8, 7, 6, 5, 4, 3, 4, 5, 6, 7, 8, 9, 10]
To have the function print instead of return list we just need to change 1 line.
def countdown_up(n, i=0, down=[], up=[] ):
if n >i:
return countdown_up(n-1, i, down+[n], [n]+up)
else:
print(" ".join("%s "%x for x in down+[i]+up))
>>>countdown_up(5)
5 4 3 2 1 0 1 2 3 4 5
>>>countdown_up(10,3)
10 9 8 7 6 5 4 3 4 5 6 7 8 9 10