The best way to replace multiple if-statementes with a dictionary - python

I have a multiple condition:
if you == 1 or you == 2:
one.put(argument)
elif you == 3:
return None
elif you == 4:
two.put(argument)
elif you == 5:
three.put(argument)
elif you == 6:
four.put(argument)
elif you == 7:
five.put(argument)
elif you == 8:
six.put(argument)
elif you == 9:
seven.put(argument)
elif you == 10:
eight.put(argument)
elif you == 11:
nine.put(argument)
elif you == 12:
ten.put(argument)
I want to change it to use a dictionary, but I get exceptions in:
if you == 1 or you == 2:
one.put(argument)
elif you == 3:
return None
What is the best way to do this?

This will work:
actions = {1: one.put,
2: one.put,
3: None,
4: two.put,
# ....
}
action = actions.get(you)
if callable(action): # guards against non existing "you"'s or if you == 3
action(argument)
# can also do this:
# if action is not None:
# action(argument)
# or that..
# try:
# action(argument)
# except TypeError: # if action is None we'll get an exception, NoneType isn't callable
# pass

Store the varying part of your expression in a dictionary.
I put 3 in there as well, just for completeness, and possible later use.
put_dict = {
1: one, 2: one,
3: None
4: two, 5: three,
6: four, 7: five,
8: six, 9: seven,
10: eight, 11: nine,
12: ten
}
if you == 3:
return None
else:
put_dict[you].put(argument)

I'd create a sink for the values you don't want:
class Sink:
#staticmethod
def put(object):
pass
put_dict = {
1: one, 2: one,
3: Sink,
4: two, 5: three,
6: four, 7: five,
8: six, 9: seven,
10: eight, 11: nine,
12: ten}
def function(you, argument)
put_dict[you].put(argument)

Related

how to elimate the need for a large number of if elif else statements

My script uses a if elif else check to determine which array item to look at for crafting values. The issue is there are a total of 24 elif statements to allow for a total of 26 choices, (1 for the if, 1 for error catching). What I'm trying to figure out is how to reduce the number of elif statements so the code is better structured.
while choice == 0:
choice = input("Choose a block (Enter only the Number):")
if not choice.isalpha(): # Makes sure that the input is a number and not a string.
choice = int(choice)
else:
choice = 0
print("Thats not a number. Choose a number Numbnuts.")
if choice == 1:
print("\n",block[0])
elif choice == 2:
print("\n",block[1])
elif choice == 3:
print("\n",block[2])
elif choice == 4:
print("\n",block[6])
elif choice == 5:
print("\n",block[7])
elif choice == 6:
print("\n",block[8])
elif choice == 7:
print("\n",block[3])
elif choice == 8:
print("\n",block[4])
elif choice == 9:
print("\n",block[5])
elif choice == 10:
print("\n",block[9])
elif choice == 11:
print("\n", block[10])
elif choice == 12:
print("\n", block[11])
elif choice == 13:
print("\n",block[12])
elif choice == 14:
print("\n",block[13])
elif choice == 15:
print("\n",block[14])
elif choice == 16:
print("\n",block[15])
elif choice == 17:
print("\n",block[16])
elif choice == 18:
print("\n",block[17])
elif choice == 19:
print("\n",block[18])
elif choice == 20:
print("\n",block[19])
elif choice == 21:
print("\n",block[20])
elif choice == 22:
print("\n", block[21])
elif choice == 23:
print("\n", block[22])
elif choice == 24:
print("\n",block[23])
elif choice == 25:
print("\n",block[24])
elif choice == 26:
print("\n",block[25])
Look for structure:
elif choice == 12:
print("\n", block[11])
elif choice == 13:
print("\n",block[12])
elif choice == 14:
print("\n",block[13])
elif choice == 15:
print("\n",block[14])
elif choice == 16:
print("\n",block[15])
Clearly, this is the same as;
print("\n", block[choice - 1])
However, for choice in {4,5,6,7,8,9} the logic isn't that simple, so you could keep the ifs:
if choice == 4:
print("\n",block[6])
elif choice == 5:
print("\n",block[7])
elif choice == 6:
print("\n",block[8])
elif choice == 7:
print("\n",block[3])
elif choice == 8:
print("\n",block[4])
elif choice == 9:
print("\n",block[5])
else:
print("\n", block[choice - 1])
You could also go a step deeper: for choice in {4,5,6} the index is choice-2, and for choice in {7,8,9} the index is choice-4:
if choice in {4,5,6}:
idx = choice - 2
elif choice in {7,8,9}:
idx = choice - 4
else:
idx = choice - 1
print("\n", block[idx])
As another answer suggested, look for structure; you have different ranges of choices that correspond to different offsets in block, so you can iterate over those:
while True:
try:
choice = input("Choose a block (Enter only the Number):")
except ValueError:
print("Thats not a number. Choose a number Numbnuts.")
continue
if choice < 1 or choice > 26:
continue
print("\n")
for limit, offset in ((3, -1), (6, 2), (9, -4), (26, -1)):
if choice <= limit:
print(block[choice + offset])
break
break
Hence for 1 <= choice <= 3 you print block[choice-1], for 4 <= choice <= 6 you print block[choice+2], and so on.
my version:
block_2 = block[:3]+block[6:9]+block[3:6]+block[9:]
print("\n", block_2[choice - 1])

