Im allowed to use Numpy for the task.
I need to show the total sales in a month with two lists: dates and sales.
My approach is to make a list of all sales during a month by stripping the month off the date, creating a 2D matrix and adding the values that check for each month.
import numpy as np
dates = ["02/01/19", "03/02/19"]
sales = ["10.50", "12.20"]
month = [x.strip("0").split("/")[0] for x in dates]
monthsales = np.vstack((month, sales)).astype(np.float)
def monthlysales():
jan = []
for i in monthsales[0, 0:]:
if i == 1:
jan.append()
s = input("Pick month: ")
if s == "1":
print("Sales total for Jan is:", np.sum(jan), "USD")
else:
print("Not a valid month")
return
print(monthsales)
print(monthlysales())
The problem is that I dont know what to append so that it takes the second row of my matrix, which would complete the code
A solution keeping your logic:
Here I loop over the months (as you did, but here using enumerate), and look for when the month is equal to 1. Using enumerate allows us to know the column number of when the month equals 1 (id). Then it's just a matter of appending the sales (row 1) at the month we're interested in (id)
import numpy as np
dates = ["02/01/19", "03/02/19"]
sales = ["10.50", "12.20"]
month = [x.strip("0").split("/")[0] for x in dates]
monthsales = np.vstack((month, sales)).astype(np.float)
def monthlysales():
jan = []
# Loop over months with enumerate
for id, month in enumerate(monthsales[0]):
if month == 1:
# Append sales (row 1) at column id
jan.append(monthsales[1, id])
s = input("Pick month: ")
if s == "1":
print("Sales total for Jan is:", np.sum(jan), "USD")
else:
print("Not a valid month")
print(monthsales)
print(monthlysales())
Of course, since you're allowed to use numpy you could have avoided any looping altogether. Consider the following line:
monthsales[1, monthsales[0] == 1].sum()
This sums up the sales for all the January months in one line. No loops. For any reasonable amount of data this will be considerably quicker than the solution with enumerate.
Looking more like your initial solution you could have had:
def monthlysales():
s = int(input("Pick month: "))
if s >= 1 and s <= 12:
monies = monthsales[1, monthsales[0] == s].sum()
print("Sales total for month {} is {} USD".format(s, monies))
else:
print("Not a valid month")
Related
def leap():
year = int(input("enter a number: "))
if year == range(300,2000):
print(year/400)
elif year == range(2001,2024):
print(year/4)
leap()
so I am trying to create a function that calculates if the year is a leap year, but it seems it does not want to show the answer of the leap year. there is no error message when I run the code,
also, I am doing this in visual studio code.
The object returned by range(300, 2000) has a type that is different than year, in your case an int. We can see this in the REPL:
>>> r = r(300, 2000)
>>> r
range(300, 2000)
>>> type(r)
<class 'range'>
Typically, comparing values of two types will not lead to equality. For this reason == is not what you're looking for.
Ranges are a builtin type in Python, which implements all the common sequence operators. This is why what you're looking for is:
if year in range(300, 2000):
...
This clause will operate as you expect. Note that it does not scan the list, and is in fact take O(1) time, not O(n).
However, it is probably easier to simply see if your values are within the expected parameters using a direct integer comparison:
if year >= 300 and <= 2000:
...
You can do it this way simply:
def leap():
year = int(input("enter a number: "))
if 300 <= year < 2000:
print(year/400)
elif 2001 <= year < 2024:
print(year/4)
leap()
Or use in instead of ==
i believe this will determine a leap year
def leap():
year = int(input("enter a number: "))
if year % 400 == 0:
print('leap year')
elif year % 4 ==0 and year % 100 != 0:
print('leap year')
else:
print('not a leap year')
leap()
leap()
I have to be able to calculate the revenu per month depending on the number of goats sold per month knowing that every month I sell 20% of the goats I had initially in January. When I try to calculate it through my price_list I can only get 400$ and not the 300$ for the corresponding months.
The variable d is there to know whether or not the month starts with a vowel. If it does d= "d'" and if not d="de".
I have been going at it for a week and can't seem to find a solution for neither of my two problems.
Help would be really appreciated !!!
goats=int(input("Enter the number of goats at the beginning of january :"))
year= ["january","february","march","april","may","june","july","august","september","october","november","december"]
vowels = "aeiouy"
price_list = [400,400,400,400,300,300,300,300,300,300,400,400]
d=""
if goats >0:
for month in range(len(year)):
goats_left = int(goats*0.8)
goats_sold = goats - goats_left
goats = goats_left
print("At the of the month of {0} {1} , we will have {2} goats left, monthly revenu: {3} $".format(d,year[month],goats,price_list[i]))
else:
print("The number entered is not valid {0}.format(goats))
goats=int(input("Enter the number of goats at the beginning of january :"))
print("\n")
print("ANNUAL REVENUE ........................................................ :".format())
print(goats_sold_list)
My first suggestion would be to use enumerate as a more pythonic way to iterate over your list and get it's index. I also don't understand your use of d anywhere so perhaps clarify how you intended it to be used.
Finally, l don't see i or goats_sold_list declared anywhere.
This should be a starting point for improvement:
goats = int(input("Enter the number of goats at the beginning of january :"))
year = ["january","february","march","april","may","june","july","august","september","october","november","december"]
vowels = "aeiou"
price_list = [400,400,400,400,300,300,300,300,300,300,400,400]
d=""
goats_sold_list = []
if goats >0:
for index, month in enumerate(year):
#int() always rounds down, i.e 0.8 goes to 0
goats_left = int(goats*0.8)
goats_sold = goats - goats_left
goats = goats_left
goats_sold_list.append(goats_sold)
print("At the of the month of {0} {1} , we will have {2} goats left, monthly revenu: {3} $".format(d,month,goats,price_list[index]))
else:
print("The number entered is not valid {0}.format(goats)")
goats=int(input("Enter the number of goats at the beginning of january :"))
print("\n")
print("ANNUAL REVENUE ........................................................ :".format())
print(goats_sold_list)
I don't see a definition for [i] in price_list[i], barring some outside definition, I think that should be price_list[month].
I don't see d being set at any point, you might need to have some line of code setting d to some value based on the first letter of the month.
I am trying to write a code that will accept any of the months of the year and output the month entered plus a list of the days in the month. But if February is entered it should ask for the birth year and check if that is a leap year and output February plus the days in February.
Where did I go wrong?
month = input("Enter any month of the year: ")
for n in month:
if (n == "January" or
n == "March" or
n == "April" or
n == "May" or
n == "June" or
n == "July" or
n == "August" or
n == "September" or
n == "October" or
n == "November" or
n == "December"):
print (n + range(1, 32))
elif n == "February" :
year = input("Enter a year")
for i in year:
if i % 4 == 0:
print (year + range(1,29))
I will advise you to simply use the built-in calendar module
# Program to display calendar of the given month and year
# importing calendar module
import calendar
yy = 2014 # year
mm = 11 # month
# To take month and year input from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy, mm))
# output
# November 2014
#Mo Tu We Th Fr Sa Su
# 1 2
# 3 4 5 6 7 8 9
#10 11 12 13 14 15 16
#17 18 19 20 21 22 23
#24 25 26 27 28 29 30
Assuming your intent is to learn how to program (such as for a educational assignment), the following should help. If it's just to do the job, you should probably use some of the built-in Python modules (like datetime or calendar) since they'll do a lot of the hard work for you.
First, input returns a string and, when you iterate over a string (for n in month), you'll get one character at a time. So iterating over "May" will give you "M", "a", and "y", none of which are equal to "May". Don't iterate, just compare the entire string:
if month == "January" ...
Second, not all those months have 31 days, you'll need to distinguish those that have 30:
if month == "February":
doFebStuff()
elif month in ['September', 'April', 'June', 'November']:
do30DayStuff()
else:
do31DayStuff()
Third, you can't concatenate a string and a range, you'll need to do something like:
print(month, end='')
for i in range(1, 32):
print(f" {i}", end='')
print()
Fourth, again for the year, input gives you a string and you don't want to iterate over it. You also want to make it an integer if you're going to do mathematical calculations on it, something like:
year = int(input("Enter a year: "))
Fifth, the rules for leap years are slightly more complex than every four years, specifically:
if it's a multiple of 400, it's a leap year; else
if it's a multiple of 100, it's not; else
if it's a multiple of 4, it is; else
it's not.
Taking all that into account, here's one way to do it, with added checks for validity (month name and year):
Days30 = ["September", "April", "June", "November"]
Days31 = ["January", "March", "May", "July", "August", "October", "December"]
lastDay = None
month = input("Enter any month of the year: ")
if month == "February":
lastDay = 28
year = -1
while year < 0:
try:
year = int(input("Enter the year: "))
except:
year = -1
if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0):
lastDay = 29
elif month in Days30:
lastDay = 30
elif month in Days31:
lastDay = 31
if lastDay is None:
print(f"I don't know the month {month}")
else:
print(f"{month}:", end="")
for day in range(1, lastDay + 1):
print(f" {day}", end="")
print()
I wouldn't try to pass that off as your own work (you'll almost certainly be pinged for plagiarism) but it's a good bit of code for getting some ideas.
If you are asking where did you go wrong, there are some places:
Your if and elif are not indented properly, they do not align.
When you write for n in month:, n takes value of every letter in the month inputed. e.g. if you entered "July", n would be iterating as "J", "u", "l", and "y". So comparing n to full names of months will always evaluate to False. Just compare the month instead of iterating over it.
When taking input, python stores the value entered by user as string (year = input("Enter a year")). So when you are iterating over the variable year (for i in year) you are iterating over a string of numbers and not the number. Furthermore, modulus operator won't work for strings (i % 4) as i in this case is a string. Just do year = int(input("Enter a year")) to convert year to ineger and do not iterate over it, check for remainder with 4 directly.
You can refer to the code by paxdiablo to get a working code.
I am doing a past paper for exam revision and stuck on this question:
Write a python script to accept from the user the day of the week on which January 1st falls in a particular year, and then to print the day of the week for any other month and day of the month specified by the user. You may assume that year is not a leap year, that the user types the inputs as the first three letters of any word, and that the following code has previously been defined:
import numpy as np
months = np.array(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])
ndays = np.array([31,28,31,30,31,30,31,31,30,31,30,31])
days=np.array(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'])
So I know how to take the input off the user by using the input command so I can create 3 variables:
user_Jan_1_day = input('Input the day of the week for Jan 1st: ')
user_month = input('Input the month: ')
user_day = input('Input the day of the month required: ')
So say the user said that Jan 1st was 'Sat', and they want the day of the week for 'Mar', '1' i.e. March 1st.
I know that I need to take 31 + 28 + 1. Find the sum = 60.
Take the modulus: 60%7 = 4, and then add four week days to 'Sat' to get 'Wed' as my answer, but how do I do it in Python?
I thought I could do this by using the index of the array so I used
a=np.where(months==user_month)
no_of_days = 0
for i in range (a):
no_of_days =+ ndays[i]
but I get an error: "'tuple' object cannot be interpreted as an integer"
Could someone show me how to do this?
Thank you!
Following pretty much your exact logic, you can do it like this, with no need to iterate (making sure to get int(input(...)) for user_day rather than the default string input):
user_Jan_1_day = input('Input the day of the week for Jan 1st: ')
user_month = input('Input the month: ')
user_day = int(input('Input the day of the month required: '))
m = np.where(months == user_month)[0][0]
d = np.where(days == user_Jan_1_day)[0][0]
# or, maybe more straightforward, since there is only one correct value:
# m = list(months).index(user_month)
# d = list(days).index(user_Jan_1_day)
result = days[(np.sum(ndays[:m]) + user_day + d) % 7]
For example:
>>> user_Jan_1_day = input('Input the day of the week for Jan 1st: ')
Input the day of the week for Jan 1st: Sat
>>> user_month = input('Input the month: ')
Input the month: Mar
>>> user_day = int(input('Input the day of the month required: '))
Input the day of the month required: 1
>>> m = np.where(months == user_month)[0][0]
>>> d = np.where(days == user_Jan_1_day)[0][0]
>>> result = days[(np.sum(ndays[:m]) + user_day + d) % 7]
>>> result
'Wed'
The range() function takes an integer. But a itself is not an integer. So try using range(a[0][0]):
for i in range(range(a[0][0])):
no_of_days += ndays[i]
no_of_days += int(user_day)
Also, your "=+" should be "+=" as shown here.
This gives you the desired date as the number of days into the calendar year. From there, you can use some modular arithmetic ("%") of that with the day for Jan 1st against your days array.
I'm trying to solve a problem but I've been working on it for so long and have tried so many things but I'm really new to python and don't know how to get the input I'm after.
The calculator needs to be in a format of a nested loop. First it should ask for the number of weeks for which rainfall should be calculated. The outer loop will iterate once for each week. The inner loop will iterate seven times, once for each day of the week. Each itteration of the inner loop should ask the user to enter number of mm of rain for that day. Followed by calculations for total rainfall, average for each week and average per day.
The main trouble I'm having is getting the input of how many weeks there are and the days of the week to iterate in the program eg:
Enter the amount of rain (in mm) for Friday of week 1: 5
Enter the amount of rain (in mm) for Saturday of week 1: 6
Enter the amount of rain (in mm) for Sunday of week 1: 7
Enter the amount of rain (in mm) for Monday of week 2: 7
Enter the amount of rain (in mm) for Tuesday of week 2: 6
This is the type out output I want but so far I have no idea how to get it to do what I want. I think I need to use a dictionary but I'm not sure how to do that. This is my code thus far:
ALL_DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
total_rainfall = 0
total_weeks = 0
rainfall = {}
# Get the number of weeks.
while True:
try:
total_weeks = int(input("Enter the number of weeks for which rainfall should be calculated: "))
except ValueError:
print("Number of weeks must be an integer.")
continue
if total_weeks < 1:
print("Number of weeks must be at least 1")
continue
else:
# age was successfully parsed and we're happy with its value.
# we're ready to exit the loop!
break
for total_rainfall in range(total_weeks):
for mm in ALL_DAYS:
mm = int(input("Enter the amount of rain (in mm) for ", ALL_DAYS, "of week ", range(total_weeks), ": "))
if mm != int():
print("Amount of rain must be an integer")
elif mm < 0 :
print("Amount of rain must be non-negative")
# Calculate totals.
total_rainfall =+ mm
average_weekly = total_rainfall / total_weeks
average_daily = total_rainfall / (total_weeks*7)
# Display results.
print ("Total rainfall: ", total_rainfall, " mm ")
print("Average rainfall per week: ", average_weekly, " mm ")
print("Average rainfall per week: ", average_daily, " mm ")
if __name__=="__main__":
__main__()
If you can steer me in the right direction I will be so appreciative!
Recommendation: Break the problem into smaller pieces. Best way to do that would be with individual functions.
For example, getting the number of weeks
def get_weeks():
total_weeks = 0
while True:
try:
total_weeks = int(input("Enter the number of weeks for which rainfall should be calculated: "))
if total_weeks < 1:
print("Number of weeks must be at least 1")
else:
break
except ValueError:
print("Number of weeks must be an integer.")
return total_weeks
Then, getting the mm input for a certain week number and day. (Here is where your expected output exists)
def get_mm(week_num, day):
mm = 0
while True:
try:
mm = int(input("Enter the amount of rain (in mm) for {0} of week {1}: ".format(day, week_num)))
if mm < 0:
print("Amount of rain must be non-negative")
else:
break
except ValueError:
print("Amount of rain must be an integer")
return mm
Two functions to calculate the average. First for a list, the second for a list of lists.
# Accepts one week of rainfall
def avg_weekly_rainfall(weekly_rainfall):
if len(weekly_rainfall) == 0:
return 0
return sum(weekly_rainfall) / len(weekly_rainfall)
# Accepts several weeks of rainfall: [[1, 2, 3], [4, 5, 6], ...]
def avg_total_rainfall(weeks):
avgs = [ avg_weekly_rainfall(w) for w in weeks ]
return avg_weekly_rainfall( avgs )
Using those, you can build your weeks of rainfall into their own list.
# Build several weeks of rainfall
def get_weekly_rainfall():
total_weeks = get_weeks()
total_rainfall = []
for week_num in range(total_weeks):
weekly_rainfall = [0]*7
total_rainfall.append(weekly_rainfall)
for i, day in enumerate(ALL_DAYS):
weekly_rainfall[i] += get_mm(week_num+1, day)
return total_rainfall
Then, you can write a function that accepts that "master list", and prints out some results.
# Print the output of weeks of rainfall
def print_results(total_rainfall):
total_weeks = len(total_rainfall)
print("Weeks of rainfall", total_rainfall)
for week_num in range(total_weeks):
avg = avg_weekly_rainfall( total_rainfall[week_num] )
print("Average rainfall for week {0}: {1}".format(week_num+1, avg))
print("Total average rainfall:", avg_total_rainfall(total_rainfall))
And, finally, just two lines to run the full script.
weekly_rainfall = get_weekly_rainfall()
print_results(weekly_rainfall)
I use a list to store average rallfall for each week.
and my loop is:
1.while loop ---> week (using i to count)
2.in while loop: initialize week_sum=0, then use for loop to ask rainfall of 7 days.
3.Exit for loop ,average the rainfall, and append to the list weekaverage.
4.add week_sum to the total rainfall, and i+=1 to next week
weekaverage=[]
i = 0 #use to count week
while i<total_weeks:
week_sum = 0.
print "---------------------------------------------------------------------"
for x in ALL_DAYS:
string = "Enter the amount of rain (in mm) for %s of week #%i : " %(x,i+1)
mm = float(input(string))
week_sum += mm
weekaverage.append(weeksum/7.)
total_rainfall+=week_sum
print "---------------------------------------------------------------------"
i+=1
print "Total rainfall: %.3f" %(total_rainfall)
print "Day average is %.3f mm" %(total_rainfall/total_weeks/7.)
a = 0
for x in weekaverage:
print "Average for week %s is %.3f mm" %(a,x)
a+=1