Change colour of ALL text depending on one value in a dictionary - python

I'm trying to print all items in a dictionary and change the text colour dependant on the data in one value (Red for Fire / Blue for Water etc)
But instead of the whole dictionary, I can only get it to print the key:value pair for the single item containing that text.
Name: Nina The Cat
Type: Fire
Special Move: Purring
Starting HP: 50
Starting MP: 50
for key, value in my_dictionary.items():
if my_dictionary[key] == "Fire":
print (f"\033[33m{key}: \033[31m{value}")
#Key = Yellow , Value = Red
Type: Fire

You want to check if my_dictionary['Type'] == "Fire" and decide the colors before you start printing all the key-value pairs. In the loop, format these colors into your string to print in addition to the key and value
if my_dictionary['Type'] == "Fire":
color_key = "\033[33m"
color_val = "\033[31m"
else:
color_key = # insert reset color code here
color_val = # and here
for key, value in my_dictionary.items():
print(f"{color_key}{key}: {color_val}{val}")

Perhaps this solution will help you in solving your problem.
my_dictionary = {
'Fire': 'Red',
'Water': 'Blue'
}
colors = {
'Red': '\033[31m',
'Blue': '\033[34m'
}
key_color = '\033[33m'
for key, value in my_dictionary.items():
print(f"{key_color + key}: {colors[value] + value}")

Related

remove keyword frequency from a key phrase which has the same keyword

I have a list of keyword frequency as the following, the frequency is counted by matching the keyword to the responses. However, I want to remove the frequency of "public health", "health issue", and "health condition" from "health". Also, remove the frequency of "public health officials" from the "public health". I am wondering, how can I do this in Python?
keyword
frequency
health
56
healthcare
23
health condition
5
health issue
4
public health
7
public health official
2
Build on the previous answer, I figure it out as the following:
Tokenize the keyword and find the max keyword length
Loop through the keyword column from the max length to a single word
Remove duplicated keyword frequency if keywords with smaller length appear within a
bigger keyphrase
Update the previous dataframe
import pandas as pd
import numpy as np
import spacy
import en_core_web_md
nlp = en_core_web_md.load()
df = .....
df_3 = df
# find the max length of the column value
max_length = df["keyword"].map(lambda x: len(nlp(x))).max()
length = max_length
# loop until the length ends with column value that only have one word
while length > 1 :
element = []
value = []
element_2 = []
value_2 = []
element_3 = []
value_3 = []
# select column value by different length
for index, row in df_3.iterrows():
a = len(nlp(row["keyword"]))
if a == length:
element.append(row["keyword"])
value.append(row["frequency"])
if a < length:
element_2.append(row["keyword"])
value_2.append(row["frequency"])
if a > length:
element_3.append(row["keyword"])
value_3.append(row["frequency"])
d_1 = dict(zip(element, value))
d_2 = dict(zip(element_2, value_2))
d_3 = dict(zip(element_3, value_3))
# remove duplicated keyword frequency if keyword with smaller length
appear in key phrase with bigger length
for key1, value1 in d_1.items():
for key2, value2 in d_2.items():
if key2 in key1:
d_2[key2] = value2-value1
new_key = []
new_value = []
# update the original dataframe
for key, value in d_2.items():
new_key.append(key)
new_value.append(value)
for key, value in d_1.items():
new_key.append(key)
new_value.append(value)
for key, value in d_3.items():
new_key.append(key)
new_value.append(value)
df_3 = pd.DataFrame({"keyword":new_key, "frequency":new_value})
length -= 1
The answer looks pretty dump, welcome one more elegant~
With this script, you can specify the value to substract from with the variable ele.
Then every element that starts with the ele will be substracted.
For public health, you would just mirror the same code with a ele = "public health" before.
d = {
"health" : 56,
"healthcare" : 23,
"health condition" : 5,
"health issue" : 4,
"public health" : 7,
"public health official" : 2,
}
ele = "health"
for key, value in d.items():
if (key != ele) or not key.startswith("ele"):
d[ele] -= value
print(d[ele]) #-41

straight flush and royal flush for poker in python

