I'm trying to create a program that lets me calculate x(i)=1/i^2 for i=1,2,⋯,N
Here is my code so far:
end = int(input("How many times do you want to calculate it?: "))
x = 0.0
for i in range (0, end):
x = x + (1 / end **2)
print ("The sum is", x)
I seem to have a problem with it adding the different values of X together.
How would I do it if i need it to work?
You aren't using your increment i.
You are also dividing by zero.
Try:
end = int(input("How many times do you want to calculate it?: "))
x = 0.0
for i in range (1, end+1):
x = x + (1 / (i**2))
print ("The sum is", x)
That should provide the result you are looking for. Enjoy!
Even in this little bit of code, there are a number of things to do better.
end = int(input("How many times do you want to calculate it?: "))
print(sum([1/i*2 for i in range(1, end+1)]))
Use built-in functions like sum. They're a major strength of python.
Be careful with range. Ranges start at 0 by default, and you don't want to divide by 0, of course. Also, I take it that you want end to be the last value of i. In that case, you have to add 1 to end to get it included in the range.
Hope this helps.
Accounting for divide by zero problems and using sum feature and list comprehension (more compact):
end = int(input("How many times do you want to calculate it?: "))
x = 0
x = sum([x + (1.0/(i**2)) for i in range(1, end+1)])
print ("The sum is", x)
Emphasis on 1.0 so you're not dividing by 0
Related
I'm brand new to this, 10 days in.
I've been thinking how I could solve this for 30 min. Please help.
Find Average
You need to calculate the average of a collection of values. Every value will be valid number. The average must be printed with two digits after the decimal point.
Input-
On the first line, you will receive N - the number of the values you must read
On the next N lines you will receive numbers.
Output-
On the only line of output, print the average with two digits after the decimal point.
Input
4
1
1
1
1
Output
1.00
Input
3
2.5
1.25
3
Output
2.25
From what I see, I figure I need to create as much inputs as the N of the first one is and then input the numbers Id like to average and then create a formula to average them. I may be completely wrong in my logic, in any case Id be happy for some advice.
So far I tried creating a while loop to create inputs from the first input. But have no clue about the proper syntax and continue with making the new inputs into variables I can use
a=int(input())
x=1
while x<a or x==a:
float(input())
x=x+1
a=int(input('Total number of input: '))
total = 0.0
for i in range(a):
total += float(input(f'Input #{i+1}: '))
print('average: ', round(total/a,2))
Modified a bit on your version to make it work
There were few things that you were doing wrong. when the numbers are decimals use float not int.
If you are looking for a single line input this should be how it's done.
When writing the code please use proper variables and add a string that's asking for the input.
total = 0
first_num=int(input("Number of inputs: "))
number = input("Enter numbers: ")
input_nums = number.split()
for i in range(first_num):
total = total + int(input_nums[i])
average = total/first_num
print(average)
If you are looking for a multiline output This should be how it's done.
first_num=int(input("Number of inputs: "))
x=1
total = 0
while x<first_num or x==first_num:
number = float(input("Enter numbers: "))
total = total + number
x=x+1
avg = total/first_num
print(avg)
The output shows a different result. Yes, the factorials of those numbers are right but the numbers outputted aren't right.
Here's the code:
input:
n = int(input("Enter a number: "))
s = 0
fact = 1
a = 1
for i in range(len(str(n))):
r = n % 10
s += r
n //= 10
while a <= s:
fact *= a
a += 1
print('The factorial of', s, 'is', fact)
Output:
Enter a number: 123
The factorial of 3 is 6
The factorial of 5 is 120
The factorial of 6 is 720
You're confusing yourself by doing it all in one logic block. The logic for finding a factorial is easy, as is the logic for parsing through strings character by character. However, it is easy to get lost in trying to keep the program "simple," as you have.
Programming is taking your problem, designing a solution, breaking that solution down into as many simple, repeatable individual logic steps as possible, and then telling the computer how to do every simple step you need, and what order they need to be done in to accomplish your goal.
Your program has 3 functions.
The first is taking in input data.
input("Give number. Now.")
The second is finding individual numbers in that input.
for character in input("Give number. Now."):
try:
int(character)
except:
pass
The third is calculating factorials for the number from step 2. I won't give an example of this.
Here is a working program, that is, in my opinion, much more readable and easier to look at than yours and others here. Edit: it also prevents a non numerical character from halting execution, as well as using only basic Python logic.
def factorialize(int_in):
int_out = int_in
int_multiplier = int_in - 1
while int_multiplier >= 1:
int_out = int_out * int_multiplier
int_multiplier -= 1
return int_out
def factorialize_multinumber_string(str_in):
for value in str_in:
print(value)
try:
print("The factorial of {} is {}".format(value, factorialize(int(value))))
except:
pass
factorialize_multinumber_string(input("Please enter a series of single digits."))
You can use map function to get every single digit from number:
n = int(input("Enter a number: "))
digits = map(int, str(n))
for i in digits:
fact = 1
a = 1
while a <= i:
fact *= a
a += 1
print('The factorial of', i, 'is', fact)
Ok, apart from the fact that you print the wrong variable, there's a bigger error. You are assuming that your digits are ever increasing, like in 123. Try your code with 321... (this is true of Karol's answer as well). And you need to handle digit zero, too
What you need is to restart the calculation of the factorial from scratch for every digit. For example:
n = '2063'
for ch in reversed(n):
x = int(ch)
if x == 0:
print(f'fact of {x} is 1')
else:
fact = 1
for k in range(2,x+1):
fact *= k
print(f'fact of {x} is {fact}')
I am gitting stuck here, please help. The code has to promt the user to enter a number, pass the number to a python function and let the function calculate the average of all the numbers from 1 to the number entered by the user.
def SumAverage(n):
sum=0
for idx in range(1,n+1):
average =sum/idx
return average
num =int(input("Enter a number"))
result=SumAverage(num)
print("The average of all numbers from 1 to {} is {}".format(num,result))
The sum of the series 1 + 2 + 3 + ... + n where n is the user inputted number is:
n(n+1)/2 (see wikipedia.org/wiki/1+2+3+4+...)
We have that the average of a set S with n elements is the sum of the elements divided by n. This gives (n(n+1)/2)/n, which simplifies to (n+1)/2.
So the implementation of the average for your application is:
def sum_average(n):
return (n + 1) / 2
This has the added benefit of being O(1).
Your version is not working because the average is always set to the last calculation from the for loop. You should be adding the idx for each iteration and then doing the division after the loop has completed. However, all of that is a waste of time because there is already a function that can do this for you.
Use mean from the statistics module.
from statistics import mean
num = int(input("Enter a number"))
result = mean(list(range(1, num+1)))
print(f'The average of all numbers from 1 to {num} is {result}')
If you are determined to do the logic yourself it would be done as below, if we stick with your intended method. #zr0gravity7 has posted a better method.
def SumAverage(n):
sum=0
for i in range(1,n+1):
sum += i
return round(sum / n, 2)
num = int(input("Enter a number"))
result = SumAverage(num)
print(f'The average of all numbers from 1 to {num} is {result}')
I'm not recommending this, but it might be fun to note that if we abuse a walrus (:=), you can do everything except the final print in one line.
from statistics import mean
result = mean(list(range(1, (num := int(input("Enter a number: ")))+1)))
print(f'The average of all numbers from 1 to {num} is {result}')
I went ahead and wrote a longer version than it needs to be, and used some list comprehension that would slow it down only to give some more visibility in what is going on in the logic.
def SumAverage(n):
sum=0
l = [] # initialize an empty list to fill
n = abs(n) # incase someone enters a negative
# lets fill that list
while n >= 1:
l.append(n)
print('added {} to the list'.format(n), 'list is now: ', l)
n = n - 1 # don't forget to subtract 1 or the loop will never end!
# because its enumerate, I like to use both idx and n to indicate that there is an index and a value 'n' at that index
for idx, n in enumerate(l):
sum = sum + n
# printing it so you can see what is going on here
print('length of list: ', len(l))
print('sum: ', sum)
return sum/len(l)
num =int(input("Enter a number: "))
result=SumAverage(num)
print("The average of all numbers from 1 to {} is {}".format(num,result))
Try this:
def SumAverage(n):
sum=0
for i in range(1,n+1):
sum += i
average = sum/n
return average
[its the better plz see this.
(short description):- user enter the list through functions then that list is converted into int. And the average is calculated all is done through functions thanx
]1
This program starts with 1 cent and doubles each day. However, I'm stuck on trying to find a way to convert the number of pennies into a dollar and cent amount. For example, converting 1020 pennies to $10.20.
I'm also attempting to make it so if user input is not a positive number, the user will be continously prompted until they enter a positive number. This isn't working, however.
I also feel I've messed up by using range, as I want to enter a set number of days, say 16 days, and when I enter 16, I receive the days 1-17, as range should be doing, and I'm not sure how to go about fixing that.
b = int(input("Input number of days "))
if b > 0:
print(b)
else:
b = int(input("Days must be positive "))
print("Day 1:","1")
days = 1
aIncrement = 2
penny = 1
for i in range(b):
pAmount = int(penny*2)
addAmount = int(2**aIncrement -1)
aIncrement +=1
days +=1
penny *= 2
print("Day " + str(days) + ":",pAmount)
Your question has multiple parts, which is not ideal for stackoverflow, but I will try to hit them all.
Fixing the numeric values to show dollars and cents.
As noted in comments to other answers, division can often run into snags due to floating point notation. But in this case, since all we really care about is the number of times 100 will go into the penny count and the remainder, we can probably safely get away with using divmod() which is included with Python and calculates the number of times a number is divisible in another number and the remainder in whole numbers.
For clarity, divmod() returns a tuple and in the sample below, I unpack the two values stored in the tuple and assign each individual value to one of two variables: dollars and cents.
dollars, cents = divmod(pAmount, 100) # unpack values (ints)
# from divmod() function
output = '$' + str(dollars) + '.' + str(cents) # create a string from
# each int
Fixing the range issue
The range() function produces a number and you can set it to start and end where you want, keeping in mind that the ending number must be set at one value higher than you want to go to... i.e. to get the numbers from one to ten, you must use a range of 1 to 11. In your code, you use i as a placeholder and you separately use days to keep track of the value of the current day. Since your user will tell you that they want b days, you would need to increment that value immediately. I suggest combining these to simplify things and potentially using slightly more self-documenting variable names. An additional note since this starts off on day one, we can remove some of the setup code that we were using to manually process day one before the loop started (more on that in a later section).
days = int(input("Input number of days "))
for day in range(1, days + 1):
# anywhere in your code, you can now refer to day
# and it will be able to tell you the current day
Continuous input
If we ask the user for an initial input, they can put in:
a negative number
a zero
a positive number
So our while loop should check for any condition that is not positive (i.e. days <= 0). If the first request is a positive number, then the while loop is effectively skipped entirely and the script continues, otherwise it keeps asking for additional inputs. Notice... I edited the string in the second input() function to show the user both the problem and to tell them what to do next.
days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input positive number of days: "))
Putting all this together, the code might look something like this:
I put the items above together AND cleaned up a few additional things.
days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input number of days: "))
# aIncrement = 2 # this line not needed
penny = 1
for day in range(1, days + 1):
pAmount = int(penny) # this line was cleaned up
# because we don't need to manually
# handle day one
dollars, cents = divmod(pAmount, 100)
output = '$' + str(dollars) + '.' + str(cents)
# addAmount = int(2**aIncrement -1) # this line not needed
# aIncrement +=1 # this line not needed
penny *= 2
print("Day " + str(day) + ":", output)
For the continuous prompting, you can use a while loop.
while True:
user_input = int(input("Enter the number"))
if user_input > 0:
break
else:
continue
Or alternatively:
user_input = int(input("Enter the number"))
while user_input <= 0:
user_input = int(input("Enter the number"))
For the range issue, you can add -1 to the parameter you're passing range.
for i in range(b - 1):
I am using python version 3.
For homework, I am trying to allow five digits of input from the user, then find the average of those digits. I have figured that part out (spent an hour learning about the map function, very cool).
The second part of the problem is to compare each individual element of the list to the average, then return the ones greater than the average.
I think the "if any" at the bottom will compare the numbers in the list to the Average, but I have no idea how to pull that value out to print it. You guys rock for all the help.
#Creating a list
my_numbers = [input("Enter a number: ") for i in range(5)]
#Finding sum
Total = sum(map(int, my_numbers))
#Finding the average
Average = Total/5
print ("The average is: ")
print (Average)
print ("The numbers greater than the average are: ")
if any in my_numbers > Average:
#Creating a list
my_numbers = []
r = range(5)
for i in r:
try:
my_numbers.append(int(input("Enter a number: ")))
except:
print( 'You must enter an integer' )
r.append(i)
#Finding sum
Total = sum(my_numbers)
#Finding the average
Average = Total/5
print ("The average is: ")
print (Average)
print ("The numbers greater than the average are: ")
print ([x for x in my_numbers if x>Average])
I'm sure that you would finally have succeeded in your code even if nobody hadn't answered.
My code is in fact to point out that you should foresee that entries could be non-integer and then to put instruction managing errors of entry.
The basic manner here is to use try except
Note the way I add i to r each time an error occurs in order to make up for the element of r that has been consumed.
Unfortunately, "if any" doesn't work. Take a look at the docs for the any function to se what it does. It doesn't do what you want even if your syntax had been correct. What you want is only the numbers greater than the average. You could use a list comprehension: [number for number in my_numbers if number > Average]. Or you could use a loop.
What you need to do is iterate through the list and print out the numbers above the average:
for i in my_numbers:
if int(i) > Average:
print(i)
To make things easier, you might also want to have the my_numbers list actually start out as a list of integers:
my_numbers = [int(input("Enter a number: ")) for i in range(5)]
Now we can get rid of the map function (don't worry, the hour did not go to waste, you'll find it very useful in other situations as well). You could also go straight to calculating the average without calculating the total, since you won't need the total again.
Average = sum(my_numbers) / 5
This means you can change the for loop so that you can replace int(i) with i.
You could also create a list with a list comprehension, and then print out the values in that list.
aboveAverage = [i for i in my_numbers if i > Average]
for i in aboveAverage:
print i