choosing multiple element in python list - python

How can i choose random multiple elements from list ? I looked it from internet but couldn't find anything.
words=["ar","aba","oto","bus"]

You could achieve that with random.sample():
from random import sample
words = ["ar", "aba", "oto", "bus"]
selected = sample(words, 2)
That would select 2 words randomly from the words list.
You can check Python docs for more details.

I think about that :
import random as rd
words=["ar","aba","oto","bus"]
random_words = [word for word in words if rd.random()>1/2]
You can adjust 1/2 by any value between 0 and 1 to approximate the percentage of words chosen in the initial list.

Use random
Here is example
random.choice
>>> import random
>>> words=["ar","aba","oto","bus"]
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
oto
>>> print(random.choice(words))
aba
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
bus
random.sample # sample takes one extra argument to pass a list with element is returned
>>> print(random.sample(words, 3))
['bus', 'ar', 'oto']
>>> print(random.sample(words, 3))
['ar', 'oto', 'aba']
>>> print(random.sample(words, 2))
['aba', 'bus']
>>> print(random.sample(words, 2))
['ar', 'aba']
>>> print(random.sample(words, 1))
['ar']
>>> print(random.sample(words, 1))
['ar']
>>> print(random.sample(words, 1))
['oto']
>>> print(random.sample(words, 1))
['bus']

You can use random library
Method 1 - random.choice()
from random import choice
words=["ar","aba","oto","bus"]
word = choice(words)
print(word)
Method 2 - Generate Random Index
from random import randint
words=["ar","aba","oto","bus"]
ind = randint(0, len(words)-1)
word = words[ind]
print(word)
Method 3 - Select Multiple Items
from random import choices
words=["ar","aba","oto","bus"]
selected = choices(words, k=2) # k is the elements count to select
print(selected)

Related

How to find longest string from a string separated by comma in python [duplicate]

This question already has answers here:
How to get all the maximums max function
(4 answers)
Closed 1 year ago.
I have a string separated by commas ,. I want to find the longest string from the given string.
words = 'run,barn,abcdefghi,yellow,barracuda,shark,fish,swim'
What I did so far
print(max(words.split(','), key=len))
And I am getting this output abcdefghi but as you can see abcdefghi and barracuda have same length. So, why I am only getting one instead of two or all.
Also
words = 'fishes,sam,gollum,sauron,frodo,balrog'
in the above string many words have same length. I want to return every one of them.
You can zip len of word to word then create dict from len and return largest len like below:
>>> from collections import defaultdict
>>> words = 'run,barn,abcdefghi,yellow,barracuda,shark,fish,swim'
>>> dct = defaultdict(list)
>>> lstWrdSplt = words.split(',')
>>> for word, length in (zip(lstWrdSplt,(map(len,lstWrdSplt)))):
... dct[length].append(word)
>>> dct[max(dct)]
['abcdefghi', 'barracuda']
# for more explanation
>>> dct
defaultdict(list,
{3: ['run'],
4: ['barn', 'fish', 'swim'],
9: ['abcdefghi', 'barracuda'],
6: ['yellow'],
5: ['shark']})
You can use this as function and use regex for find only words like below:
from collections import defaultdict
import re
def mxLenWord(words):
dct = defaultdict(list)
lstWrdSplt = re.findall('\w+', words)
for word, length in (zip(lstWrdSplt,(map(len,lstWrdSplt)))):
dct[length].append(word.strip())
return dct[max(dct)]
words = 'rUnNiNg ,swimming, eating,biking, climbing'
mxLenWord(words)
Output:
['swimming', 'climbing']
Try the below
from collections import defaultdict
data = defaultdict(list)
words = 'run,barn,abcdefghi,yellow,barracuda,shark,fish,swim'
for w in words.split(','):
data[len(w)].append(w)
word_len = sorted(data.keys(),reverse=True)
for wlen in word_len:
print(f'{wlen} -> {data[wlen]}')
output
9 -> ['abcdefghi', 'barracuda']
6 -> ['yellow']
5 -> ['shark']
4 -> ['barn', 'fish', 'swim']
3 -> ['run']
There're plenty of methods which I find way too complicated for such an easy task. You can solve it using combination of sorted() and groupby():
from itertools import groupby
words = 'run,barn,abcdefghi,yellow,barracuda,shark,fish,swim'
_, (*longest,) = next(groupby(sorted(words.split(","), key=len, reverse=True), len))
print(longest)
To find all words with same length you can use next one-liner:
from itertools import groupby
words = 'fishes,sam,gollum,sauron,frodo,balrog'
words_len = {l: list(w) for l, w in groupby(sorted(words.split(","), key=len), len)}
print(words_len)

Identify patterns within list of words with pattern threshold

