Multiple inputs to produce wanted output - list

I am trying to create a code that takes the user input, compares it to a list of tuples (shares.py) and then prints the values in a the list. for example if user input was aia, this code would return:
Please list portfolio: aia
Code Name Price
AIA Auckair 1.50
this works fine for one input, but what I want to do is make it work for multiple inputs.
For example if user input was aia, air, amp - this input would return:
Please list portfolio: aia, air, amp
Code Name Price
AIA Auckair 1.50
AIR AirNZ 5.60
AMP Amp 3.22
This is what I have so far. Any help would be appreciated!
import shares
a=input("Please input")
s1 = a.replace(' ' , "")
print ('Please list portfolio: ' + a)
print (" ")
n=["Code", "Name", "Price"]
print ('{0: <6}'.format(n[0]) + '{0:<20}'.format(n[1]) + '{0:>8}'.format(n[2]))
z = shares.EXCHANGE_DATA[0:][0]
b=s1.upper()
c=b.split()
f=shares.EXCHANGE_DATA
def find(f, a):
return [s for s in f if a.upper() in s]
x= (find(f, str(a)))
print ('{0: <6}'.format(x[0][0]) + '{0:<20}'.format(x[0][1]) + ("{0:>8.2f}".format(x[0][2])))
shares.py contains this
EXCHANGE_DATA = [('AIA', 'Auckair', 1.5),
('AIR', 'Airnz', 5.60),
('AMP', 'Amp',3.22),
('ANZ', 'Anzbankgrp', 26.25),
('ARG', 'Argosy', 12.22),
('CEN', 'Contact', 11.22)]

I am assuming a to contain values in the following format 'aia air amp'
raw = a # just in case you want the original string at a later point
toDisplay = []
a = a.split() # a now looks like ['aia','air','amp']
for i in a:
temp = find(f, i)
if(temp):
toDisplay.append(temp)
for i in toDisplay:
print ('{0: <6}'.format(i[0][0]) + '{0:<20}'.format(i[0][1]) + ("{0:>8.2f}".format(i[0][2])))
Essentially what I'm trying to do is
Split the input into a list
Do exactly what you were doing for a single input for each item in that list
Hope this helps!

Related

Questions about Tuples

So I was able to run part of a program doing below (using tuples)
def reverse_string():
string_in = str(input("Enter a string:"))
length = -int(len(string_in))
y = 0
print("The reverse of your string is:")
while y != length:
print(string_in[y-1], end="")
y = y - 1
reverse_string()
The output is:
Enter a string:I Love Python
The reverse of your string is:
nohtyP evoL I
I am still thinking how for the program to reverse the position of the words instead of per letter.
The desired output will be "Phython Love I"
Is there anyway that I will input a string and then convert it to a tuple similar below:
So If I enter I love Phyton, a certain code will do as variable = ("I" ,"Love", "Python") and put additional codes from there...
Newbie Programmer,
Mac

how to get the series out of a data frame?

