Shuffle a list within a specific range python - python

I'm very new to Python, so bear with me. I would like to run a program that will shuffle a string of integers in a specific range, but without having to input each integer within that range. I.e., I want to randomize the list of integers from 1 to 100 without typing out (1, 2, 3...100).
Yes, I've looked at other answers to similar questions, but all are asking for one integer within a specific range, or are not answered for Python, or are asking for something way more complex. Thanks

You can use range() along with list() to generate a list of integers, and then apply random.shuffle() on that list.
>>> lst = list(range(1,11))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> random.shuffle(lst)
>>> lst
[4, 5, 3, 9, 2, 10, 7, 1, 6, 8]
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return an object that produces a sequence of integers from start (inclusive)
| to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
| start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
| These are exactly the valid indices for a list of 4 elements.
| When step is given, it specifies the increment (or decrement).

In case you want the entire population within a given range, As #Ashwini proposed you can use random.shuffle
In Case you are interested in a subset of the population, you can look forward to use random.sample
>>> random.sample(range(1,10),5)
[3, 5, 2, 6, 7]
You may also use this to simulate random.shuffle
>>> random.sample(range(1,10),(10 - 1))
[4, 5, 9, 3, 2, 8, 6, 1, 7]
Note, The advantage of using random.sample over random.shuffle, is , it can work on iterators, so in
Python 3.X you don;t need to convert range() to list
In Python 2,X, you can use xrange
Same Code can work in Python 2.X and 3.X

Related

Rotate array in Python

There is this question, 189 Rotate array on Leetcode. enter link description here Its statement is "Given an array, rotate the array to the right by k steps, where k is non-negative."
To understand it better, here's an example.
enter image description here
So, My code for this is
for _ in range(k):
j = nums[-1]
nums.remove(nums[-1])
nums.insert(0, j)
It cannot pass some of the test cases in it.
In the discussion panel, I found a code claiming it got submitted successfully that went like
for _ in range(k):
nums.insert(0, nums.pop(-1))
I would like to know, what is the difference between these two and why my code isn't able to pass some of the test cases.
If you do this on python shell [].remove.__doc__, you'll see the purpose of list.remove is to:
Remove first occurrence of value. Raises ValueError if the value is
not present.
In your code nums.remove(nums[-1]) does not remove the last item, but first occurrence of the value of your last item.
E.g.
If you have a list with values nums = [2, 4, 8, 3, 4] and if you do nums.remove(nums[-1]) the content of nums becomes [2, 8, 3, 4] not [2, 4, 8, 3] that you're expecting.
Just use slicing:
>>> def rotate(l, n):
... return l[-n:] + l[:-n]
...
>>> lst = [1, 2, 3, 4, 5, 6, 7]
>>> rotate(lst, 1)
[7, 1, 2, 3, 4, 5, 6]
>>> rotate(lst, 2)
[6, 7, 1, 2, 3, 4, 5]
>>> rotate(lst, 3)
[5, 6, 7, 1, 2, 3, 4]
In your code j = nums[-1] and you are trying to insert(0, nums[-1]).
In
for _ in range(k):
nums.insert(0, nums.pop(-1))
inserting other number - (0, nums.pop(-1))
Answer given by cesarv is good and simple, but on large arrays numpy will definitely perform better. Consider:
np.roll(lst, n)
The remove() method takes a single element as an argument and removes it's first occurence from the list.
The pop() method takes a single argument (index). The argument passed to the method is optional. If not passed, the default index -1 is passed as an argument (index of the last item).
If the test case has the same item before the last index then test case will fail.
Hence to correct your code replace remove with pop
for _ in range(k):
poppedElement = nums.pop()
nums.insert(0, poppedElement)
or to make it even concise -
for _ in range(k):
nums.insert(0, nums.pop())

Is there a way to use setdiff1d on 2D arrays?

I have an assignment to code kfold(n, n_folds) function, which is supposed to work exactly like sklearn.model_selection.KFold: divide list of integers from 1 to n into n % k_folds groups of n // k_folds + 1 elements and n - n % k groups of n // k_folds elements (this part works well & optimized), then for each group get tuple (all integers from 1 to n not being part of the group, the group) My own realization of this last step just hits TL verdict hard (yet outputs correct answers).
def kfold(n, n_folds):
elements = np.arange(0, n)
slices = np.array(np.array_split(elements, n_folds))
ans = []
for slice in slices:
ans.append((np.setdiff1d(elements, slice), slice))
return ans
kfold(10, 3) as example returns:
[([5, 6, 7, 8, 9, 10], [1, 2, 3, 4]), ([1, 2, 3, 4, 8, 9, 10], [5, 6, 7]), ([1, 2, 3, 4, 5, 6, 7], [8, 9, 10])]
I believe the problem is my code is not fully vectorized, employing one cycle instead of numpy methods. I've read documentation of setdiff1d, setxor1d and likewise functions. While they work well dividing a single slice, I cannot see a way to make them execute all the n_folds slices simultaneously. Is there a way to make this functions work? If there is a nice alternative solution, I'd like to hear about it too

