I'm working on this code that basically gives output based on the input (the users names) that the user give, i need help/ advice on how i can differentiate the output given based on the name.
i've tried if statements, but its really basic detecting, since i've only studied python not so long ago.
# var
import random
nopes = ("nope1", "nope2", "nope3")
list1 = 1
list2 = 2
list3 = 3
list4 = 4
list5 = 5
list6 = 6
list7 = 7
list8 = 8
list9 = 9
# functions
def mainfunc():
if a in "name1":
print(list1)
elif a in "name2":
print(list2)
elif a in "name3":
print(list3)
elif a in "name4":
print(list4)
elif a in "name5":
print(list5)
elif a in "name6":
print(list6)
elif a in "name7":
print(list7)
elif a in "name8":
print(list8)
elif a in "name9":
print(list9)
else:
talk()
def talk():
print(random.choice(nopes))
#syntax's
a = input("What's your name? : ")
mainfunc()
yes, it works. but with a single typo the code would not work as i expected, and im trying to avoid that.
I don't completely get the intention of your code, but if you want to print differnt lists based on the input, you could use a dictionary instead of the several list#-objects.
lists = {
"name1": ["a","b","c"],
"name2": ["d","e","f"]
}
a = "name1"
if (a in lists.keys()):
print(lists[a])
# Output: ['a', 'b', 'c']
That way, you just have to maintain the dictionary object and not many single objects and the elseifs
Related
I am writing a program that can take in three numbers and three letters on seperate lines. The program will then seperate the numbers into items of a list and will do the same for the letters in a separate list. The program will then sort the the numbers from lowest to highest. I then want to assign the numbers to letters (In a sorted letter order (I.E. A=5, B=16, C=20) and then print the letters in the order it came in from the input (I.E. Input: CAB, output: 20 5 16). I have been able to sort the variables and can do all of this with if statements and for loops but I feel like there is a prettier and more efficient way of doing this. I want to be able to take the input letter string that's divided by use of a list and format the string to insert the variables in the correct order. I know that the globals() and locals() functions do something similar to this but can not figure out how to use them. Any ideas?
Working code:
nput_numbers_list = ((input()).split(" "))
input_letters = (input())
input_letters_list = []
for i in range(3):
input_letters_list.append(input_letters[i])
input_numbers_list = [int(x) for x in input_numbers_list]
input_numbers_list.sort()
print_string = ""
for i in range(3):
if input_letters[i] == "A":
print_string = print_string + A + " "
if input_letters[i] == "B":
print_string = print_string + B + " "
if input_letters[i] == "C":
print_string = print_string + C + " "
print(print_string)
My (wanted) code:
input_numbers_list = ((input()).split(" "))
input_letters = (input())
input_letters_list = []
for i in range(3):
input_letters_list.append(input_letters[i])
input_numbers_list = [int(x) for x in input_numbers_list]
input_numbers_list.sort()
A = str(input_numbers_list[0])
B = str(input_numbers_list[1])
C = str(input_numbers_list[2])
final_list = ["""Magic that turns input_letters_list into variables in the order used by list and then uses that order"""]
print("{} {} {}".format("""Magic that turns final_list into variables in the order used by list and then puts it in string""")
Wanted/expected input and output:
Input: "5 20 16"
Input: "CAB"
Output: "20 5 16"
As others have suggested, you will likely want an answer that uses a dictionary to lookup numbers given letters.
##----------------------
## hardcode your input() for testing
##----------------------
#input_numbers = input()
#input_letters = input()
input_numbers = "5 20 16"
input_letters = "CAB"
input_numbers_list = input_numbers.split(" ")
input_letters_list = list(input_letters) # not technically needed
##----------------------
##----------------------
## A dictionary comprehension
# used to construct a lookup of character to number
##----------------------
lookup = {
letter: number
for letter, number
in zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
)
}
##----------------------
##----------------------
## use our original letter order and the lookup to produce numbers
##----------------------
result = " ".join(lookup[a] for a in input_letters_list)
##----------------------
print(result)
This will give you your requested output of:
20 5 16
There is a lot going on with the construction of the dictionary lookup, so let's unpack it a bit.
First of, it is based on calling zip(). This function takes two "lists" and pairs their elements up creating a new "list". I use "list" in quotes as it is more like iterables and generators. Anyways. let's take a closer look at:
list(zip(["a","b","c"], ["x","y","z"]))
this is going to give us:
[
('a', 'x'),
('b', 'y'),
('c', 'z')
]
So this is how we are going to pairwise combine our numbers and letters together.
But before we do that, it is important to make sure that we are going to pair up the "largest" letters with the "largest" numbers. To ensure that we will get a sorted version of our two lists:
list(
zip(
sorted(input_letters_list), #ordered by alphabet
sorted(input_numbers_list, key=int) #ordered numerically
)
)
gives us:
[
('A', '5'),
('B', '16'),
('C', '20')
]
Now we can feed that into our dictionary comprehension (https://docs.python.org/3/tutorial/datastructures.html).
This will construct a dictionary with keys of our letters in the above zip() and values of our numbers.
lookup = {
letter: number
for letter, number
in zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
)
}
print(lookup)
Will give us our lookup dictionary:
{
'A': '5',
'B': '16',
'C': '20'
}
Note that our zip() technically gives us back a list of tuples and we could also use dict() to cast them to our lookup.
lookup = dict(zip(
sorted(input_letters_list),
sorted(input_numbers_list, key=int)
))
print(lookup)
also gives us:
{
'A': '5',
'B': '16',
'C': '20'
}
But I'm not convinced that clarifies what is going on or not. It is the same result though so if you feel that is clearer go for it.
Now all we need to do is go back to our original input and take the letters one by one and feed them into our lookup to get back numbers.
Hope that helps.
Its very weird the case when you need to conver string to a variable, when you feel that you need something like that a dictionary will probably do the trick.
in this case the solution can be done with the following code.
input_numbers_list = (("5 20 16").split(" "))
input_letters = ("CAB")
input_letters_list = [letter for letter in input_letters]
input_numbers_list = [int(x) for x in input_numbers_list]
rules = {}
for letter, value in zip(input_letters_list, input_numbers_list):
rules[value] = letter
output = ""
input_numbers_list.sort()
for numb in input_numbers_list:
output += rules[numb] + " "
print(output)
And you can use it for n inputs and outputs.
The idea of a dictionary is that you have keys, and values, so for a key (in this case text of letters) you can get a value, similar to a variable. Plus is super fast.
You could use a dictionary for that! https://www.w3schools.com/python/python_dictionaries.asp
EDIT: the output is more consistent with the requested one, but it should be "20 16 5" instead of "20 5 16" if I understood your problem well.
input_numbers_list = input().split(" ")
input_letters = input()
# Create new dictionary
input_dict = {}
# Fill it by "merging" both lists
for index, letter in enumerate(input_letters):
input_dict[letter] = input_numbers_list[index]
# Sort it by converting it into a list and riconverting to dict
sorted_dict = {k: v for k, v in sorted(list(input_dict.items()))}
# Print the result
output = ''
for value in sorted_dict.values():
output += value + ' '
print(output)
Using zip function helps
num_arr = list(map(int,input().split(' ')))
word = input()
num_arr.sort()
word = sorted(word)
mapper = dict(zip(word,num_arr))
result = ' '.join(map(str,[mapper[i] for i in word]))
print(result)
I make a bunch of matrices that I want to store in python dictionaries and I always find myself typing the same thing for every state that I want to build, i.e.
Ne21_1st_state = {}
Ne21_2nd_state = {}
Ne21_3rd_state = {}
Ne21_4th_state = {}
Ne21_5th_state = {}
Ne21_6th_state = {}
...
Ne21_29th_state = {}
Ne21_30th_state = {}
Can somebody help me automate this using python for loops?
Thanks in advance!
I want something like this:
for i in range(3, 11):
states = f'Ar36_{i}th_state'
print(states)
where the output would be:
Ar36_3th_state
Ar36_4th_state
Ar36_5th_state
Ar36_6th_state
Ar36_7th_state
Ar36_8th_state
Ar36_9th_state
Ar36_10th_state
but instead of printing it it would create individual dictionaries named Ar36_3th_state, Ar36_4th_state, Ar36_5th_state, ...
can't we make a List of dictionaries
List of 30 (or any N) elements where each element is a dictionary with key = "Ar36_{i}th_state" and value = {whatever value you want}
You can create "name" of pseudo variable and use it as key in dictionary like:
my_dic = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
my_empty_dic = {}
solution = {}
for i in range(1, 31):
name = 'Ne21_'+str(i)+'st_state'
#solution[name] = my_dic
solution[name] = my_empty_dic
for pseudo_variable in solution:
print(pseudo_variable, solution[pseudo_variable])
print(solution['Ne21_16st_state'])
for pseudo_variable in solution:
if '_16st' in pseudo_variable:
print(pseudo_variable, solution[pseudo_variable])
One way I've done this is using list comprehension.
key = list(
str(input(f"Please enter a Key for value {x + 1}: "))
if x == 0
else str(input(f"\nPlease enter a Key for value {x + 1}: "))
for x in range(3))
value = list(str(input(f"\nPlease enter a Bool for value {x + 1}: "))
for x in range(3))
BoolValues = dict(zip(key, value))
I first create a list of keys followed by a list of the values to be stored in the keys. Then I just zip them together into a dictionary. The conditional statements in the first list are only for a slightly better user-experience with \n being added if it's passed the first input.
Actually now that I look back on the question it may be slightly different to what I was thinking, are you trying to create new dictionaries for every matrix? If that is the case, is it something similar to this?: How do you create different variable names while in a loop?
This question already has answers here:
How to declare many variables?
(5 answers)
Closed 3 years ago.
I would like to do something like this:
for i in range(0, 3):
if i == 0:
name_i = "A"
elif i == 1:
name_i = "B"
else:
name_i = "C"
to have name_o = "A", name_1 = "B", name_i = "C".
I know I cannot do it like that method but is there some trick I can use to achieve that?
Dict example:
names = ['A', 'B', 'C']
my_dict = {}
for n, i in enumerate(names):
name = 'name_{}'.format(n)
my_dict[name] = i
Output:
{'name_0': 'A', 'name_1': 'B', 'name_2': 'C'}
Depending on where you get your A, B, C from, you can simply take them out of a list.
# or wherever your letters / whatever come from
import string
abc = string.ascii_uppercase
name0, name1, name2 = abc[0: 3]
print(name0)
print(name1)
print(name2)
I created 5 rooms with same Game id and print result (list if Rooms' id). i get Game with Id and print result (list of Rooms' id. I need to check if this two outputs (rooms id are matches).
for i in range(5):
post_req = requests.post(custom_url) # create 5 custom rooms with same Game id
json_data = post_req.text
python_data = json.loads(json_data)
for i in range(len(python_data["data"])):
first_list = python_data["data"][i]["id"]
print (first_list)
# Get Rooms with Game id. It should give a list of all rooms id created with same game id
custom_get_objects = requests.get(custom_url)
json_data = custom_get_objects.text
python_get_data = json.loads(json_data)
for i in range(len(python_get_data["data"])):
second_list = python_get_data["data"][i]["id"]
print (second_list)
How to program next following logic?
if first_list.data == second_list.data:
return True
my list.data output:
2b88a706-0ae0-4cac-84b3-8f69657ac8cd
402210ca-8397-4329-9c96-770f1d93ab43
78c9faae-74ad-44f8-9bab-b54bb8815afb
9a374566-d992-40a8-9e23-9cfe83ced532
f39794ed-d2f1-4443-a3f3-ef12534387d6
i tried to sort and iterated one list in another, but output is not what i expected. If you know or have any idea, please let me know.
If the order in your lists does not matter you can use sorted(listA) == sorted(listB) to compare them. If the order matters then simply use listA == listB.
Example:
aList = [2, 4, 5]
bList = [2, 5, 4]
print(aList == bList)
print(sorted(aList) == sorted(bList))
Output:
False
True
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I'm new to python, so I don't know if this is possible. I'm trying to create a list of variable names from a list of strings so I can then assign values to the newly created variables.
I saw another similar question, but there was already a dict pays of keys and values.
Here's my code:
def handy(self):
a = raw_input('How many hands? ')
for i in range(int(a)):
h = "hand" + str(i+ 1)
self.list_of_hands.append(h)
# would like to create variable names from self.list_of_hands
# something like "hand1 = self.do_something(i)"
print h
print self.list_of_hands
Given some of the answers, i'm adding the following comment:
I'm going to then assign dicts to each variable. So, can I create a dictionary of dictionaries?
Why don't you just construct a dictionary using the strings as keys?
>>> class test():
def handy(self):
a = raw_input('How many hands? ')
d = { "hand" + str(i + 1) : self.do_something(i) for i in range(int(a)) }
keys = d.keys()
keys.sort()
for x in keys:
print x, '=', d[x]
def do_something(self, i):
return "something " + str(i)
>>> test().handy()
How many hands? 4
hand1 = something 0
hand2 = something 1
hand3 = something 2
hand4 = something 3
Edit: You updated the question to ask if you can store a dictionary as a value in a dictionary. Yes, you can:
>>> d = { i : { j : str(i) + str(j) for j in range(5) } for i in range(5) }
>>> d[1][2]
'12'
>>> d[4][1]
'41'
>>> d[2]
{0: '20', 1: '21', 2: '22', 3: '23', 4: '24'}
>> d[5] = { 1 : '51' }
>> d[5][1]
'51'
If you ever have multiple variables that only differ by a number at the end (hand1, hand2, etc.), you need a container.
I think a dictionary would work best:
self.hands = {}
self.hands[h] = self.do_something(i)
You can access the individual keys in the dictionary easily:
self.hands['hand1']
h = "hand" + str(i+ 1)
vars()[h] = do_something(i)
Now you can call hand1 to call do_something()