Write a function that takes two arguments — a list 𝐿 and a number
𝑛 and returns a list of 𝐿 elements, scrolled 𝑛 elements to the right (elements,
those at the end of the list are placed at the beginning). If 𝑛 < 0, the shift must be to the left.
(For example)
In [1]: lrot([1,3,4,2,7,5], 2)
Out[1]: [7,5,1,3,4,2]
In [2]: lrot([1,3,4,2,7,5], -2)
Out[2]: [4,2,7,5,1,3]
In [3]: lrot([1,3,4,2,7,5], 7)
Out[3]: [5,1,3,4,2,7]
In [4]:
I will be really greatful for any help!
Does this help? I'm not sure about negative n.
Related
I am new to python. Using it with grasshopper.
I have 5 lists, each actually with 8760 items for which i have found max values at each index "but I also need to know which list the value came from at any given index."
I would put a simple example to explain myself better.
For 2 lists
A = [5,10,15,20,25]
B = [4,9,16,19,26]
Max value per index = [5,10,16,20,26]
What I want is something like
Max value per index = [5(A), 10(A), 16(B), 20(A), 26(B)]
Or something along the line that can relate. I am not sure whether its possible.
I would really appreciate the help. Thank you.
This can be adapted to N lists.
[(max(a),a.index(max(a))) for a in list(zip(A,B))]
The .index(max(a)) gets the index at which the max(a) occurs.
The output for your example is
[(5, 0), (10, 0), (16, 1), (20, 0), (26, 1)]
Of course, if both A and B share the same value, then the index will be the first one found, A.
See https://docs.python.org/3.3/library/functions.html for description of very useful zip built-in function.
This question already has answers here:
How to get the n next values of a generator into a list
(5 answers)
Fetch first 10 results from a list in Python
(4 answers)
Closed 9 days ago.
With linq I would
var top5 = array.Take(5);
How to do this with Python?
Slicing a list
top5 = array[:5]
To slice a list, there's a simple syntax: array[start:stop:step]
You can omit any parameter. These are all valid: array[start:], array[:stop], array[::step]
Slicing a generator
import itertools
top5 = itertools.islice(my_list, 5) # grab the first five elements
You can't slice a generator directly in Python. itertools.islice() will wrap an object in a new slicing generator using the syntax itertools.islice(generator, start, stop, step)
Remember, slicing a generator will exhaust it partially. If you want to keep the entire generator intact, perhaps turn it into a tuple or list first, like: result = tuple(generator)
import itertools
top5 = itertools.islice(array, 5)
#Shaikovsky's answer is excellent, but I wanted to clarify a couple of points.
[next(generator) for _ in range(n)]
This is the most simple approach, but throws StopIteration if the generator is prematurely exhausted.
On the other hand, the following approaches return up to n items which is preferable in many circumstances:
List:
[x for _, x in zip(range(n), records)]
Generator:
(x for _, x in zip(range(n), records))
In my taste, it's also very concise to combine zip() with xrange(n) (or range(n) in Python3), which works nice on generators as well and seems to be more flexible for changes in general.
# Option #1: taking the first n elements as a list
[x for _, x in zip(xrange(n), generator)]
# Option #2, using 'next()' and taking care for 'StopIteration'
[next(generator) for _ in xrange(n)]
# Option #3: taking the first n elements as a new generator
(x for _, x in zip(xrange(n), generator))
# Option #4: yielding them by simply preparing a function
# (but take care for 'StopIteration')
def top_n(n, generator):
for _ in xrange(n):
yield next(generator)
The answer for how to do this can be found here
>>> generator = (i for i in xrange(10))
>>> list(next(generator) for _ in range(4))
[0, 1, 2, 3]
>>> list(next(generator) for _ in range(4))
[4, 5, 6, 7]
>>> list(next(generator) for _ in range(4))
[8, 9]
Notice that the last call asks for the next 4 when only 2 are remaining. The use of the list() instead of [] is what gets the comprehension to terminate on the StopIteration exception that is thrown by next().
Do you mean the first N items, or the N largest items?
If you want the first:
top5 = sequence[:5]
This also works for the largest N items, assuming that your sequence is sorted in descending order. (Your LINQ example seems to assume this as well.)
If you want the largest, and it isn't sorted, the most obvious solution is to sort it first:
l = list(sequence)
l.sort(reverse=True)
top5 = l[:5]
For a more performant solution, use a min-heap (thanks Thijs):
import heapq
top5 = heapq.nlargest(5, sequence)
With itertools you will obtain another generator object so in most of the cases you will need another step the take the first n elements. There are at least two simpler solutions (a little bit less efficient in terms of performance but very handy) to get the elements ready to use from a generator:
Using list comprehension:
first_n_elements = [generator.next() for i in range(n)]
Otherwise:
first_n_elements = list(generator)[:n]
Where n is the number of elements you want to take (e.g. n=5 for the first five elements).
This should work
top5 = array[:5]
I have list like following
m=[['abc','x-name',222],['pqr','y-name',333],['mno','j-name',333],['qrt','z-name',111],['dcu','lz-name',999]]
Let's say I want to get top 2 out of this list considering 3rd column(i.e 222 or etc)
I know I can get the Max one like following
>>> m=[['abc','x-name',222],['pqr','y-name',333],['mno','j-name',333],['qrt','z-name',111],['dcu','lz-name',999]]
>>> print max(m, key=lambda x: x[2])
['dcu', 'lz-name', 999]
but what I have to get top 2 (considering the duplicates) my result should be
['dcu', 'lz-name', 999] ['pqr','y-name',333] ['mno','j-name',333]
Is it possible? I head is spinning trying to figure it out, can you pls have look and help me..
OR -just got idea
You can tell me to delete MAX element so that I can get top 2 elements using iteration( duplicate will be a problem though)
You can sort and slice instead:
>>> from operator import itemgetter
>>> sorted(m, key=itemgetter(2), reverse=True)[:3]
[['dcu', 'lz-name', 999], ['pqr', 'y-name', 333], ['mno', 'j-name', 333]]
Or, using the heapq.nlargest():
>>> import heapq
>>> heapq.nlargest(3, m, key=itemgetter(2))
[['dcu', 'lz-name', 999], ['pqr', 'y-name', 333], ['mno', 'j-name', 333]]
This, though, would not handle the duplicates nicely and it is not of a linear time complexity, plus it would created a sorted copy of the initial list in memory. Please see the following threads for linear-time and more memory-efficient solutions:
Get the second largest number in a list in linear time
Best way to sort 1M records in Python
I am having problems with list of prolog. I want to make this:
[1,2,3,4,5]
[5,6,9,12,10]
You take a number for example 3, and you do a plus operation with the neighbours so the operation is 2+3+4 = 9. For the first and the last element you pretend there is an imaginary 1 there.
I have this now:
sum_list([A,X,B|T], [Xs|Ts]):-
add(A,X,B,Xs),
sum_list([X,B|T], Ts).
I haven't consider the first and the last element. My problem is I don't know how to get the element before and the next and then how to move on.
Note: I not allow to use meta-predicates.
Thanks.
I'm not sure how you calculated the first 5. The last 10 would be 4 + 5 + implicit 1. But following that calculation, the first element of your result should be 4 instead of 5?
Anyways, that doesn't really matter in terms of writing this code. You are actually close to your desired result. There are of course multiple ways of tackling this problem, but I think the simplest one would be to write a small 'initial' case in which you already calculate the first sum and afterwards recursively calculate all of the other sums. We can then write a case in which only 2 elements are left to calculate the last 'special' sum:
% Initial case for easily distinguishing the first sum
initial([X,Y|T],[Sum|R]) :-
Sum is X+Y+1,
others([X,Y|T],R).
% Match on 2 last elements left
others([X,Y],[Sum|[]]) :-
Sum is X+Y+1.
% Recursively keep adding neighbours
others([X,Y,Z|T],[Sum|R]) :-
Sum is X+Y+Z,
others([Y,Z|T],R).
Execution:
?- initial([1,2],Result)
Result = [4,4]
?- initial([1,2,3,4,5],Result)
Result = [4, 6, 9, 12, 10]
Note that we now don't have any cases (yet) for an empty list or a list with just one element in it. This still needs to be covered if necessary.
I'm trying to figure out the best way of doing the following:
I have a list of values: L
I'd like to pick a subset of this list, of size N, and get a different subset (if the list has enough members) every X minutes.
I'd like the values to be picked sequentially, or randomly, as long as all the values get used.
For example, I have a list: [google.com, yahoo.com, gmail.com]
I'd like to pick X (2 for this example) values and rotate those values every Y(60 for now) minutes:
minute 0-59: [google.com, yahoo.com]
minute 60-119: [gmail.com, google.com
minute 120-179: [google.com, yahoo.com]
etc.
Random picking is also fine, i.e:
minute 0-59: [google.com, gmail.com]
minute 60-119: [yahoo.com, google.com]
Note: The time epoch should be 0 when the user sets the rotation up, i.e, the 0 point can be at any point in time.
Finally: I'd prefer not to store a set of "used" values or anything like that, if possible. i.e, I'd like this to be as simple as possible.
Random picking is actually preferred to sequential, but either is fine.
What's the best way to go about this? Python/Pseudo-code or C/C++ is fine.
Thank you!
You can use the itertools standard module to help:
import itertools
import random
import time
a = ["google.com", "yahoo.com", "gmail.com"]
combs = list(itertools.combinations(a, 2))
random.shuffle(combs)
for c in combs:
print(c)
time.sleep(3600)
EDIT: Based on your clarification in the comments, the following suggestion might help.
What you're looking for is a maximal-length sequence of integers within the range [0, N). You can generate this in Python using something like:
def modseq(n, p):
r = 0
for i in range(n):
r = (r + p) % n
yield r
Given an integer n and a prime number p (which is not a factor of n, making p greater than n guarantees this), you will get a sequence of all the integers from 0 to n-1:
>>> list(modseq(10, 13))
[3, 6, 9, 2, 5, 8, 1, 4, 7, 0]
From there, you can filter this list to include only the integers that contain the desired number of 1 bits set (see Best algorithm to count the number of set bits in a 32-bit integer? for suggestions). Then choose the elements from your set based on which bits are set to 1. In your case, you would use pass n as 2N if N is the number of elements in your set.
This sequence is deterministic given a time T (from which you can find the position in the sequence), a number N of elements, and a prime P.