i have to do a rotation of a list. I get a sorted list and i have to get minimum of pairs and maximum of tree numbers in a permutation of this sorted list as an answear. It has to have different numbers sorted from lowest to highest. For example:
MyList=[1, 1, 1, 2, 2, 2, 3, 3, 3, 3]
and the output must be:
1 2 3
1 2 3
1 3
2 3
and for :
MyList=[1, 1, 1, 1, 1, 2, 3, 4, 5, 6]
and the output must be:
1 2
1 3
1 4
1 5
1 6
I saw i can do it with a method called round-robin but i don't know how.
Thank you for your help!
from itertools import cycle
A = [[1,2,3],[4,5,6],[7]]
B = [[8],[9,10,11],[12,13]]
for p in A:
max1 = len(p) if max1 <len(p) else max1
for p in B:
max1 = len(p) if max1 <len(p) else max1
i = len(A)
j = 0
C = []
list_num = cycle(k for k in range(i))
for x in list_num:
j += 1
if j == i*3:
break
if A[x]:
C.append(A[x].pop(0))
if B[x]:
C.append(B[x].pop(0))
Output:
[1, 8, 4, 9, 7, 12, 2, 5, 10, 13, 3, 6, 11]
Related
I want to solve this question using dict in python.However i am not able to create code out of the logic.
question says Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher frequency come first. If frequencies of two elements are same, then smaller number comes first.
Input:
2
5
5 5 4 6 4
5
9 9 9 2 5
Output:
4 4 5 5 6
9 9 9 2 5
t=int(input())
for i in range(t):
n=int(input())
arr=list(map(int,input().split()))
d={}
for i in arr:
d[i]=d.get(0,i)+1
a=max(d[i])
print(i*d[i])
a=a+1
Little bit of code that I tried is as above
import collections
sample = [1, 9, 1, 1, 10, 10, 7, 1, 2, 2, 2, 0, 2, 3, 3, 4, 0, 5]
counter = collections.Counter(sample)
def helper_function(item):
return counter[item], item # returns a tuple
sorted_list = sorted(sample, key=helper_function)
# or if you prefer using lambda
sorted_list = sorted(sample, key=lambda item: (counter[item], item))
print(sorted_list)
Output:
[4, 5, 7, 9, 0, 0, 3, 3, 10, 10, 1, 1, 1, 1, 2, 2, 2, 2]
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 need to find all possible gcd of all contiguous subarray of a very large array. I need a solution less than O(N2) time.
Here is my solution with O(N^2).
from math import gcd
lst = [5,3,5,8,9,4,5,6] # A very long list
gcds = {1:0,2:0,3:0,4:0}# ..... All initialized with 0
for i in range(N):
g = lst[i]
for j in range(i+1,N):
g = gcd(g,lst[j])
if g== 1:
gcds[1] += N-j
break
gcds[j] += 1
The key to solving this is that the GCD function is associative. That is gcd(a, gcd(b, c)) == gcd(gcd(a, b), c)
There are exactly n(n+1)/2 contiguous subarrays and each has one GCD these can be calculated like by simply taking the GCD of adjacent elements and then repeating this for the results of each row in the triangle:
5 3 5 8 9 4 5 6
1 1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1
1 1 1 1
1 1 1
1 1
1
from fractions import gcd
output = []
lst = [5,3,5,8,9,4,5,6]
while lst:
o = []
x = lst[0]
for l in lst[1:]:
o.append(gcd(l, x))
x = l
output.extend(o)
lst = o
print output
Results in [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] which is 28 ones.
The complexity of this is n(n+1)/2 or O(n^2). Let us ignore that n=len(input)-1.
This also works for the other example
3 6 9 4
3 3 1
3 1
1
The result of the program is [3, 3, 1, 3, 1, 1]
Using Counter, this can output a histogram rather than a list:
from fractions import gcd
from collections import Counter
output = []
gcds = Counter()
lst = [3, 6, 9, 4]
while lst:
o = []
x = lst[0]
for l in lst[1:]:
v = gcd(l, x)
gcds[v] += 1
o.append(v)
x = l
lst = o
print gcds
prints Counter({1: 3, 3: 3})
I have a code snippet in python. It gets top K=5 values but don't increment the value of K if the value has already occurred.
For example upon giving [1, 3, 3, 5, 5, 6, 1, 4, 8, 9, 34, 66, 124] and K = 5, it should return
[1, 3, 3, 5, 5, 6, 1, 4]
Here if a value is repeating then it should not increment the value of K. Here is the Python code. But how can I do it in pandas Series?.
def get_top_K_uniques(K, nums):
ret = []
presense = defaultdict(bool)
counter = 0
for each in nums:
if not presense[each]:
presense[each] = True
counter+=1
ret.append(each)
if counter == K:
return ret
Thanks in advance.
Using Series.unique() and Series.isin()
nums = pd.Series([1, 3, 3, 5, 5, 6, 1, 4, 8, 9, 34, 66, 124])
uniq = nums.unique()[:5]
nums[nums.isin(uniq)]
Output
0 1
1 3
2 3
3 5
4 5
5 6
6 1
7 4
Using category
s[s.astype('category').cat.codes<4]
Out[153]:
0 1
1 3
2 3
3 5
4 5
6 1
7 4
dtype: int64
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