Working on a pattern recognition function in Python that suppose to return an array of patterns with a counter
Let's imagine a list of strings:
m = ['ABA','ABB', 'ABC','BCA','BCB','BCC','ABBC', 'ABBA', 'ABBC']
at the high-level, what I would like to get back is:
Pattern | Count
----------------
AB | 6
ABB | 4
BC | 3
----------------
The problem: all I know that patterns begin with 2 characters and are leading characters for each string value (i.e. XXZZZ, XXXZZZ (where XX is a pattern that I'm looking for)). I would like to be able to parametrize minimal length of a pattern as a function's input to optimize the run time.
PS. each item in the list is a single word already.
my problem is that I need to iterate for each letter starting from the threshold, and I'm getting stuck there.
I'd prefer to use startswith('AB')
First, let's define your string:
>>> m = ['ABA','ABB', 'ABC','BCA','BCB','BCC','ABBC', 'ABBA', 'ABBC']
Now, let's get a count of all leading strings of length 2 or 3:
>>> from collections import Counter
>>> c = Counter([s[:2] for s in m] + [s[:3] for s in m if len(s)>=3])
To compare with your table, here are the three most common leading strings:
>>> c.most_common(3)
Out[15]: [('AB', 6), ('ABB', 4), ('BC', 3)]
Update
To include all keys up to up to length len(max(m, key=len))-1:
>>> n = len(max(m, key=len))
>>> c = Counter(s[:i] for s in m for i in range(2, min(n, 1+len(s))))
Additional Test
To demonstrate that we are working correctly with longer strings, let's consider different input:
>>> m = ['ab', 'abc', 'abcdef']
>>> n = len(max(m, key=len))
>>> c = Counter(s[:i] for s in m for i in range(2, min(n, 1+len(s))))
>>> c.most_common()
[('ab', 3), ('abc', 2), ('abcd', 1), ('abcde', 1)]
Using collections.Counter
counter = collections.Counter()
min_length = 2
max_length = len(max(m, key=len))
for length in range(min_length, max_length):
counter.update(word[:length] for word in m if len(word) >= length)
You can use the function accumulate() to generate accumulated strings and the function islice() to get the strings with a minimal length:
from itertools import accumulate, islice
from collections import Counter
m = ['ABA','ABB', 'ABC','BCA','BCB','BCC','ABBC', 'ABBA', 'ABBC']
c = Counter()
for i in map(accumulate, m):
c.update(islice(i, 1, None)) # get strings with a minimal length of 2
print(c.most_common(3))
# [('AB', 6), ('ABB', 4), ('BC', 3)]

How to pop entire item from array?

I want to randomly assign the three items from list into randlist but I also don't want the items to be assigned more than once
I tried to use a while loop that would pop the items randomly into randlist but it seems to be taking characters from the array item instead of the entire string.
from random import randint
list = ["car", "zonk1", "zonk2"]
randlist = []
x = 0
while x < 3:
randlist += list.pop(randint(0, len(list) - 1))
x += 1
door1 = randlist[0]
door2 = randlist[1]
door3 = randlist[2]
print (door1, door2, door3)
Result:
z o n
This line:
randlist += list.pop(randint(0, len(list) - 1))
extends the str object, character by character, into the list.
>>> mylist = []
>>> mylist += 'foo'
>>> mylist
['f', 'o', 'o']
You want to append what you are popping.
>>> mylist = []
>>> mylist.append('foo')
>>> mylist
['foo']
As an aside, you should use other functions in the random module instead of re-inventing the wheel. You want a random sample from your list:
>>> import random
>>> mylist = ["car", "zonk1", "zonk2"]
>>> random.sample(mylist, 3)
['zonk1', 'car', 'zonk2']
>>> random.sample(mylist, 3)
['zonk2', 'car', 'zonk1']
>>> random.sample(mylist, 3)
['car', 'zonk2', 'zonk1']
If you are willing to use numpy. Then the following code is slightly faster (and arguably neater) than for-looping:
import numpy as np
_list = ["car", "zonk1", "zonk2"]
idx = np.random.permutation(len(_list))
mylist = list(np.array(_list)[idx])
Example output:
>>> mylist
['zonk1', 'car', 'zonk2']

How to generate a list of palindromes with only 'x','y' and a given length n in Python?

is there any patterns i can use to sort out how to create a string that is palindrome which made up with 'X' 'Y'
Let's assume n is even. Generate every string of length n/2 that consists of x and y, and append its mirror image to get a palindrome.
Exercise 1: prove that this generates all palindromes of length n.
Exercise 2: figure out what to do when n is odd.
First generate all possible strings given a list of characters:
>>> from itertools import product
>>> characters = ['x','y']
>>> n = 5
>>> [''.join(i) for i in product(characters, repeat=n)]
['xxxxx', 'xxxxy', 'xxxyx', 'xxxyy', 'xxyxx', 'xxyxy', 'xxyyx', 'xxyyy', 'xyxxx', 'xyxxy', 'xyxyx', 'xyxyy', 'xyyxx', 'xyyxy', 'xyyyx', 'xyyyy', 'yxxxx', 'yxxxy', 'yxxyx', 'yxxyy', 'yxyxx', 'yxyxy', 'yxyyx', 'yxyyy', 'yyxxx', 'yyxxy', 'yyxyx', 'yyxyy', 'yyyxx', 'yyyxy', 'yyyyx', 'yyyyy']
Then filter out non-palindrome:
>>> n = 4
>>> [''.join(i) for i in product(characters, repeat=n) if i[:n/2] == i[::-1][:n/2]]
['xxxx', 'xyyx', 'yxxy', 'yyyy']
>>> n = 5
>>> [''.join(i) for i in product(characters, repeat=n) if i[:n/2] == i[::-1][:n/2]]
['xxxxx', 'xxyxx', 'xyxyx', 'xyyyx', 'yxxxy', 'yxyxy', 'yyxyy', 'yyyyy']
If you don't like if conditions in list comprehension, you can use filter():
>>> from itertools import product
>>> characters = ['x','y']
>>> n = 5
>>> def ispalindrome(x): return x[:n/2] == x[::-1][:n/2];
>>> filter(ispalindrome, [''.join(i) for i in product(characters, repeat=n)])
['xxxxx', 'xxyxx', 'xyxyx', 'xyyyx', 'yxxxy', 'yxyxy', 'yyxyy', 'yyyyy']

Generate all base26 triplests in the fastest way

I need to generate a list of triplets containing only uppercase English letters:
["AAA","AAB","AAC", ..., 'ZZZ']
What is the fastest way to do this in python?
>>> from itertools import product
>>> from string import ascii_uppercase
>>> triplets = map(''.join, product(ascii_uppercase, repeat=3))
>>> triplets[4]
'AAE'

Categories

Resources