How can I get a random pair from a dict? I'm making a game on black jack so user will get a random pair from
deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
and it will get stored in a dictionary
player_deck = {}
How can I do this?
Use random.choice()
import random
player_deck = {}
deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
key, value = random.choice(list(deck_of_cards.items()))
player_deck[key] = value
Or in case you want key and value directly into a dictionary, you can do it like this
player_deck = dict([random.choice(list(deck_of_cards.items()))])
It's not really clear how you want to simulate a deck with this dict.
If you just use random.choice multiple times, you might get the same card twice, which probably shouldn't happen.
You could create a whole deck (as a list, not as a dict), shuffle it, draw a card (thus removing it from the deck), and check its value.
Defining a new Card class isn't too hard with namedtuple, and it will make it easier to work with afterwards (Thanks to #MaartenFabré for the comment):
# encoding: utf-8
import random
from collections import namedtuple
class Card(namedtuple('Card', ['face', 'color'])):
colors = ['♠', '♥', '♦', '♣']
faces = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
values = dict(zip(faces, [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]))
def __repr__(self):
return self.face + self.color
def value(self):
return Card.values[self.face]
#staticmethod
def all():
return [Card(face, color)
for color in Card.colors for face in Card.faces]
deck = Card.all()
print(deck)
# ['A♠', '2♠', '3♠', '4♠', '5♠', '6♠', '7♠', '8♠', '9♠', '10♠', 'J♠', 'Q♠', 'K♠', 'A♥', '2♥', '3♥', '4♥', '5♥', '6♥', '7♥', '8♥', '9♥', '10♥', 'J♥', 'Q♥', 'K♥', 'A♦', '2♦', '3♦', '4♦', '5♦', '6♦', '7♦', '8♦', '9♦', '10♦', 'J♦', 'Q♦', 'K♦', 'A♣', '2♣', '3♣', '4♣', '5♣', '6♣', '7♣', '8♣', '9♣', '10♣', 'J♣', 'Q♣', 'K♣']
random.shuffle(deck)
print(deck)
# ['9♣', '4♠', 'J♥', '9♦', '10♠', 'K♣', '8♥', '3♣', 'J♣', '10♦', '8♦', 'A♣', '7♦', '3♠', '7♠', 'Q♣', '7♥', 'Q♦', 'A♦', '9♥', '2♠', '7♣', '6♦', '4♣', 'Q♠', '3♥', 'K♠', '6♣', '5♦', '4♥', '5♣', '2♣', '2♥', '6♥', '8♠', '2♦', '4♦', '8♣', 'K♦', '10♥', 'K♥', '5♠', 'J♦', '5♥', 'A♥', '9♠', '6♠', 'Q♥', '10♣', 'A♠', '3♦', 'J♠']
a_card = deck.pop()
print(a_card)
# J♠
print(a_card.face)
# J
print(a_card.color)
# ♠
print(a_card.value())
# 10
Use random.choice
import random
player_deck = {}
deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
d = random.choice(list(deck_of_cards.items()))
player_deck.update(d)
print(player_deck)
{'9': 9}
You can do something like this:
import random
deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
player_deck = dict(random.sample(deck_of_cards.items(),1))
where I am basically asking for '1' random sample from the dictionary and typecasting the output to a dictionary (as it returns a list).
You can use random.choice:
import random
player_deck=[]
player_deck.append(random.choice(list(deck_of_cards.items())))
print(player_deck)
Related
here's my code :
UserList = [['person1', '25yo','70kg','170cm'],[ 'person2','21yo','54kg','164cm']]
ListStrUser = []
for ListStrUser in UserList:
ListStrUser = GetNum(UserList)
def GetNum(anyList):
for i in range(1,len(anyList)):
anyList[i] = re.sub (r'\D',"", str(anyList[i]))
return anyList
print(ListStrUser)
########
expected result :
[['person1', '25','70','170'],[ 'person2','21','54','164']]
You were not far off Asif. But I cannot add much more to Ethan's answer which is why I'm confused that it was down voted. If you want a function that can handle all the work without the need for another for loop then this function below will do just that:
import re
UserList = [['person1', '25yo','70kg','170cm'],[ 'person2','21yo','54kg','164cm']]
def get_num(any_list):
# includes the for loop to iterate through the list of lists
list_str_user = []
for inner_list in any_list:
temp_list = [inner_list[0]]
for i in range(1,len(inner_list)):
temp_list.append(re.sub(r'\D', '', str(inner_list[i])))
list_str_user.append(temp_list)
return list_str_user
print(get_num(UserList))
Output:
[['person1', '25', '70', '170'], ['person2', '21', '54', '164']]
So no need for the for loop outside the function.
import re
def GetNum(anyList):
for i in range(1, len(anyList)):
anyList[i] = re.sub(r'\D[^0-9]',"",str(anyList[i]))
return anyList
userList = [['person1','25yo','70kg','170cm'],['person2','21yo','54kg','164cm']]
for ListStrUser in userList: ListStrUser = GetNum(ListStrUser)
print("Output : ", userList)
output: [['person1', '25', '70', '170'], ['person2', '21', '54', '164']]
from #Guy 's comment:
UserList = [['person1', '25yo','70kg','170cm'],[ 'person2','21yo','54kg','164cm']]
import re
def GetNum(anyList):
for i in range(1,len(anyList)):
anyList[i] = re.sub (r'\D',"", str(anyList[i]))
return anyList
ListStrUser = []
for ListStr in UserList:
ListStrUser.append(GetNum(ListStr))
print(ListStrUser)
gives
[['person1', '25', '70', '170'], ['person2', '21', '54', '164']]
Try the following code:
user_list = [['person1', '25yo','70kg','170cm'],[ 'person2','21yo','54kg','164cm']]
list_str_user = []
def get_num(any_list):
updated_list = [any_list[0]]
for i in range(1,len(any_list)):
updated_list.append(re.sub(r'\D',"", str(any_list[i])))
return updated_list
for user in user_list:
list_str_user.append(get_num(user))
print(list_str_user)
Notice I also updated the naming of your variables and functions and the spacing between functions to be compliant with pep8. Keep this in mind when writing Python code.
Also functions should be defined before you use them otherwise Python won't find them.
I also created the updated_list variable in get_num, it's never a bad idea to not mutate parameters in functions.
I have the following function which produces results;
myNames = ['ULTA', 'CSCO', ...]
def get_from_min_match(var):
temp = []
count_elem = generate_elem_count()
for item in count_elem:
if var <= count_elem[item]:
temp.append(item)
return set(temp) if len(set(temp)) > 0 else "None"
def generate_elem_count():
result_data = []
for val in mapper.values():
if type(val) == list:
result_data += val
elif type(val) == dict:
for key in val:
result_data.append(key)
count_elem = {elem: result_data.count(elem) for elem in result_data}
return count_elem
I call this function like this;
myNames_dict_1 = ['AME', 'IEX', 'PAYC']
myNames_dict_1 = ['ULTA', 'CSCO', 'PAYC']
mapper = {1: myNames_dict_1, 2: myNames_dict_2}
print(" These meet three values ", get_from_min_match(3))
print(" These meet four values ", get_from_min_match(4))
The output I get from these functions are as follows;
These meet three values {'ULTA', 'CSCO', 'SHW', 'MANH', 'TTWO', 'SAM', 'RHI', 'PAYC', 'AME', 'CCOI', 'RMD', 'AMD', 'UNH', 'AZO', 'APH', 'EW', 'FFIV', 'IEX', 'IDXX', 'ANET', 'SWKS', 'HRL', 'ILMN', 'PGR', 'ATVI', 'CNS', 'EA', 'ORLY', 'TSCO'}
These meet four values {'EW', 'PAYC', 'TTWO', 'AME', 'IEX', 'IDXX', 'ANET', 'RMD', 'SWKS', 'HRL', 'UNH', 'CCOI', 'ORLY', 'APH', 'PGR', 'TSCO'}
Now, I want to insert the output, of the get_from_min_match function into a Sqlite database. Its structure looks like this;
dbase.execute("INSERT OR REPLACE INTO min_match (DATE, SYMBOL, NAME, NUMBEROFMETRICSMET) \
VALUES (?,?,?,?)", (datetime.today(), symbol, name, NUMBEROFMETRICSMET?))
dbase.commit()
So, it's basically a new function to calculate the "NUMBEROFMETRICSMET" parameter rather than calling each of these functions many times. And I want the output of the function inserted into the database. How to achieve this? Here 3, 4 would be the number of times the companies matched.
date ULTA name 3
date EW name 4
...
should be the result.
How can I achieve this? Thanks!
I fixed this by just using my already written function;
count_elem = generate_elem_count()
print("Count Elem: " + str(count_elem))
This prints {'AMPY': 1} and so on.
Basically I'm trying to write a program, which runs through a string, and returns all possible Amino-Acids and how often they occuring. I made this program, which gives me the names but not the numbers. Can someone please help me?
DNA_Codons = {
# U
'UUU': 'Phenylalanin', 'UCU': 'Serin', 'UAU': 'Tyrosin', 'UGU': 'Cystein', # UxU
'UUC': 'Phenylalanin', 'UCC': 'Serin', 'UAC': 'Tyrosin', 'UGC': 'Cystein', # UxC
'UUA': 'Leucin', 'UCA': 'Serin', 'UAA': '---', 'UGA': '---', # UxA
'UUG': 'Leucin', 'UCG': 'Serin', 'UAG': '---', 'UGG': 'Tryptophan', # UxG
# C
'CUU': 'Leucin', 'CCU': 'Prolin', 'CAU': 'Histidin', 'CGU': 'Arginin', # CxU
'CUC': 'Leucin', 'CCC': 'Prolin', 'CAC': 'Histidin', 'CGC': 'Arginin', # CxC
'CUA': 'Leucin', 'CCA': 'Prolin', 'CAA': 'Glutamin', 'CGA': 'Arginin', # CxA
'CUG': 'Leucin', 'CCG': 'Prolin', 'CAG': 'Glutamin', 'CGG': 'Arginin', # CxG
# A
'AUU': 'Isoleucin', 'ACU': 'Threonin', 'AAU': 'Asparagin', 'AGU': 'Serin', # AxU
'AUC': 'Isoleucin', 'ACC': 'Threonin', 'AAC': 'Asparagin', 'AGC': 'Serin', # AxC
'AUA': 'Isoleucin', 'ACA': 'Threonin', 'AAA': 'Lysin', 'AGA': 'Arginin', # AxA
'AUG': 'Met', 'ACG': 'Threonin', 'AAG': 'Lysin', 'AGG': 'Arginin', # AxG
# G
'GUU': 'Valin', 'GCU': 'Alanin', 'GAU': 'Asparaginsäure', 'GGU': 'Glycin', # GxU
'GUC': 'Valin', 'GCC': 'Alanin', 'GAC': 'Asparaginsäure', 'GGC': 'Glycin', # GxC
'GUA': 'Valin', 'GCA': 'Alanin', 'GAA': 'Glutaminsäure', 'GGA': 'Glycin', # GxA
'GUG': 'Valin', 'GCG': 'Alanin', 'GAG': 'Glutaminsäure', 'GGG': 'Glycin' # GxG }
def translate_code(seq, init_pos=0):
return {
DNA_Codons[seq[pos:pos + 3]]
for pos in range(init_pos, len(seq) - 2, 3)
}
print(translate_code("ACAAUUGACACAUAUCGUCGAGGGUGGCCA"))
What I'm looking for is something like this:
{'Threonin': 2, 'Isoleucin': 1, 'Asparaginsäure': 1, 'Tyrosin': 1, 'Arginin': 2,
'Glycin': 1, 'Tryptophan': 1, 'Prolin': 1}
def translate_code(seq, init_pos=0):
final_codons = {}
for pos in range(init_pos, len(seq) - 2, 3):
current_codon = DNA_Codons[seq[pos:pos + 3]]
if current_codon in final_codons:
final_codons[current_codon] += 1
else:
final_codons[current_codon] = 1
return final_codons
This should work exactly as you specified for it to.
import numpy as np
def count_amino_acids(seq, init_pos=0):
#First, create an amino acid dictionary from the codon dictionary:
count_dict = {}
# go from the initial position, to full length in steps of 3
for i in np.arange(init_pos, len(seq), 3):
codon = seq[i:i+3] # get the codon
aa = DNA_Codons[codon] # look up the amino acid
if aa == '---': # stop at stop codons
return count_dict
count_dict[aa] += 1 # increment the counter
return count_dict
count_amino_acids("ACAAUUGACACAUAUCGUCGAGGGUGGCCA")
You can use the Counter class from the collections module:
To exclude the combinations you don't want I would suggest not placing them in the codon dictionary at all. I also inverted your dictionary to reduce the number of repetitions and make it more maintainable.
Setup:
acids = { 'Alanin': ['GCA', 'GCC', 'GCG', 'GCU'],
'Arginin': ['AGA', 'AGG', 'CGA', 'CGC', 'CGG', 'CGU'],
'Asparagin': ['AAC', 'AAU'],
'Asparaginsäure':['GAC', 'GAU'],
'Cystein': ['UGC', 'UGU'],
'Glutamin': ['CAA', 'CAG'],
'Glutaminsäure': ['GAA', 'GAG'],
'Glycin': ['GGA', 'GGC', 'GGG', 'GGU'],
'Histidin': ['CAC', 'CAU'],
'Isoleucin': ['AUA', 'AUC', 'AUU'],
'Leucin': ['CUA', 'CUC', 'CUG', 'CUU', 'UUA', 'UUG'],
'Lysin': ['AAA', 'AAG'],
'Met': ['AUG'],
'Phenylalanin': ['UUC', 'UUU'],
'Prolin': ['CCA', 'CCC', 'CCG', 'CCU'],
'Serin': ['AGC', 'AGU', 'UCA', 'UCC', 'UCG', 'UCU'],
'Threonin': ['ACA', 'ACC', 'ACG', 'ACU'],
'Tryptophan': ['UGG'],
'Tyrosin': ['UAC', 'UAU'],
'Valin': ['GUA', 'GUC', 'GUG', 'GUU'] }
codons = { seq:name for name,sequences in acids.items() for seq in sequences }
Counting:
from collections import Counter
def translate_code(seq, init_pos=0):
return Counter( codons[seq[pos:pos + 3]]
for pos in range(init_pos, len(seq), 3)
if seq[pos:pos + 3] in codons)
output:
print(translate_code("ACAAUUGACACAUAUCGUCGAGGGUGGCCA"))
Counter({'Threonin': 2, 'Arginin': 2, 'Isoleucin': 1, 'Asparaginsäure': 1, 'Tyrosin': 1, 'Glycin': 1, 'Tryptophan': 1, 'Prolin': 1})
Note, the Counter class is actually a dictionary. You can cast it back to a normal dictionary if needed.
You were almost there. I made some changes to your code. Note: mine is not inside a function.
d = {}
s = "ACAAUUGACACAUAUCGUCGAGGGUGGCCA"
for i in range(0, len(s) - 2, 3):
d[DNA_Codons[s[i:i+3]]] = s.count(s[i:i+3])
print(di) ```
Having the following list of lists ['boundari', 'special', ['forest', 'arb'], 'abod'], I would like to obtain the the following combination:
[['boundari', 'special', 'forest', 'abod'], ['boundari', 'special', 'arb', 'abod']]
The nearest solution applying the next product when removing the last item abod (which I need to keep):
print([list(p) for p in product([toks[:2]], *toks[2:])])
[[['boundari', 'special'], 'forest'], [['boundari', 'special'], 'arb']]
However, I have not obtained the correct combination:
[['boundari', 'special', 'forest', 'abod'], ['boundari', 'special', 'arb', 'abod']]
You can do something like this:
arr = ['boundari', 'special', ['forest', 'arb'], 'abod']
def get_combinations(arr):
n = len(arr)
def _get_combinations(so_far, idx):
if idx >= n:
yield so_far[:]
return
if isinstance(arr[idx], list):
for val in arr[idx]:
so_far.append(val)
yield from _get_combinations(so_far, idx + 1)
so_far.pop()
else:
so_far.append(arr[idx])
yield from _get_combinations(so_far, idx + 1)
so_far.pop()
yield from _get_combinations([], 0)
expected_ans = [
['boundari', 'special', 'forest', 'abod'],
['boundari', 'special', 'arb', 'abod'],
]
assert list(get_combinations(arr)) == expected_ans
Another solution using only simple loops would be something like this and in case order of lists inside is not important:
my_list_of_list = ['boundari', 'special', ['forest', 'arb'], 'abod']
indecies_of_lists = []
base_list = []
lists_of_lists = []
output = []
for item in my_list_of_list:
if type(item) == list:
lists_of_lists.append(item)
else:
base_list.append(item)
for item in lists_of_lists:
for sub_item in item:
new_list = list(base_list)
new_list.append(sub_item)
output.append(new_list)
print(output)
output will be [['boundari', 'special', 'abod', 'forest'], ['boundari', 'special', 'abod', 'arb']]
I have a list of (around 100) values like this list:
list = ['40201020', '45102020', '25203020', '20106020', '25301020', '40402030', '20202010']
I need a dictionary that
a) lists all parents for each value. The parent has one digit less (from the right):
child = '40201020'
parent = '4020102'
this format would be ideal:
dict['4020102parent'] = '40201020'
b) I need all parents of parents up to one remaining digit. So parent '4020102' gets this parent:
dict['4020102parent"] = '402010'
and
dict['402010parent"] = '40201'
etc.
c) I then need all last descendents for each parent as a list. By last descendant, I mean the 8 digit codes of the original list. So the digit '4' would have these codes:
dict['4children'] = ['40201020', '45102020', '40402030']
or:
dict['40children'] = ['40201020', '40402030']
Will your list always contain strings and is a dictionary a requirement? If you will always be working with strings and you are just wanting a way to find parents and children, I would suggest using python's string handling capabilities. You could define functions parent and children like this:
def parent(list_item):
return list_item[:-1]
def children(my_list, parent_str):
children_found = []
for item in my_list:
if item.startswith(parent_str)
children_found.append(item)
return children_found
Then calling parent('40201020') would produce '4020102' and calling children(my_list, '40') would produce ['40201020', '40402030']. You can call parent recursively to get a string with one less item each time.
I am still confused why you need parent dict when you can just store recursive result in a list and can use str.startswith() method :
still i have stored parentdict in dict_data you can use that :
list1 = ['40201020', '45102020', '25203020', '20106020', '25301020', '40402030', '20202010']
dict_data=[]
track=[]
list_2={}
def main_function(lst_1):
for i in lst_1:
def recursive(lst):
parent = {}
if not lst:
return 0
else:
parent[lst[:-1] + 'parent'] = lst
track.append(lst)
dict_data.append(parent)
return recursive(lst[:-1])
recursive(i)
main_function(list1)
for recursive_unit in set(track):
for items in list1:
if items.startswith(recursive_unit):
if recursive_unit not in list_2:
list_2[recursive_unit]=[items]
else:
list_2[recursive_unit].append(items)
print(list_2)
output:
{'25203': ['25203020'], '25': ['25203020', '25301020'],'4': ['40201020', '45102020', '40402030'],'4510': ['45102020'], '2520302': ['25203020'], '40402030': ['40402030'], '2010602': ['20106020'], '45102020': ['45102020'], '45': ['45102020'], '253010': ['25301020'], '4020': ['40201020'], '252': ['25203020'], '20202010': ['20202010'], '20106': ['20106020'], '201060': ['20106020'],'202020': ['20202010'], '2530102': ['25301020'], '402': ['40201020'], '2010': ['20106020'], '4510202': ['45102020'], '2530': ['25301020'], '451020': ['45102020'], '2020201': ['20202010'], '404020': ['40402030'], '25203020': ['25203020'], '2': ['25203020', '20106020', '25301020', '20202010'], '20202': ['20202010'], '253': ['25301020'], '40402': ['40402030'], '451': ['45102020'], '40201020': ['40201020'], '252030': ['25203020'], '2520': ['25203020'], '40': ['40201020', '40402030'], '4040': ['40402030'], '402010': ['40201020'], '4020102': ['40201020'], '25301020': ['25301020'], '20106020': ['20106020'], '201': ['20106020'], '20': ['20106020', '20202010'], '202': ['20202010'], '40201': ['40201020'], '45102': ['45102020'], '2020': ['20202010'], '25301': ['25301020'], '4040203': ['40402030'], '404': ['40402030']}
As stated in my comment, a dictionary where each key contains the children seems like a more reasonable idea.
To achieve this, we can loop through each element in your list (which I renamed to l as to not override the built-in list() function), and append this value to the lists of all its parents in a dictionary, d.
The code for the above described method would look something along the lines of:
d = {}
for i in l:
for e in range(1, len(l)-1):
d.setdefault(i[:e], []).append(i)
which will then allow you to do things like:
>>> d['4']
['40201020', '45102020', '40402030']
>>> d['40']
['40201020', '40402030']
>>> d['25']
['25203020', '25301020']
# do not use "list" as variable name (it's a python builtin)
mylist = ['2', '20', '201', '2010', '20106', '201060', '2010602']
mylist_sorted = mylist.clone()
mylist_sorted.sort()
parents = {}
children = {}
for element in mylist_sorted:
parents[e] = []
children[e] = []
for subelement in [element[0:x] for x in range(1,len(element))]:
if subelement in parents:
parents[element].append(subelement)
children[subelement].append(element)
print(parents)
print(children)
Output:
{'201060': ['2', '20', '201', '2010', '20106'],
'20106': ['2', '20', '201', '2010'],
'2010': ['2', '20', '201'],
'201': ['2', '20'],
'2': [],
'2010602': ['2', '20', '201', '2010', '20106', '201060'],
'20': ['2']}
{'201060': ['2010602'],
'20106': ['201060', '2010602'],
'2010': ['20106', '201060', '2010602'],
'201': ['2010', '20106', '201060', '2010602'],
'2': ['20', '201', '2010', '20106', '201060', '2010602'],
'2010602': [],
'20': ['201', '2010', '20106', '201060', '2010602']}