Usage of a random function and lists - python

Here is my code
N=str(input("Enter the catagory: "))
Countries=["canada","albania","cuba"]
if N=="Countries":
y=random.choice(Countries)
if I do something like this the code takes the elements in the countries but when I try to create a function by using it I fail. For example I have many catogories so I dont want to write if function like 10 times for every catagory.Hence I tried to write it like this
N=str(input("Enter the catagory: "))
Countries=["canada","albania","cuba"]
def cata(N):
y=random.choice(N)
z=len(str(y))
return (z,y)
but at this time when I type countries I only get the letters of the countries so the code refers to the word "countries" but the list name.And I need the elements of the countries list. I am not sure how to fix it
thanks.
Well after the function ends I need both y and z values.

If you have a number of categories, and you need a single function to return a random value from one of those list, depending on the name of the list that you send, I think your best way of doing this is through a dictionary with lists as value. Something like
dic = {
'countries' : ["A","B","C"]
'cities' : ["X","Y","Z"]
}
Now your function can take the name of the list as a parameter, and use it to look up in the dictionary to get the appropriate list, and return a random value from that
N = str(input("Enter the catagory: "))
def cata(n):
y = random.choice(dic[n])
cata(N)

You are confusing a str (a piece of data) with variables and a piece of program code.
If user enters 'Countries' to the input, the string N gets turned into a list ['C', 'o', 'u', ...] inside random.choice(N).
To "fix" your program, you can do it this way:
Countries = ["canada","albania","cuba"]
N = str(input("Enter the catagory: "))
y = random.choice(eval(N))
...
HOWEVER, it is strongly discouraged to apply eval() to a string that user input. Most users can be expected to make mistakes at least some of the time, and a malicious user can abuse it to break your program or even your system.

Related

Calling methods and iterating over list

I'm trying to ask for ingredients in a recipe via the input function. I want to store that ingredient in a dictionary, separated by quantity and ingredient. For example, an input of '3 eggs', should yield {'3': 'eggs'}.
The way i do this is with the separate() and convert_to_dict() methods.
I want to ask continuously for the ingredients by means of the input, hence the while True loop.
Basically, i do this via the following code:
ingredients_list = []
def separate(list):
for i in list:
return re.findall(r'[A-Za-z]+|\d+', i)
def convert_to_dict(list):
i = iter(list)
dct = dict(zip(i, i))
return dct
while True:
ingredient = input("Please input your ingredient: ")
ingredients_list.append(ingredient)
print(convert_to_dict(separate(ingredients_list)))
This works fine, but the only problem with it is that when i input another ingredient, the separate() and convert_to_dict() methods only seem to work for the first ingredient in the ingredient list. For example, i firstly input '3 eggs', and then '100 gr of flour', yet it only returns {'3': 'eggs'}. I'm sure there is something i'm missing, but can't figure out where it goes wrong.
I think you've got the idea of your key-value pairs the wrong way around!
Keys are unique. Updating a dictionary with an existing key will just override your value. So if you have 3 eggs, and 3 cups of sugar, how do you envision your data structure capturing this information?
Rather try doing -
{'eggs': 3} # etc.
That should sort out a lot of problems...
But that's all besides the point of your actual bug. You've got a return in your for-loop in the separate function...This causes the function to return the first value encountered in the loop, and that's it. Once a function's reached a return in exist the function and returns to the outer scope.

How can I add two or more elements to a list from a single input in Python?

What my script is doing now is adding elements to a list. For example, if the user types "JO", I will add "John" to the list. What I want to do now is that, if the user types "2 JO", I add two elements to the list: "John" and "John".
This is how the database looks like now:
Sample database copy.png
This is the code now:
import pandas
data = pandas.read_excel("Sample database copy.xlsx")
name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input(Please type what you want to add: )
list1.append(name[incoming_msg])
I need to do it all from the same input, I cannot ask separately for quantity and abbreviation. I wanted to know if there is any library that can do this somehow easily because I am a beginner coder. If there is no library but you have any idea how I could solve it, it would be awesome as well.
Thank you so much in advance!
you can use string.split() to split the string by space into a list then use the first element to multiply a list that contains the value from the dictionary and increment it to the result list. see the code
name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input('Please type what you want to add: ')
incoming_msg = incoming_msg.split() # split the string by space
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
list1 += [name[incoming_msg[1]]] * int(incoming_msg[0])
else:
list1.append(name[incoming_msg[0]])

