How do I add a "noHigherStocks" function when there are no higher stocks in a list? - python-3.x

I am attempting to create a program that has 4 functions, getStocks, searchStocks, printStocks, and then the main function that uses the other three.
My issue is that I want to make it so that if the stock you searched for is the highest stock, I want the message "There are no higher stocks" to appear as the output instead of empty space, but I am unsure what and where I would need to add to do that. I have the "noHigherStocks" variable as the message I want displayed, but where am I to implement it? I feel as though I should use an else statement in the main function, but I can't think of where it would make sense to put it. Thanks for reading! any help or tips would be greatly appreciated :-)
def getStocks():
stockNames = []
stockPrices = []
name = str(input("What is the name of the stock?"))
price = int(input("what is the price of that stock?"))
while name != 'done':
stockNames.append(name)
stockPrices.append(price)
name = str(input("What is the name of the stock?"))
if name != 'done':
price = int(input("what is the price of that stock?"))
return (stockNames, stockPrices)
# returns a single value pertaining to the found price
def searchStocks(stockNames, stockPrices, s):
for i in range (len(stockNames)):
if stockNames[i] == s:
return stockPrices[i]
return -1
# print the names of stocks whose price is higher than p.
def printStock(stockNames, stockPrices, p):
i = 0
while i <len(stockPrices):
if p < stockPrices[i]:
print(stockNames[i])
i = i + 1
return
def main():
n,p = getStocks()
stock = str(input("what stock are you searching for?"))
price = searchStocks(n,p,stock)
printStock(n,p,price)
noStocksHigher = str('There are no stocks higher than',stock)
main()

This might be solved using the max() builtin. Since you already know the price of the stock for which you searched, you could just compare that price against the highest price in p, and if equal, print your message, otherwise search the list.
Starting where you call searchStocks:
price = searchStocks(n,p,stock)
if max(p) == price:
print('There are no stocks higher than',stock)
else:
printStock(n,p,price)
This should do the trick.

Related

You have to build a dictionary (Or any other container of your choice) . Using python

You have to build a dictionary (Or any other container of your choice) which contains multiple True/false type quiz questions.
Every participant/user will attempt 5 rounds and in each round random quiz questions will be displayed to the user/participant.
If the participant answers the quiz question correct, then congratulate him and add the scores.
At the end display the details and score of the participant.
I have tried but I am not getting expected output.
I hope it can be useful for you. There are many other ways to do it but i think in this way you can understand easier what the script is doing.
import requests
import random
import numbers
def get_quiz_questions():
response = requests.get('https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json')
if response.status_code != 200:
return [
["The Mars Rover \"Spirit\" is powered by six small motors the size of \"C\" batteries. It has a top speed of 0.1 mph.", True],
["Burt Reynolds was originally cast to be Han Solo in the first Star Wars film. He dropped out before filming.", True]
]
return response.json()
# Get questions
quiz_questions = get_quiz_questions()
# Get numeric value, retry if it's not valid.
def get_numeric_value(message):
print(message)
value = input()
if not(value and value.isnumeric()):
print('Entered value is not valid\n')
# using recursion to prompt again for a valid value
return get_numeric_value(message)
return int(value)
def request_boolean_answer():
print('Enter answer: [ 0: false | 1: true]')
answer = input()
# Check if the value entered is numeric and if it's not 1 or 0
if answer.isnumeric() and ( 0 != int(answer) != 1):
print('Entered answer is not valid\n')
# using recursion
return request_boolean_answer()
return bool(answer)
# Start Game
num_players = get_numeric_value('\nEnter number of players: ')
num_questions = get_numeric_value('\nEnter number of questions: ')
score = {}
for player in range(num_players):
print("\nPlayer #:", player )
# initialize score for current user
score[f'player_{player}'] = 0
for question in range(num_questions):
question, answer = random.choice(quiz_questions)
print(question)
user_answer = request_boolean_answer()
print(f'Your answer: {user_answer}, correct answer: {answer}\n')
# Add a point if the answer is correct
if answer == user_answer:
score[f'player_{player}']+=1
print(f'\nScore: {score}')

Python function to perform calculation among each group of data frame