Here is some code I have so far for a poker game and I got the def main to show some of the hands but I can't figure out to get the straight flush and royal flush. Also how would I go about doing the high card?
The card number values 0-12 are one suit, 13-25 are the next, 26-38, and 39-51.
Also if anyone can tell me how I'd implement this PokerHand class into another def main window.
class PokerHand:
"""class for representing a poker hand"""
# Poker value of hands in increasing order so they can be compared
HIGH_CARD = 0
TWO_OF_A_KIND = 1
TWO_PAIRS = 2
THREE_OF_A_KIND = 3
STRAIGHT = 4
FLUSH = 5
FULL_HOUSE = 6
FOUR_OF_A_KIND = 7
STRAIGHT_FLUSH = 8
# hand names for printing the card names
HAND_NAMES = ('High Card', 'Two of a Kind', 'Two Pairs', 'Three of a Kind',
'Straight', 'Flush', 'Full House', 'Four of a Kind',
'Straight Flush')
#------------------------------------------------------------------
def __init__(self):
"""initialize empty hand"""
self.cards = []
#------------------------------------------------------------------
def addCard(self, cardNumber):
"""add cardNumber to the hand"""
self.cards.append(cardNumber)
#------------------------------------------------------------------
def evalHand(self):
"""determine the value of the hand and return a tuple; the
first value in the tuple is an integer corresponding to the
hand value using the constants HIGH_CARD, TWO_OF_A_KIND, etc.;
the remaining values in the tuple depend on the type of hand
and are described below to break ties based on the face values
of the cards
for HIGH_CARD, it is five values: the face values sorted in
descending order
for TWO_OF_A_KIND, it is four values: the face value for the
pair, followed by the face values of the other cards in
descending order
for TWO_PAIRS, it is three values: the face value of the
higher pair, the face value of the lower pair, followed by the
face value of the other card
for THREE_OF_A_KIND, it is three values: the face value of the
three of a kind, followed by the face value of the other two
cards in descending order
for STRAIGHT, it is one value: the face value of the lowest
card in the straight
for FLUSH, it is five values: the face values sorted in
descending order
for FULL_HOUSE, it is two values: the face value of the three
of a kind, followed by the face value of the pair
for FOUR_OF_A_KIND, it is two values: the face value that
there are four of followed by the face value that there is one
of
for STRAIGHT_FLUSH, it is one value: the face value of the
lowest card in the straight"""
faces = [0,0,0,0,0,0,0,0,0,0,0,0,0]
for value in self.cards:
face = value % 13
faces[face] += 1
suits = [0,0,0,0]
for value in self.cards:
suit = value // 13
suits[suit] += 1
if faces.count(2) == 1 and faces.count(1) == 3:
return self.TWO_OF_A_KIND
elif faces.count(2) == 2 and faces.count(1) == 1:
return self.TWO_PAIRS
elif faces.count(3) == 1 and faces.count(1) == 2:
return self.THREE_OF_A_KIND
elif faces.count(3) == 1 and faces.count(2) == 1:
return self.FULL_HOUSE
elif faces.count(4) == 1 and faces.count(1) == 1:
return self.FOUR_OF_A_KIND
elif faces.count(1) == 5:
pos = faces.index(1)
if faces[pos:pos+5] == [1,1,1,1,1] or faces[pos:pos+13] == [1,0,0,0,0,0,0,0,0,1,1,1,1]:
return self.STRAIGHT
if suits.count(5) == 1 and suits.count(1) == 0:
return self.FLUSH
if suits.count(5) == 1 and faces.count(1) == 5:
pos = faces.index(1)
if faces[pos:pos + 5] == [1, 1, 1, 1, 1] or faces[pos:pos + 13] == [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]:
return self.STRAIGHT_FLUSH
return self.STRAIGHT_FLUSH
#----------------------------------------------------------------------
def main():
hand = PokerHand()
hand.addCard(9)
hand.addCard(10)
hand.addCard(8)
hand.addCard(11)
hand.addCard(7)
r = hand.evalHand()
print(r)
print(PokerHand.HAND_NAMES[r])
if __name__ == '__main__':
main()
Consider putting your hand conditionals in functions
This will help your code readability and also make it more testable.
E.g.
def is_flush(suits):
return suits.count(5) == 1
Make sure lower value hands don't short circuit higher ones
If you rearrange the order of your hand conditionals, putting higher value tests first, you will catch the more specific case first and you won't accidentally return prematurely.
You could think of hands as being of two non-exclusive types: suit based and face based. Suit conditions are "flush" or "non-flush" so it might read well to flag this up front.
Then you have a face combos, some of which "intersect" with flush_flag to increase their value.
Or... you can keep your hand test ordered the way you have, it might be more optimal since you are testing for more frequent hands earlier. If you do this make sure your conditionals are "complete". I.e. if the hand is a two-of-a-kind you must also make sure it's not a two-pair or any of the other hands that contain two-of-a-kind. You are doing this with your faces.count(2) == 1 and faces.count(1) == 3. You need to follow the same "completeness" for STRAIGHT and FLUSH.