iterate over pd dataframe to change integers to strings [duplicate]

This question already has answers here:
Remap values in pandas column with a dict, preserve NaNs
(11 answers)
Closed 4 years ago.
It's a very basic question but somehow my loop does not work. I have a pandas dataframe with two columns; path and word. A neural network predicted the outcome value in word, however this is still an integer. I wrote a for loop to replace those integers with words but there are no changes in the df. My df:
path word
0 f7f172c01bec6a3e9a36dcafdf9e02e7df3522e4.wav 21
1 c17c29e392c57a9243ed52175568b40c04912194.wav 21
2 eea9239d4986b1f7dbffdcce76e0fce6e5f38ca8.wav 21
3 4fec4b033ba19d1ac875c0c062fda2869dbece73.wav 21
my loop:
for i in df['word']:
if i == 0:
i == "backward"
elif i == 1:
i == "bed"
elif i == 2:
i == "bird"
elif i == 3:
i == "cat"
elif i == 4:
i == "dog"
elif i == 5:
i == "down"
elif i == 6:
i == "eight"
elif i == 7:
i == "five"
elif i == 8:
i == "follow"
elif i == 9:
i == "forward"
elif i == 10:
i == "four"
elif i == 11:
i == "go"
elif i == 12:
i == "happy"
elif i == 13:
i == "house"
elif i == 14:
i == "learn"
elif i == 15:
i == "left"
elif i == 16:
i == "marvin"
elif i == 17:
i == "nine"
elif i == 18:
i == "no"
elif i == 19:
i == "off"
elif i == 20:
i == "on"
elif i == 21:
i == "one"
elif i == 22:
i == "right"
elif i == 23:
i == "seven"
elif i == 24:
i == "sheilla"
elif i == 25:
i == "six"
elif i == 26:
i == "stop"
elif i == 27:
i == "three"
elif i == 28:
i == "tree"
elif i == 29:
i == "two"
elif i == 30:
i == "up"
elif i == 31:
i == "visual"
elif i == 32:
i == "wow"
elif i == 33:
i == "yes"
elif i == 34:
i == "zero"
You can use pd.Series.map:
#Add the rest of your mapping here (I just included a few)
mapping = {0: 'backward', 1: 'bed', 21: 'one', 22: 'right'}
df['word'] = df['word'].map(mapping)
Returns:
path word
0 f7f172c01bec6a3e9a36dcafdf9e02e7df3522e4.wav one
1 c17c29e392c57a9243ed52175568b40c04912194.wav one
2 eea9239d4986b1f7dbffdcce76e0fce6e5f38ca8.wav one
3 4fec4b033ba19d1ac875c0c062fda2869dbece73.wav one

How to condense if statments [duplicate]

This question already has answers here:
What's an alternative to if/elif statements in Python? [duplicate]
(3 answers)
Closed 5 years ago.
I am making a program in python that will play the game of war. I was wondering if there is a way to condense all the if statements to a simpler code. I need to pick a random number from 1-13 and those numbers relate to one of the cards in a deck. 1=Ace, 2=2 ... 11=Jack, 12=Queen, 13=King. I have not learned any functions yet so I cannot use any of those.
while player_picked == computer_picked:
player_picked = random.randint(1,13)
computer_picked = random.randint(1,13)
if player_picked == 1:
card_picked_player = "Ace"
if player_picked == 2:
card_picked_player = "Two"
if player_picked == 3:
card_picked_player = "Three"
if player_picked == 4:
card_picked_player = "Four"
if player_picked == 5:
card_picked_player = "Five"
if player_picked == 6:
card_picked_player = "Six"
if player_picked == 7:
card_picked_player = "Seven"
if player_picked == 8:
card_picked_player = "Eight"
if player_picked == 9:
card_picked_player = "Nine"
if player_picked == 10:
card_picked_player = "Ten"
if player_picked == 11:
card_picked_player = "Jack"
if player_picked == 12:
card_picked_player = "Queen"
if player_picked == 13:
card_picked_player = "King"
if computer_picked == 1:
card_picked_computer = "Ace"
if computer_picked == 2:
card_picked_computer = "Two"
if computer_picked == 3:
card_picked_computer = "Three"
if computer_picked == 4:
card_picked_computer = "Four"
if computer_picked == 5:
card_picked_computer = "Five"
if computer_picked == 6:
card_picked_computer = "Six"
if computer_picked == 7:
card_picked_computer = "Seven"
if computer_picked == 8:
card_picked_computer = "Eight"
if computer_picked == 9:
card_picked_computer = "Nine"
if computer_picked == 10:
card_picked_computer = "Ten"
if computer_picked == 11:
card_picked_computer = "Jack"
if computer_picked == 12:
card_picked_computer = "Queen"
if computer_picked == 13:
card_picked_computer = "King"
Use a list, and then index the list.
cards = ["Ace", "Two", "Three", ..., "King"]
card_picked_player = cards[player_picked-1]
card_picked_computer = cards[computer_picked-1]
You can also select directly from the list if you don't need the numeric value.
card_picked_player = random.choice(cards)
card_picked_computer = random.choice(cards)

