How do I remove duplicate numbers from my hand of cards? - python

So i have my hand of cards that i randomly dealt from a deck but i need to remove the duplicate numbers in my hand. I have no idea where to start.
this is an example of what my hand would look like before removing the pairs:
l=['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢', '2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
and this is what i've tried:
no_pairs=[]
l.sort()
for i in range(len(l)):
for j in (i+1, len(l)):
if i[-2] not in j:
no_pairs.append(i)
when i do this, it keeps saying
TypeError: 'int' object is not subscriptable

Strip the final character when iterating through the list of strings.
If you're just looking for the number, ignoring the suit, then you just need to strip the suit from the number before comparing it to an array of the numbers you've already sorted, and then adding both the stripped value to the array of numbers, and the original value to the final output. This should work:
l.sort()
sorted_num = []
final = []
for i in l:
if i[:-1] not in sorted_num:
sorted_num.append(i[:-1])
final.append(i)
When run, this gives the value of final as:
['10♢', '2♠', '3♢', '4♡', '6♠', '7♠', '8♢', '9♠', 'A♠', 'J♣', 'K♡', 'Q♠']

Check for the occurrence of each element in the list, and append only if occurs once.
l=['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢', '2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
no_pairs=[]
for i in set(l):
if l.count(i)==1:
no_pairs.append(i)

Get first character of items with item[0], then check it is a number with num.isdigit() method and add it to no_pairs list.
l=['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢', '2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
no_pairs = []
for item in l:
num = item[0]
if num.isdigit():
num = int(num)
no_pairs.append(int(num))
print(no_pairs)
#output :
[6, 6, 7, 1, 8, 2, 9, 8, 7, 9, 1, 2, 2, 3, 6, 4, 4]

Your i is an int, you can achieve i[2] (for the error). Then I really don't know where your code was going, so I didn't try to fix I wrote a new one.
I'd suggest you keep track of the numbers you already added, so that you know if you add the card or not
l = ['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢',
'2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
no_pairs = []
nb_cards = set()
for card in l:
nb_card = card[:-1]
if nb_card not in nb_cards:
nb_cards.add(nb_card)
no_pairs.append(card)
print(no_pairs) # ['6♠', '7♢', '10♣', '8♣', '2♣', '9♠', 'K♢', 'Q♡', '3♢', '4♣', 'A♡', 'J♣']
You can replace the set by a list, but that woul dbe just less performant

Related

How to execute a function once something happens until something else happens

I need to create a program that takes a file containing DNA and converts the open reading frame into protein data. I need to run the function once "ATG" occurs and until the stop codons "TAG" "TAA" or "TGA" occur.
I'm new to programming and this is what I have,
map = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',
}
DNA = 'AGCCATGTAGCTAACTCAGGTTACATGGGGATGACCCCGCGACTTGGATTAGAGTCTCTTTTGGAATAAGCCTGAATGATCCGAGTAGCATCTCAG'
DNAlist = []
DNAlist1 = []
DNAlist2 = []
protein = []
for i in range(0, len(DNA), 3):
DNAlist.append(DNA[i:i+3])
for i in range(1, len(DNA), 3):
DNAlist1.append(DNA[i:i+3])
for i in range(2, len(DNA), 3):
DNAlist2.append(DNA[i:i+3])
while True:
if elements in DNAlist2 == 'TAG' or 'TAA' or 'TGA':
False
else:
protein = ''.join([map[elements] for elements in DNAlist2])```
A sample output would be
MLLGSFRLIPKETLIQVAGSSPCNLS
M
MGMTPRLGLESLLE
MTPRLGLESLLE
well tried without using Biopython, went only for forward strand (no reverse) and used the translated sequence
found two ways, I am sure these are non-optimal approaches, I am waiting for somebody better here How to find a open reading frame in Python are fastest ways I suppose.
first one gives you ORFs even if there is no stop codon (sequence doesnt terminate so no '_' for stop codon presence :
mappy = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',
}
# for i in mappy:
# print(mappy[i])
DNA = 'AGCCATGTAGCTAACTCAGGTTACATGGGGATGACCCCGCGACTTGGATTAGAGTCTCTTTTGGAATAAGCCTGAATGATCCGAGTAGCATCTCAG'
DNAlist1 = []
DNAlist2 = []
DNAlist3 = []
# protein = []
def revProt(dna_list):
proteinz = []
for elements in dna_list:
if len(elements) == 3:
proteinz.append(mappy[elements])
# proteinz = ''.join(proteinz)
return ''.join([ i for i in reversed(proteinz)])
for i in range(0, len(DNA), 3):
DNAlist1.append(DNA[i:i+3])
for i in range(1, len(DNA), 3):
DNAlist2.append(DNA[i:i+3])
for i in range(2, len(DNA), 3):
DNAlist3.append(DNA[i:i+3])
# for i in [DNAlist1] : #, DNAlist2, DNAlist3]:
for i in [DNAlist1, DNAlist2, DNAlist3]:
protein = revProt(i)
print(''.join(protein), type(''.join(protein)))
seqs = []
j = 0
orf = []
while True:
if j <= len(protein)-1:
if protein[j] == '_' :
if orf[0] == 'M':
orf.append('_')
seqs.append(''.join([i for i in reversed(orf)]))
orf = []
else :
orf = []
orf.append('_')
if protein[j] not in [ '_' , 'M'] :
orf.append(protein[j])
if protein[j] == 'M':
orf.append(protein[j])
seqs.append(''.join([i for i in reversed(orf)]))
else :
break
j += 1
print(seqs, '\n')
output:
QSAVRIM_A_ELLSELGLRPTMGMYGSNAVHS <class 'str'>
['MIRVASQ', 'MTPRLGLESLLE_', 'MGMTPRLGLESLLE_'] -----> here sequences 1st is at the end of DNA so no stop
LH_ES_EPKNWFLS_DLDRP_GWTVQTL_MA <class 'str'>
['M_']
SISSPDNLSIGFSVRIWTAPDDGHLRL_SCP <class 'str'>
[]
second way even more cumbersome :
import itertools
mappy = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',
}
DNA = 'AGCCATGTAGCTAACTCAGGTTACATGGGGATGACCCCGCGACTTGGATTAGAGTCTCTTTTGGAATAAGCCTGAATGATCCGAGTAGCATCTCAG'
DNAlist1 = []
DNAlist2 = []
DNAlist3 = []
def Prot(dna_list):
proteinz = []
for elements in dna_list:
if len(elements) == 3:
proteinz.append(mappy[elements])
# proteinz = ''.join(proteinz)
return proteinz
def Met(protein):
met = [i for i, x in enumerate(protein) if x == "M"]
return met
def Stop(protein):
stop = [i for i, x in enumerate(protein) if x == "_"]
return stop
for i in range(0, len(DNA), 3):
DNAlist1.append(DNA[i:i+3])
for i in range(1, len(DNA), 3):
DNAlist2.append(DNA[i:i+3])
for i in range(2, len(DNA), 3):
DNAlist3.append(DNA[i:i+3])
for i in [DNAlist1, DNAlist2, DNAlist3]:
protein = Prot(i)
print(''.join(protein), type(''.join(protein)))
met = Met(protein)
# print('met : ', met)
stop = Stop(protein)
# print('stop : ' , stop)
# print('------------------')
orf = [i for i in list(itertools.product(met, stop)) if i[0] < i[1]]
print(orf)
orf_p = [''.join(protein[j[0]:j[1]]) for j in orf]
orf_pp = [i for i in orf_p]
for y in orf_p:
# print(y, type(y))
if '_' in y:
# print('ok')
orf_pp.remove(y)
print('orf_pp : ',orf_pp)
print('______________')
output:
SHVANSGYMGMTPRLGLESLLE_A_MIRVASQ <class 'str'>
[(8, 22), (8, 24), (10, 22), (10, 24)]
orf_pp : ['MGMTPRLGLESLLE', 'MTPRLGLESLLE'] ----->here the sequences
______________
AM_LTQVTWG_PRDLD_SLFWNKPE_SE_HL <class 'str'>
[(1, 2), (1, 10), (1, 16), (1, 25), (1, 28)]
orf_pp : ['M']
______________
PCS_LRLHGDDPATWIRVSFGISLNDPSSIS <class 'str'>
[]
orf_pp : []
______________
shorter (probably faster copied from : How to find a open reading frame in Python
import re
mappy = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',
}
# for i in mappy:
# print(mappy[i])
DNA = 'AGCCATGTAGCTAACTCAGGTTACATGGGGATGACCCCGCGACTTGGATTAGAGTCTCTTTTGGAATAAGCCTGAATGATCCGAGTAGCATCTCAG'
def Prot(dna_list):
proteinz = []
for elements in dna_list:
if len(elements) == 3:
proteinz.append(mappy[elements])
return proteinz
pattern = re.compile(r'(?=(ATG(?:...)*?)(?=TAG|TGA|TAA))')
def revcomp(dna_seq):
return dna_seq[::-1].translate(str.maketrans("ATGC","TACG"))
def orfs(dna):
return set(pattern.findall(dna) + pattern.findall(revcomp(dna)))
for j in orfs(DNA):
# print(j, type(j))
DNAlistz = []
for i in range(0, len(j), 3):
DNAlistz.append(j[i:i+3])
print(''.join(Prot(DNAlistz)))
print('+++++++++++++')
output this time with reverse strand translation too:
MGMTPRLGLESLLE
MTPRLGLESLLE
M
MLLGSFRLIPKETLIQVAGSSPCNLS
+++++++++++++

Looking for pair in a list of playing cards

So I am creating a card game in python. For the part of the game I an currently working on, I need to check an array of playing cards to see if there are any pairs. A pair is considered two cards with the same value and color. For example, king of hearts and king of diamonds are a pair, but king of hearts and king of clubs aren't.
I need to return a new list with all of the pairs removed.
Suppose we have
list = ['9♠', '5♠', 'K♢', 'A♣', 'K♣', 'K♡', '2♠', 'Q♠', 'K♠', 'Q♢', 'J♠', 'A♡', '4♣', '5♣', '7♡', 'A♠', '10♣', 'Q♡', '8♡', '9♢', '10♢', 'J♡', '10♡', 'J♣', '3♡']
The result should be:
list without pairs = ['10♣', '2♠', '3♡', '4♣', '7♡', '8♡', '9♠', '9♢', 'A♣', 'A♡', 'A♠', 'J♠', 'J♡', 'J♣', 'K♢', 'K♣', 'K♡', 'K♠', 'Q♠']
I currently have this code:
import random
result=[]
for i in range(len(l)):
if '♣' in l[i]:
pass
elif '♠' in l[i]:
pass
elif '♡' in l[i]:
pass
elif '♢' in l[i]:
pass
random.shuffle(result)
return result
cards_list = [
"9♠",
"5♠",
"K♢",
"A♣",
"K♣",
"K♡",
"2♠",
"Q♠",
"K♠",
"Q♢",
"J♠",
"A♡",
"4♣",
"5♣",
"7♡",
"A♠",
"10♣",
"Q♡",
"8♡",
"9♢",
"10♢",
"J♡",
"10♡",
"J♣",
"3♡",
]
SAME_COLORS = {"♢": "♡", "♡": "♢", "♠": "♣", "♣": "♠"}
list_without_pairs = []
for card in cards_list:
if card[:-1] + SAME_COLORS[card[-1]] in cards_list:
continue
else:
list_without_pairs.append(card)
print(list_without_pairs)
Output:
['9♠', '2♠', 'Q♠', 'A♡', '4♣', '7♡', '10♣', '8♡', '9♢', 'J♡', '3♡']
This work exactly the same but could be a little bit more confuse:
list_without_pairs = [card for card in cards_list if card[:-1] + SAME_COLORS[card[-1]] not in cards_list]

How to find pairs of a card pack list using python

I have the following list in python.
list = ['10♠', '10♣', '2♡', '4♠', '4♣', '5♡', '5♣', '6♡', '6♣', '7♠', '7♡', '7♢', '7♣', '8♡', '8♢', '8♣', '9♡', '9♢', '9♣', 'A♠', 'A♢', 'A♣', 'J♢', 'K♠', 'K♢', 'Q♡']
how can I remove pairs from this? As an example, if a number appears an odd number of times, the last appearance of it should be kept. All others should be removed. Including all the ones that appear an even number of times.
ex: From '9♡', '9♢', '9♣', only the '9♣' should be kept.
Can someone help me with this?
I tried to use the below code to identify indices first. But still no luck.
i = 0
while i < len(deck):
count = 0
k = len(deck[i])
pivot = i
j = i
while j < len(deck):
if deck[i][:k-1] == deck[j][:k-1]:
print(deck[i]+','+deck[j])
count+= 1
pivot = j
j+=1
if (count %2 != 0):
print('pivot:'+str(pivot))
i = pivot +1
i +=1
No need to consider symbols. Just want to remove pairs from the list.
Please provide your suggestions.
Is this what you are looking for?
from collections import defaultdict
deck = ['10♠', '10♣', '2♡', '4♠', '4♣', '5♡', '5♣', '6♡', '6♣', '7♠', '7♡', '7♢', '7♣', '8♡', '8♢', '8♣', '9♡', '9♢', '9♣', 'A♠', 'A♢', 'A♣', 'J♢', 'K♠', 'K♢', 'Q♡']
# Create a dictionary and group all the cards with same number
groups = defaultdict(list)
for card in deck:
key = card[:-1]
groups[key].append(card)
new_deck = []
for subgroup in groups.values():
# iterate through the dictionary
# If you have odd number of cards in a subgroup
# consider the last card in that subgroup
if len(subgroup)%2 == 1:
new_deck.append(subgroup[-1])
for card in new_deck:
print(card)
Output
2♡ 8♣ 9♣ A♣ J♢ Q♡
Edit: A minor simplification to the second iteration with groups.values, thanks to RoadRunner.
Group the card pairs into a collections.defaultdict, then only return the last card from uneven pairs in a new list using a list comprehension:
from collections import defaultdict
lst = ['10♠', '10♣', '2♡', '4♠', '4♣', '5♡', '5♣', '6♡', '6♣', '7♠', '7♡', '7♢', '7♣', '8♡', '8♢', '8♣', '9♡', '9♢', '9♣', 'A♠', 'A♢', 'A♣', 'J♢', 'K♠', 'K♢', 'Q♡']
cards = defaultdict(list)
for card in lst:
cards[card[:-1]].append(card)
result = [pairs[-1] for pairs in cards.values() if len(pairs) % 2]
print(result)
Output:
['2♡', '8♣', '9♣', 'A♣', 'J♢', 'Q♡']
Keeping the same order, you can use:
import re
l = ['10♠', '10♣', '2♡', '4♠', '4♣', '5♡', '5♣', '6♡', '6♣', '7♠', '7♡', '7♢', '7♣', '8♡', '8♢', '8♣', '9♡', '9♢', '9♣', 'A♠', 'A♢', 'A♣', 'J♢', 'K♠', 'K♢', 'Q♡']
nc, nl = [], [0]
for x in l:
clean = re.sub(r"[^A-Z\d]", "", x)
if clean != nl[-1]:
nl.append(clean)
nc.append(x)
else:
del nl[-1]
del nc[-1]
print(nc)
# ['2♡', '8♣', '9♣', 'A♣', 'J♢', 'Q♡']
Demo
First of all, list is a reserved keyword, you should never name your variables after reserved keywords, use lst instead of list
Now, Here is the minimal solution:
lst = ['10♠', '10♣', '2♡', '4♠', '4♣', '5♡', '5♣', '6♡', '6♣', '7♠', '7♡', '7♢', '7♣', '8♡', '8♢', '8♣', '9♡', '9♢', '9♣', 'A♠', 'A♢', 'A♣', 'J♢', 'K♠', 'K♢', 'Q♡']
dictionary = dict.fromkeys(list('A23456789JQK')+['10'])
for item in lst:
dictionary[item[:-1]] = item if dictionary[item[:-1]] is None else None
print(list(filter(None.__ne__, dictionary.values())))
output:
['A♣', '2♡', '8♣', '9♣', 'J♢', 'Q♡']

Matplotlib Auto Annotate max doesn't annotate and pushes chart off page

Hello I'm trying to auto annotate matplotlib chart.
I've manage to create it in a way that that doesn't give me any errors when I run it.
However, it doesn't plot the annotation and as I'm plotting in jupyter notebooks it pushes the plot right off the page.
The result I'm looking for is an automatically assigning annotation pointing to the max number in the series ppc_rolling_7d on the chart.
I'm kinda out of ideas as to what has happened here.
example data:
ppc_data = pd.DataFrame({
'Day':['2018-08-31', '2018-09-01', '2018-09-02', '2018-09-03',
'2018-09-04', '2018-09-05', '2018-09-06', '2018-09-07',
'2018-09-08', '2018-09-09', '2018-09-10', '2018-09-11',
'2018-09-12', '2018-09-13', '2018-09-14', '2018-09-15',
'2018-09-16', '2018-09-17', '2018-09-18', '2018-09-19',
'2018-09-20', '2018-09-21', '2018-09-22', '2018-09-23',
'2018-09-24', '2018-09-25', '2018-09-26', '2018-09-27',
'2018-09-28', '2018-09-29', '2018-09-30', '2018-10-01',
'2018-10-02', '2018-10-03', '2018-10-04', '2018-10-05',
'2018-10-06', '2018-10-07', '2018-10-08', '2018-10-09',
'2018-10-10', '2018-10-11', '2018-10-12', '2018-10-13',
'2018-10-14', '2018-10-15', '2018-10-16', '2018-10-17',
'2018-10-18', '2018-10-19', '2018-10-20', '2018-10-21',
'2018-10-22', '2018-10-23', '2018-10-24', '2018-10-25',
'2018-10-26', '2018-10-27', '2018-10-28', '2018-10-29',
'2018-10-30', '2018-10-31', '2018-11-01', '2018-11-02',
'2018-11-03', '2018-11-04', '2018-11-05', '2018-11-06',
'2018-11-07', '2018-11-08', '2018-11-09', '2018-11-10',
'2018-11-11', '2018-11-12', '2018-11-13', '2018-11-14',
'2018-11-15', '2018-11-16', '2018-11-17', '2018-11-18',
'2018-11-19', '2018-11-20', '2018-11-21', '2018-11-22',
'2018-11-23', '2018-11-24', '2018-11-25', '2018-11-26',
'2018-11-27', '2018-11-28', '2018-11-29', '2018-11-30',
'2018-12-01', '2018-12-02', '2018-12-03', '2018-12-04',
'2018-12-05', '2018-12-06', '2018-12-07', '2018-12-08'],
'Cost' : [1105.8097834013993, 1035.8355715930172, 2335.4700418958632,
655.0721024605979, 1154.3067936459986, 2275.8927050269917,
174.47816810392712,1606.0865381579742,973.1285739075876,
677.3734705782231,2381.149891233519, 1137.840620239881,
673.0575320194132, 1969.3783478235364, 1667.3405411738886,
1365.707089062391, 1686.492803446683, 1613.2530220414621,
2275.475164597224, 1593.9382082221036, 1278.8267306408893,
1342.2964464944962, 863.9840442789089, 289.34425736432837,
15.219941807702485, 1595.2327617943374, 1592.8333476628231,
961.5931139385652, 703.2690737772505, 312.9730830647801,
2105.920303495205, 707.710807657391, 873.7377744639931,
152.51387772605813, 1292.4027169055073, 1142.7323830723421,
2400.462099397225, 2027.5730000421765, 2380.127923249452,
370.97680360266463, 978.7472607817784, 144.50724935561453,
1257.3962926696906, 339.44922335906256, 989.3364341529344,
1274.7020560588671, 1697.9640365081489, 81.00819304765376,
528.9126509191693, 893.839100786781, 1778.7263797734338,
1388.1976452584615, 533.7823940180391, 1390.507110740847,
1582.8069647428326, 2058.124928605663, 1456.0037174730746,
315.93672830017414,488.9620970966599, 2020.6125475658266,
1358.8988386729175,1967.1442608919235,436.40540549351783,
2090.41730824453,2114.3435803364277,2235.719648814769,
1773.3190866160382,2372.165649889117, 1186.850504563462,
864.4092140750176, 772.6148714908818,1749.9856862684244,
802.1475898419487, 1013.3410373277948, 1604.4137362997474,
1880.084707526689, 1823.9691856540412,550.6041906641643,
75.26104973616485, 819.9409527114842, 2272.8529542934198,
1836.7071931445969,1491.3728333359875, 1807.2130424285615,
2378.1185581431337,1434.1809462567153,296.49945129452675,
2025.2054514729998,2346.234514785023, 2438.058561262957,
277.36529451533386, 1212.541281523483,2005.258496330315,
2053.7325650486177,2076.001012737591, 2245.606468047353,
2493.336539619115,1116.075112703116,319.54750552662733,
648.633853658328]}
).set_index('Day')
ppc_data.index = pd.to_datetime(ppc_data.index)
ppc_weekly = ppc_data['Cost'].resample('W').mean()
ppc_rolling_7d = ppc_data['Cost'].rolling(window=7, center=True).mean()
ax = fig.add_subplot(111)
figsize = (15,8)
ppc_data['Cost'].plot(figsize=figsize,
alpha=.5,
marker='.',
linestyle='-',
linewidth=0.5,
label='Daily'
)
ppc_weekly.plot(figsize=figsize,
marker='x',
markersize=8,
linestyle='-',
label='Weekly Mean Resample'
)
ppc_rolling_7d.plot(figsize=figsize,
marker='o',
linestyle='-',
label='7-d Rolling Mean'
)
max_value = ppc_rolling_7d.max()
max_value_index = [i for i, j in enumerate(ppc_rolling_7) if j == max_value]
#Create ax customatisations
ax.annotate('Lots of Pageviews but few clicks',
xy=(max_value_index[0],max_value),
xytext=(max_value_index[0],max_value),
arrowprops=dict(facecolor='cyan', #colour
shrink=0.05, #length of arrow
lw=1, #line width
ec='magenta', #boarder colour
zorder=1)) #layering order of annotation
#Global Plot settings
plt.title('COMPARE: Daily, Weekly Mean, 7-d Rolling Mean ') # set chart name
fig.legend() # set the legend
#display the charts
plt.show()
Any suggestions to what could be the problem are welcome.
Thanks to ImportanceOfBeingErnest who commented with the answer.
Using idxmax() will quickly find the index of the max value.
x = ppc_rolling_7d.idxmax(); y = ppc_rolling_7d.max()

Get A Random Value from dictionary in Python

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)

Categories