I need to have a function which performs below mentioned action ;
The dataset is :
and output expected is value in 'Difference' column , where remaining are input column.
Please note that within each group we first need to identify the maximum 'Closing_time' and the corrosponding amount will be the maximum value for that period , and then each row value will be subtracted from maximum detected value of previous period and result would be difference for that cell.
Also in case if the record do not have previous period then max value will be NA and difference caculation would be NA for all record for that period,
Adding points - within in each group (Cost_centre, Account, Year, Month) - Closing_time values are like ( D-0 00 CST is min and D-0 18 CST is maximim , similary within D-0,D+1, D+3 etc - D+3 will be maximum)
I tried to find first if previous value exist for each of the group or not and then find maximum time within each period and then crrosponding amount value to it.
Further using the maximum value , tried to subtract record Amount from Maximum value ,
but not getting how to implement , kindly help.
post sharing the above question i came up for this solution.
I splitted this in 3 part -
a) First find previous year and month for each of cost_center and account
b) Find maximum Closing_time within each group of cost_cente,account, year and month. Then pick corrosponding Amount value as amount .
c) using amount coming from b , subtract current amount with b to get diffrence.
def prevPeriod(df):
period =[]
for i in range(df.shape[0]):
if df['Month'][i]==1:
val_year = df['Year'][i]-1
val_month = 12
new_val =(val_year,val_month)
period.append(new_val)
else:
val_year = df['Year'][i]
val_month = df['Month'][i]-1
new_val =(val_year,val_month)
period.append(new_val)
print(period)
df['Previous_period'] = period
return df
def max_closing_time(group_list):
group_list = [item.replace('CST','') for item in group_list]
group_list = [item.replace('D','') for item in group_list]
group_list = [item.split()[:len(item)] for item in group_list]
l3 =[]
l4 =[]
for item in group_list:
l3.append(item[0])
l4.append(item[1])
l3 =[int(item) for item in l3]
l4 = [int(item) for item in l4]
max_datevalue = max(l3)
max_datevalue_index = l3.index(max(l3))
max_time_value = max(l4[max_datevalue_index:])
maximum_period = 'D+'+str(max_datevalue)+' '+str(max_time_value)+' '+'CST'
return maximum_period
def calculate_difference(df):
diff =[]
for i in range(df.shape[0]):
prev_year =df['Previous_period'][i][0]
print('prev_year is',prev_year)
prev_month = df['Previous_period'][i][1]
print('prev_month is', prev_month)
max_closing_time = df[(df['Year']==prev_year)& (df['Month']==prev_month)]['Max_Closing_time']
print('max_closing_time is', max_closing_time)
#max_amount_consider = df[(df['Year']==prev_year)& (df['Month']==prev_month) &(df['Max_Closing_time']==max_closing_time)]['Amount']
if bool(max_closing_time.empty):
found_diff = np.nan
diff.append(found_diff)
else:
max_closing_time_value = list(df[(df['Year']==prev_year)& (df['Month']==prev_month)]['Max_Closing_time'])[0]
max_amount_consider = df[(df['Cost_centre']==df['Cost_centre'][i])&(df['Account']==df['Account'][i])&(df['Year']==prev_year) & (df['Month']==prev_month) &(df['Closing_time']==str(max_closing_time_value))]['Amount']
print('max_amount_consider is',max_amount_consider)
found_diff = int(max_amount_consider) - df['Amount'][i]
diff.append(found_diff)
df['Variance'] = diff
return df
def calculate_variance(df):
'''
Input data frame is coming as query used above to fetch data
'''
try:
df = prevPeriod(df)
except:
print('Error occured in prevPeriod function')
# prerequisite for max_time_period
df2 = pd.DataFrame(df.groupby(['Cost_centre','Account','Year','Month'])['Closing_time'].apply(max_closing_time).reset_index())
df = pd.merge(df,df2, on =['Cost_centre','Account','Year','Month'])
# final calculation
try:
final_result = calculate_difference(df)
except:
print('Error in calculate_difference')
return final_result

How to return 2 output from a list