Python Dictionaries with lists from user input how to solve this?

Write a program that ask the user to enter an integer representing the number of items to be added to the stock. For these items, the program should then ask for the item barcode number and name, add them to a dictionary and print them.
Why is my code not working as expected?
size=input("Enter size of list")
names=[input()]
code=[int(input())]
for i in size:
print("Enter name and code")
names.append(input())
code.append(int(input()))
dict={names[i]:code[i]}
print(dict)
This a functioning version of your code:
size = input("Enter size of list")
names = []
code = []
for i in range(int(size)):
print("Enter name and code")
names.append(input())
code.append(int(input()))
d = dict(zip(names, code))
print(d)
Among the errors that needed fixing:
Only use input() in your for loop when you need the data.
i needs to cycle through range(int(size)) rather than a string input.
Create the dictionary from your lists at the end via zip.
Do not name variables after classes, e.g. use d instead of dict.

How to flip list to dictionary python

can you help me to flip list to dictionary
shopping_list = raw_input("Enter you Shopping List: ").title().split(',')
i need to flip this list to dictionary
and i dont know how much product the user want to input
This question is a bit ambiguous as you did not provide example input or output. I will assume that you are going to ask the user multiple times to enter in an item and how many they need separated by a comma. If the input changes, then I will edit my answer.
dictionary = {}
item, numberOfItems = raw_input("Enter your Shopping List: ").title().split(',')
dictionary[item] = numberOfItems
This is assuming that no matter what, your input comes in the form of:
banana,3
carrot,7
pack of gum,9
Edit
Since I see what the input is, I can answer this better.
The input string someone will input follows this pattern:
item1,3,item2,7,item3,20,item4,5
So we need to split the input every 2 items.
my_list = raw_input("Enter your Shopping List: ").title().split(',')
composite_list = [my_list[x:x+2] for x in range(0, len(my_list),2)]
This should set composite_list as such.
[[item1,3], [item2,7], [item3,20], [item4,5]]
Now all we need to do is loop through composite_list
for pair in composite_list:
print('({}:{})'.format(pair[0], pair[1]))
The output will now look like:
(item1:3)

ArcMap Field Calculator Program to create Unique ID's

I'm using the Field Calculator in ArcMap and
I need to create a unique ID for every storm drain in my county.
An ID Should look something like this: 16-I-003
The first number is the municipal number which is in the column/field titled "Munic"
The letter is using the letter in the column/field titled "Point"
The last number is simply just 1 to however many drains there are in a municipality.
So far I have:
rec=0
def autoIncrement()
pStart=1
pInterval=1
if(rec==0):
rec=pStart
else:
rec=rec+pInterval
return "16-I-" '{0:03}'.format(rec)
So you can see that I have manually been typing in the municipal number, the letter, and the hyphens. But I would like to use the fields: Munic and Point so I don't have to manually type them in each time it changes.
I'm a beginner when it comes to python and ArcMap, so please dumb things down a little.
I'm not familiar with the ArcMap, so can't directly help you, but you might just change your function to a generator as such:
def StormDrainIDGenerator():
rec = 0
while (rec < 99):
rec += 1
yield "16-I-" '{0:03}'.format(rec)
If you are ok with that, then parameterize the generator to accept the Munic and Point values and use them in your formatting string. You probably should also parameterize the ending value as well.
Use of a generator will allow you to drop it into any later expression that accepts an iterable, so you could create a list of such simply by saying list(StormDrainIDGenerator()).
Is your question on how to get Munic and Point values into the string ID? using .format()?
I think you can use following code to do that.
def autoIncrement(a,b):
global rec
pStart=1
pInterval=1
if(rec==0):
rec=pStart
else:
rec=rec+pInterval
r = "{1}-{2}-{0:03}".format(a,b,rec)
return r
and call
autoIncrement( !Munic! , !Point! )
The r = "{1}-{2}-{0:03}".format(a,b,rec) just replaces the {}s with values of variables a,b which are actually the values of Munic and Point passed to the function.

Categories

Resources