i keep getting attribute error randint

everytime I run my code I get attribute error and int has no randint, but when I looked online how to do random, that is what it told me to do, please help.
def gorandom():
if random.randint(1,8) == 1:
turtle.goto(-250,250)
elif random.randint(1,8) == 2:
turtle.goto(0,250)
elif random.randint(1,8) == 3:
turtle.goto(250,250)
elif random.randint(1,8) == 4:
turtle.goto(250,0)
elif random.randint(1,8) == 5:
turtle.goto(250,-250)
elif random.randint(1,8) == 6:
turtle.goto(0,-250)
elif random.randint(1,8) == 7:
turtle.goto(-250,-250)
else:
turtle.goto(-250,0)
You are missing an import. Please add
import random
To the top of your file.
try this:
import random
def gorandom():
if random.randint(1,8) == 1:
turtle.goto(-250,250)
elif random.randint(1,8) == 2:
turtle.goto(0,250)
elif random.randint(1,8) == 3:
turtle.goto(250,250)
elif random.randint(1,8) == 4:
turtle.goto(250,0)
elif random.randint(1,8) == 5:
turtle.goto(250,-250)
elif random.randint(1,8) == 6:
turtle.goto(0,-250)
elif random.randint(1,8) == 7:
turtle.goto(-250,-250)
else:
turtle.goto(-250,0)
And be sure your goto(x,y) function works ;)
found solution, thanks guys for help
from random import randint
def gorandom():
if randint(1,8) == 1:
turtle.goto(-250,250)
elif randint(1,8) == 2:
turtle.goto(0,250)
elif randint(1,8) == 3:
turtle.goto(250,250)
elif randint(1,8) == 4:
turtle.goto(250,0)
elif randint(1,8) == 5:
turtle.goto(250,-250)
elif randint(1,8) == 6:
turtle.goto(0,-250)
elif randint(1,8) == 7:
turtle.goto(-250,-250)
else:
turtle.goto(-250,0)

Appending specific values to a list while iterating from a string using a for loop

Basically I need help creating a function to read a given parameter which is a list, go through each digit of the list, checking them and adding their binary value to a different list. I am trying this code, but it's not working the way I think it should. Any help is welcome: The side parameter is there to help sort the binary. I have two sets and depending on which 'side' the digits in the list are on, they have a different binary code.
def bin_convert(upc, side):
bin_list = []
if side == 0:
for digit in upc:
if digit == 0:
bin_list.append(0001101)
elif digit == 1:
bin_list.append(0011001)
elif digit == 2:
bin_list.append(0010011)
elif digit == 3:
bin_list.append(0111101)
elif digit == 4:
bin_list.append(0100011)
elif digit == 5:
bin_list.append(0110001)
elif digit == 6:
bin_list.append(0101111)
elif digit == 7:
bin_list.append(0111011)
elif digit == 8:
bin_list.append(0110111)
elif digit == 9:
bin_list.append(0001011)
print bin_list
return bin_list
else:
for digit in upc:
if digit == 0:
bin_list.append(1110010)
elif digit == 1:
bin_list.append(1100110)
elif digit == 2:
bin_list.append(1101100)
elif digit == 3:
bin_list.append(1000010)
elif digit == 4:
bin_list.append(1011100)
elif digit == 5:
bin_list.append(1001110)
elif digit == 6:
bin_list.append(1010000)
elif digit == 7:
bin_list.append(1000100)
elif digit == 8:
bin_list.append(1001000)
elif digit == 9:
bin_list.append(1110100)
print bin_list
return bin_list

Categories

Resources