Probably a very stupid Q! Too much office has damaged my brain today.
I am stuck at solving a basic problem from a site.
I have a function that has 3 values in tuple (name, age, gender). I have worked on getting just age & gender in a list & then iterating there to get average if the gender matches M or F and No match if anything apart from it.
Now I am stuck in the problem in BOLD in the code where I am unable to return either one of the output i.e. if gender = "m' or 'f' it works properly, but if it uses avergae_age(members,Z), it doesnt return ' No matches found' instead error, which is obvious.
How do I make this code better?
b) How do I just get the output if anything apart form M/F is input without changing my existing code pls ?
Thanks in advance
def average_age(members,gender):
lst=[]
for x in zip(members):
lst.append(x[0][1])
lst.append(x[0][2])
lst_tuple = [x for x in zip(*[iter(lst)]*2)]
#return lst_tuple
**lst1=[]
for z in lst_tuple:
if z[1]!=gender:
lst1=[]
return ("No matches found.")
for z in lst_tuple:
if z[1]==gender:
lst1.append(z[0])
return (sum(lst1)/len(lst1))**
For input data:
members = [("Maria", 20, "F"), ("Dan", 21, "M"), ("Ana", 30, "F"), ("Max", 40, "M")]
You can compute average age like this:
def average_age(members: list, gender: str):
# Collect ages for the given gender
ages = [member[1] for member in members if member[2] == gender]
try:
return sum(ages) / len(ages)
except ZeroDivisionError:
print("Unable to compute average age")

Duplicate entries in the list

Having to enter 8 unique entries, logic should detect if any entry is duplicate otherwise continue until all 8 entries are entered.
I've played around with the For loop but it seems to not give me desired output, i want to go back to last entry if duplicate entry is scanned instead it will give a message "Duplicate SCAN, please rescan" but also the counter moves on.
sorry, i'm new to this i thought i've included code. Hoping it goes through this time.
x=1
mac_list = []
while (x <=8):
MAC1 = input("SCAN MAC"+str(x)+":")
for place in mac_list:
print (mac_list)
if place==MAC1:
print ("place"+place)
print ("Duplicate SCAN, please rescan")
else:
mac_list.append(MAC1)
x+=1
Python's in comparison should do what you need:
values = []
while True:
value = input('Input value: ')
if value in values:
print('Duplicate, please try again')
else:
values.append(value)
if len(values) > 7:
break
print(values)
Would something like this not work?
Sets can only hold unique elements and thus remove any duplicates by default - that should solve a lot of your worries. This should work better for larger datasets over elementwise comparison.
entries = set()
while len(entries)<8:
entries = entries ^ set([input("You do not have enough unique items yet, add another")])
To detect a change you can have an old list and a new one:
entries = set()
new=set()
while True:
latest = input("You do not have enough unique items yet, add another")
new = entries ^ set([latest])
if len(new) == len(entries):
print("you entered a duplicate:",latest, " Please rescan")
else:
entries = new
if len(entries) == 8 : break
Store the entries in a set, check if the set has fewer than 8 elements. If it does not, break the loop.
entries = set()
counter = 0
while len(entries) < 8:
counter += 1
entries.add(input("Enter an item: "))

List is not being appended right

I have this code block
purchase_amounts = []
item_price = ''
subtotal = 0
while item_price != 'done':
item_price = input('Enter the amount to add to the list!')
purchase_amounts.append(item_price)
while purchase_amounts != [] and item_price != 'done':
pop_var = purchase_amounts.pop()
subtotal += int(pop_var)
print(purchase_amounts)
print(subtotal)
It runs as expected but for some reason the list purchase_amounts only shows done after it has been run. I would like to know how to fix this and why it is not working for me at the moment. The output I am getting is purchase_amounts = ['done'] and subtotal = 101 for 17, 17, 12, 55. The expected output for purchase_amounts should be ['17','17','12','55']
-Thanks
First, you're appending is working fine, however you've added done to the list before you print it, and you're popping elements off the list while you are getting input. Therefore, you won't see those appended items in the final output
It's not clear what the purpose of popping is, so you can sum up the numbers after the loop instead
purchase_amounts = []
item_price = None
while True:
item_price = input('Enter the amount to add to the list!')
if item_price == 'done':
break
purchase_amounts.append(float(item_price))
print(purchase_amounts)
print(sum(purchase_amounts))
.pop() will remove the item from the list. Try by getting the last item each time.
purchase_amounts[-1]
or even better add item_price to your list only when item_price is a number then use the function sum() to sum it.
purchase_amounts = []
item_price = ''
subtotal = 0
while item_price != 'done':
item_price = input('Enter the amount to add to the list!')
if item_price.isdigit():
purchase_amounts.append(int(item_price))
subtotal = sum(purchase_amounts)
print(purchase_amounts)
print(subtotal)

Resources