How to insert 1 interval numbers between given irregular numbers in python

I've generated index number list what I do find data using for-loop.
That numbers are as follows.
I want to generate 1 interval index numbers between each given numbers
Int64Index([ 2343, 2913, 5466, 8589, 10151, 11713, 13275, 14837, 15618,7961, 19523, 21624, 21700],dtype='int64')
for e.g) 2343,2344,2345,2346 ......,2911,2912,2913,2914....5464,5465,5466 some thing like that.
Is there any method that i generate 1 interval numbers do not use for-loop?
Try using the builtin range() function.
First you need to determine start and end number using the min() and max() functions.
start_num = min(listr)
end_num = max(listr)
Then we use range() to create our new list
new_listr = list(range(start_num, end_num+1))
The complete sample code:
listr = [2343, 2913, 5466, 8589, 10151, 11713, 13275, 14837, 15618,7961, 19523, 21624, 21700]
start_num = min(listr)
end_num = max(listr)
new_listr = list(range(start_num, end_num+1))
Did you try:
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10,1)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10,2)
[1, 3, 5, 7, 9]
>>> range(1,10,3)
[1, 4, 7]
>>> help(range)
Help on built-in function range in module __builtin__:
range(...)
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
(END)

Mapping a function each list in a list of lists

I've been given a homework task that asks me to find in a list of data the greatest continuous increase. i.e [1,2,3,4,5,3,1,2,3] the greatest static increase here is 4.
I've written a function that takes a single list and spits out a list of sublists like this.
def group_data(lst):
sublist= [[lst[0]]]
for i in range(1, len(lst)):
if lst[i-1] < lst[i]:
sublist[-1].append(lst[i])
else:
sublist.append([lst[i]])
return(sublist)
Which does what it's supposed to
group_data([1,2,3,4,5,6,7,8,9,10,1,2,3,5,4,7,8])
Out[3]: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 5], [4, 7, 8]]
And I now want to subtract the last element of each individual list from the first to find their differences. But I'm having difficulty figuring out how to map the function to each list rather than each element of the list. Any help would be greatly appreciated.
you can do it using map function where arr is your grouped list
list(map(lambda x: x[-1]-x[0], arr ))
For this problem I think itertools.groupby would be a good choice. Since your final goal is to find the difference of longest consecutive numbers:
from itertools import groupby
max_l = max([len(list(g)) - 1 for k, g in groupby(enumerate([1,2,3,4,5,6,7,8,9,10,1,2,3,5,4,7,8]), key=lambda x: x[0] - x[1])])
print(max_l)
#it will print 9
Explanation:
First groupby the numbers with the difference between index and number value. For example [0, 1, 2, 4] will create [0, 0, 0, 1] as the index of 0 is 0, so 0-0=0, for the second one 1-1=0. Then take the maximum length of the grouped list. Since you want difference, I used len(list(g)) - 1

Check what numbers in a list are divisible by certain numbers?

Write a function that receives a list of numbers
and a list of terms and returns only the elements that are divisible
by all of those terms. You must use two nested list comprehensions to solve it.
divisible_numbers([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3]) # returns [12, 6]
def divisible_numbers(a_list, a_list_of_terms):
I have a vague pseudo code so far, that consists of check list, check if divisible if it is append to a new list, check new list check if divisible by next term and repeat until, you have gone through all terms, I don't want anyone to do this for me but maybe a hint in the correct direction?
The inner expression should check if for a particular number, that number is evenly divisible by all of the terms in the second list
all(i%j==0 for j in a_list_of_terms)
Then an outer list comprehension to iterate through the items of the first list
[i for i in a_list if all(i%j==0 for j in a_list_of_terms)]
All together
def divisible_numbers(a_list, a_list_of_terms):
return [i for i in a_list if all(i%j==0 for j in a_list_of_terms)]
Testing
>>> divisible_numbers([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3])
[12, 6]
if you want to get input from the user using this type of way.
enter code hereprint("numbers which are divisible by 5")
user_input=eval(input("enter the value in list type [1,2,3]: "))**
print(type(user_input)) if type(user_input)==list: for i in
user_input: if(i%5==0): print(i,end=",") else:
print("none")
OUTPUT:
numbers that are divisible by 5 enter the value in list type [1,2,3]:
[15,10,20,45,69] <class 'list'> 15,10,20,45,

Categories

Resources