Getting elements from a table and counting total

I have a table as such representing the result of a game.
GameTab = [['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']]
I appended the result from a text file into table form so here's the text format: To put it easier, it's interpreted in such that for example, TRE scored 1 and ARD scored 1. PRK scored 2 and GEA score 3.
TRE:ARD:1:1
PRK:GEA:2:3
ARD:PRK:1:0
TRE:GEA:2:1
Instead of obtaining the result for the player, i want to obtain the result of the opponent instead. I have done my code in a way where it obtains the result of the player but i couldn't think of a way to obtain the opponents result.
For example, in the match of PRK:GEA and TRE:GEA:
The opponent of GEA scored a total of: 4
My code:
gameTab =[['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],
['TRE','GEA','2','1']]
dictionary = {}
for i in gameTab:
for c in range(len(i[:2])):
if i[:2][c] not in dictionary.keys():
dictionary[i[:2][c]] = int(i[2:][c])
else:
dictionary[i[:2][c]] += int(i[2:][c])
print(dictionary)
In order to obtain the result of the opponent against a team, The below code satisfied the condition:
gameTab =[['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']]
dictionary = {}
for i in gameTab:
if i[0] in dictionary:
dictionary[i[0]] += int(i[3])
else:
dictionary[i[0]] = int(i[2])
if i[1] in dictionary:
dictionary[i[1]] += int(i[2])
else:
dictionary[i[1]] = int(i[2])
print(dictionary)
it prints out: {'ARD': 1, 'GEA': 4, 'TRE': 2, 'PRK': 3}
Basically traverse the list of lists, and for every team check if it exists in dictionary then increment its value as the opponents value. And finally you would get all point scored against a team by the opposition.
gametab = [['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']]
dicta = {}
for i in range(len(gametab)):
for j in range(2):
if gametab[i][j] in dicta:
dicta[gametab[i][j]] += int(gametab[i][j+2])
else:
dicta[gametab[i][j]] = int(gametab[i][j+2])
print dicta

Why print the wrong result?

I am a new guy in python,Today I write a program to get max value pair from some data sets,but the program I wrote did't give me the right answer,the code is
#!/usr/bin/python
import sys
maxsale = 0
oldKey = None
# Loop around the data
# It will be in the format key\tval
# Where key is the store name, val is the sale amount
#
# All the sales for a particular store will be presented,
# then the key will change and we'll be dealing with the next store
for line in sys.stdin:
data_mapped = line.strip().split("\t")
if len(data_mapped) != 2:
# Something has gone wrong. Skip this line.
continue
thisKey, thisSale = data_mapped
if oldKey and oldKey != thisKey:
print oldKey, "\t", maxsale
oldKey = thisKey;
oldsale = 0
oldKey = thisKey
if maxsale < thisSale:
maxsale = thisSale
if oldKey != None:
print oldKey, "\t", maxsale
the data sets is:
Anchorage 298.86
Anchorage 6.38
Aurora 34.1
Aurora 10.6
Aurora 55.7
Austin 327.75
Austin 379.6
Austin 469.63
Austin 11.6
The result is:
Anchorage 6.38
Aurora 34.1
Austin 469.63
Can anyone help me deal with this issue?thank you in advance!
First, you are not converting the inputs to numbers. This means that any "number" that starts with '6' is greater than any "number" that starts with '2', even for values like '6.38' and '198.86'.
thisKey, thisSale = data_mapped
thisSale = float(thisSale)
Next, you are setting oldSale to 0, but never referring to it. I think you meant to do maxSale = 0 there, to reset the value for a new store.
Lastly, you don't need oldKey = thisKey; in the if block, as you're doing that immediately afterward anyway.
Note that currency calculations work best when you convert the values to the smallest denomination of that currency and use integers, as floating-point calculations aren't always perfectly accurate and you may get rounding errors. It looks like your data aren't guaranteed to have trailing zeros, so you would have to check the string for a decimal point, split on the decimal point if it exists, and so on.
thisKey, thisSale = data_mapped
if '.' not in thisSale:
thisSale = int(thisSale)*100
else:
dollars, cents = thisSale.split('.')
if len(cents) < 2:
cents += '0'
thisSale = int(dollars)*100 + int(cents)
Carry out financial calculations on the integer representing the number of cents, and then format values as dollars and cents when necessary for display purposes:
>>> '%.2f' % (29886/100.)
'298.86'
>>> '{:.02f}'.format(29886/100.)
'298.86'
#!/usr/bin/python
import sys
maxsale = 0
oldKey = None
# Loop around the data
# It will be in the format key\tval
# Where key is the store name, val is the sale amount
#
# All the sales for a particular store will be presented,
# then the key will change and we'll be dealing with the next store
d = dict()
for line in sys.stdin:
data_mapped = line.strip().split("\t")
if len(data_mapped) != 2:
# Something has gone wrong. Skip this line.
continue
key,value = data_mapped
if (key in d) and d[key] < float(value):
d[key] = float(value)
elif not key in d:
d[key] = float(value)
for k,v in d.items():
print k,'\t',v

How can i store values in my dictionary

bag contains:
['Item','item','item']
coins contains:
['Item','Item','Item']
coin_to_bag = {}
print('Here are your bags:\n')
print(bags)
print('\n')
print('Here are your coin types:\n')
print (coins)
my nested loop
bags = ['small', 'medium','large']
coins = ['quarter', 'dime', 'nickel', 'penny']
'''
what Im trying to do:
foreach bag in bags:
print: enter in a coin index. e.g. 1 for quarter out of ['quarter', 'dime', 'nickel', 'penny']
prompt:: how many of this type? 15 (thus will store '15' representing, there are 15 quarters, storing '15')
for index_position in coins:
assign index, type = bag create a dictionary like ["quarter"] = {"1", "15"}}
print(coin_to_bag)
'''
for bag in bags:
coin_to_bag = coin_to_bag[bag] # set quarter as a key in coin_to_bag = {["quarter"]}
coin_type = input('Number of this type? e.g. type 1 for Quarter "["Quarter", "Nickel"]" ') #e.g. 0.25 * 2
coin_amount = input('Number of this type? e.g. 15') #e.g. 0.25 * 2
for coin in coins:
#set values for key: quarter like {["quarter"] = ["1", "15"]}
coin_to_bag[bag] = coin_to_bag[coin_type], coin_to_bag[coin_amount]
print(coin_to_bag)
I can't seem to figure out how to use my dictionary and lists(coin,bags)
Ultimately I'm trying to get coin_to_bag to store:
coin_to_bag = {"small": {"1", "15"}, "medium": {"2", "5"} }
Values are stored to dictionaries in this way:
some_dict = {}
some_dict[key] = value
Or in one line as: some_dict = {key: value}.
So presumably, you want:
coin_to_bag[bag] = [coin_type, coin_amount]
For example this might mean,
coin_to_bag['small'] = ["1", "15"]
Doing this, coin_to_bag[bag] means access the element of the coin_to_bag dictionary with the key given by bag. But that key-value won't exist until you set it.

Categories

Resources