fake = {'EmployeeID' : [0,1,2,3,4,5,6,7,8,9],
'State' : ['a','b','c','d','e','f','g','h','i','j'],
'Email' : ['a','b','c','d','e','f','g','h','i','j']
}
fake_df = pd.DataFrame(fake)
I am trying to define a function that returns a Series of strings of all email addresses of employees in states. The email addresses should be separated by a given delimiter. I think I will use ";".
Arguments:
- DataFrame
- delimiter (;)
Do I have to use for loop?? to be honest, I don't even know how to start on this..
====EDITION
After done with coding, I should run
emails = getEmailListByState(fake_df, ", ")
for state in sorted(emails.index):
print "%15s: %s" % (state, emails[state])
and should get something like
a: a
b: b
c: c,d
d: e
e: f,g
as my output
If I understand the problem properly you are looking for groupby state,get the emails and apply join i.e joining the emails based on the state i.e
fake = {'EmployeeID' : [0,1,2,3,4,5,6,7,8,9],
'State' : ['NZ','NZ','NY','NY','ST','ST','YK','YK','YK','YK'],
'Email' : ['ab#h.com','bab#h.com','cab#h.com','dab#h.com','eab#h.com','fab#h.com','gab#h.com','hab#h.com','iab#h.com','jab#h.com']
}
fake_df = pd.DataFrame(fake)
ndf = fake_df.groupby('State')['Email'].apply(', '.join)
Output:
State
NY cab#h.com, dab#h.com
NZ ab#h.com, bab#h.com
ST eab#h.com, fab#h.com
YK gab#h.com, hab#h.com, iab#h.com, jab#h.com
Name: Email, dtype: object
If you want that in a method then
def getEmailListByState(df,delim):
return df.groupby('State')['Email'].apply(delim.join)
emails = getEmailListByState(fake_df, ", ")
for state in sorted(emails.index):
print( "%15s: %s" % (state, emails[state])

Split Pandas Column by values that are in a list

I have three lists that look like this:
age = ['51+', '21-30', '41-50', '31-40', '<21']
cluster = ['notarget', 'cluster3', 'allclusters', 'cluster1', 'cluster2']
device = ['htc_one_2gb','iphone_6/6+_at&t','iphone_6/6+_vzn','iphone_6/6+_all_other_devices','htc_one_2gb_limited_time_offer','nokia_lumia_v3','iphone5s','htc_one_1gb','nokia_lumia_v3_more_everything']
I also have column in a df that looks like this:
campaign_name
0 notarget_<21_nokia_lumia_v3
1 htc_one_1gb_21-30_notarget
2 41-50_htc_one_2gb_cluster3
3 <21_htc_one_2gb_limited_time_offer_notarget
4 51+_cluster3_iphone_6/6+_all_other_devices
I want to split the column into three separate columns based on the values in the above lists. Like so:
age cluster device
0 <21 notarget nokia_lumia_v3
1 21-30 notarget htc_one_1gb
2 41-50 cluster3 htc_one_2gb
3 <21 notarget htc_one_2gb_limited_time_offer
4 51+ cluster3 iphone_6/6+_all_other_devices
First thought was to do a simple test like this:
ages_list = []
for i in ages:
if i in df['campaign_name'][0]:
ages_list.append(i)
print ages_list
>>> ['<21']
I was then going to convert ages_list to a series and combine it with the remaining two to get the end result above but i assume there is a more pythonic way of doing it?
the idea behind this is that you'll create a regular expression based on the values you already have , for example if you want to build a regular expressions that capture any value from your age list you may do something like this '|'.join(age) and so on for all the values you already have cluster & device.
a special case for device list becuase it contains + sign that will conflict with the regex ( because + means one or more when it comes to regex ) so we can fix this issue by replacing any value of + with \+ , so this mean I want to capture literally +
df = pd.DataFrame({'campaign_name' : ['notarget_<21_nokia_lumia_v3' , 'htc_one_1gb_21-30_notarget' , '41-50_htc_one_2gb_cluster3' , '<21_htc_one_2gb_limited_time_offer_notarget' , '51+_cluster3_iphone_6/6+_all_other_devices'] })
def split_df(df):
campaign_name = df['campaign_name']
df['age'] = re.findall('|'.join(age) , campaign_name)[0]
df['cluster'] = re.findall('|'.join(cluster) , campaign_name)[0]
df['device'] = re.findall('|'.join([x.replace('+' , '\+') for x in device ]) , campaign_name)[0]
return df
df.apply(split_df, axis = 1 )
if you want to drop the original column you can do this
df.apply(split_df, axis = 1 ).drop( 'campaign_name', axis = 1)
Here I'm assuming that a value must be matched by regex but if this is not the case you can do your checks , you got the idea

Pig Latin involving digits

I'm new to computer programming and I'm trying to write a program that converts English into Pig Latin (For every word, move the first letter to the end of the word and add 'ay').
If the there is a number (in digits), multiply it by 2 and add 4.
ex. John has 4 cats --> ndaay ashay 12 atscay)
I got the first pig latin part down but can't seem to figure out the number part. My code accesses a text file but here is the program that would perform the string pig-latin. Where would I fit the number function?
def pig_english():
letterlist = [i + i[0] for i in read_script()]
ayList = [i + 'ay' for i in letterlist]
delaylist = [i[1:] for i in ayList]
print (delaylist)
You can test if i.isdigit() and then cast to an int but it will be easier doing it all in one comprehension:
def pig_english(words):
ayList = [str(int(i)*2+4) if i.isdigit() else i[1:]+i[0]+"ay" for i in words]
print (ayList)
If you split the operations across multiple comprehensions then you will need to guard against ints:
def pig_english(words):
numberlist = [int(i)*2+4 if i.isdigit() else i for i in words]
letterlist = [i if isinstance(i, int) else i + i[0] for i in numberlist]
ayList = [i if isinstance(i, int) else i + 'ay' for i in letterlist]
delaylist = [str(i) if isinstance(i, int) else i[1:] for i in ayList]
print (delaylist)
>>> pig_english("John has 4 cats".split())
['ohnJay', 'ashay', '12', 'atscay']

Python remove odd numbers and print only even

user = int(raw_input("Type 5 numbers"))
even = []
def purify(odd):
for n in odd:
even.append(n)
if n % 2 > 0:
print n
print purify(user)
Hello I am a beginner and I would like to understand what is wrong with this code.
The User chose 5 numers and I want to print the even numbers only.
Thanks for helping
There are a few problems:
You can't apply int to an overall string, just to one integer at a time.
So if your numbers are space-separated, then you should split them into a list of strings. You can either convert them immediately after input, or wait and do it within your purify function.
Also, your purify function appends every value to the list even without testing it first.
Also, your test is backwards -- you are printing only odd numbers, not even.
Finally, you should return the value of even if you want to print it outside the function, instead of printing them as you loop.
I think this edited version should work.
user_raw = raw_input("Type some space-separated numbers")
user = user_raw.split() # defaults to white space
def purify(odd):
even = []
for n in odd:
if int(n) % 2 == 0:
even.append(n)
return even
print purify(user)
raw_input returns a string and this cannot be converted to type int.
You can use this:
user = raw_input("Input 5 numbers separated by commas: ").split(",")
user = [int(i) for i in user]
def purify(x):
new_lst = []
for i in x:
if i % 2 == 0:
new_lst.append(i)
return new_lst
for search even
filter would be the simplest way to "filter" even numbers:
output = filter(lambda x:~x&1, input)
def purify(list_number):
s=[]
for number in list_number:
if number%2==0:
s+=[number]
return s