Find average in python - python

can anyone help?
import math
a = int(raw_input('Enter Average:')) # Average number probability
c = int(raw_input('Enter first number:')) #
d = int(raw_input('Enter last number:')) #
e = 2.71828
for b in range(c,d+1):
x = (a**b)/math.factorial(b)*(e**-a)
odd = round (1/x*0.92, 2)
print odd
How to find average value of odd?

You can do two things:
Accumulate all of those odd values into, e.g., a list, then average the result.
Keep a running total and count and divide.
(I'm assuming that by "average" you mean "arithmetic mean". If you mean something different, the details are different, but the basic idea is the same.)
For the first:
odds = []
for b in range(c,d+1):
x = (a**b)/math.factorial(b)*(e**-a)
odd = round (1/x*0.92, 2)
print odd
odds.append(odd)
print sum(odds) / len(odds)
If you don't what sum or len do, read the docs.
For the second:
total, count = 0, 0
for b in range(c,d+1):
x = (a**b)/math.factorial(b)*(e**-a)
odd = round (1/x*0.92, 2)
print odd
total += odd
count += 1
print total / count

Related

Trying to calculate the arithmetic median

I was just trying to calculate the arithmetic median of a list. Odd list length works but my program has problems with even list length.
here's an example:
The example for the even numbers
Here is what I tried:
#the sorted list
number = int(input('How many numbers do you want to put in? '))
print("")
values = []
for i in range(number):
values.append(int(input('Please enter a value: ')))
print("")
sort = sorted(values)
print("Sorted list:", sort)
#the function
firstMid = int(len(sort)) / 2
secoundMid = (int(len(sort)) / 2) + 1
if isOdd(len(values)) == True:
print("Zentralwert:", values[int(len(sort)/2)]) #odd numbers
else:
print("Zentralwert:", (firstMid + secoundMid) / 2)
It seems you are trying to find median.
For odd numbers, it's the middle number.
[1,2,3,4,5,6,7,8,9] -> Median is 5 at index 4 means index = len(arr) // 2 # // is integer division in python and returns floor value. So 9/2 = 4.5 but 9//2 = 4
Now for even numbers, median would be mean of middle two numbers ie (4+5)/2.
Now here we need to target the correct elements using correct index.
For 8 elements, the correct number would be at index len(arr)//2 8//2 = 4 and len(arr)//2 - 1 8//2 -1 = 4-1=3
Your code should now be this.
#the function
firstMidIndex = int(len(sort)) // 2
secoundMidIndex = (int(len(sort)) // 2) - 1
if isOdd(len(values)) == True:
print("Zentralwert:", sort[firstMidIndex] #odd numbers
else:
print("Zentralwert:", (sort[firstMidIndex] + sort[secoundMidIndex]) / 2)
Probably you want,
#the sorted list
number = int(input('How many numbers do you want to put in? '))
print("")
values = []
for i in range(number):
values.append(int(input('Please enter a value: ')))
print("")
sort = sorted(values)
print("Sorted list:", sort)
#the function
firstMid = int(len(sort)) / 2
secoundMid = (int(len(sort)) / 2) + 1
if isOdd(len(values)) == True:
print("Zentralwert:", sort[int(len(sort)/2)]) #odd numbers
else:
print("Zentralwert:", (sort[firstMid] + sort[secoundMid]) / 2)

How to write a for loop program that finds the sum of all odd numbers in a range, but does not use the if function

I need to write a code that asks for user input 'num' of any number and calculates the sum of all odd numbers in the range of 1 to num. I can't seem to figure out how to write this code, because we had a similar question about adding the even numbers in a range that I was able to figure out.
I've also added the lines of code that I've written already for any critiques of what I may have done right/wrong. Would greatly appreciate any help with this :)
total = 0
for i in range(0, num + 1, 1):
total = total + i
return total
total = sum(range(1, num + 1, 2))
if you really need a for loop:
total = 0
for i in range(1, num+1, 2):
total += i
and to make it more exotic, you can consider the property that i%2==1 only for odd numbers and i%2==0 for even numbers (caution: you make your code unreadable)
total = 0
for i in range(1, num+1):
total += i * (i % 2)
You can invent a lot more ways to solve this problem by exploiting the even-odd properties, such as:
(-1)^i is 1 or -1
i & 0x1 is 0 or 1
abs(((1j)**i).real) is 0 or 1
and so on
The range function has three parameters: start, stop, and step.
For instance: for i in range(1, 100, 2) will loop from 1-99 on odd numbers.
Easiest solution
You can use math formula
#sum of odd numbers till n
def n_odd_sum(n):
return ((n+1)//2)**2
print(n_odd_sum(1))
print(n_odd_sum(2))
print(n_odd_sum(3))
print(n_odd_sum(4))
print(n_odd_sum(5))
1
1
4
4
9
Using filter:
start_num = 42
end_num = 500
step = 7
sum([*filter(lambda x: x % 2 == 1, [*range(start_num, end_num+1, step)])])
You can use the math formula (works every time):
num = int(input("Input an odd number: "))
total = (1+num)**2//4
print(total)
Output:
Input an odd number: 19
100
total = 0
num = int(input())
for i in range(num+1):
if i%2 == 1:
total += i
print (total)
The % operator returns the remainder, in this case, the remainder when you divide n/2. If that is 1, it means your number is odd, you can add that to your total.
You can of course do it in 1 line with python, but this might be easier to understand.

I want to find the sum of the number which i have

I have some code where I must find the multiples of number 3 and then summarize them
I have done the first job, I mean I found all the multiples of number 3 with for loop but I can't summarize all the numbers which I found.
I have tried so many times and tried to find the solution on google, but could not find
x = 3
for number in range(1000):
if number%x == 0:
print(number)
I need now the sum of all the numbers which indicates on this code, when you run this code you can see that there is publishing only the numbers that can divide by 3 now I need the sum of them
It's easier than you think:
sum(range(0, 1000, 3))
Explanation:
range is defined as such: range([start], end[, step]) so range(0, 1000, 3) means go from 0 to 1000 in steps of 3
The sum function will sum over any iterable (which includes range)
You need a variable to hold the sum (If you are in learning stage):
x = 3
total = 0
for number in range(1000):
if number % x == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
Edit:
To answer your comment use condition or condition:
x = 3
y = 5
total = 0
for number in range(10):
if number % x == 0 or number % y == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
You could create a result variable to which you can keep adding:
result = 0
x = 3
for number in range(1000):
if number%x == 0:
result += number
print(result)
The best way is using filter and sum:
# any iterable variable
iterable_var = range(100)
res = sum(filter(lambda x: x % 3 == 0, iterable_var), 0)

How do you find a median without using lists?

My teacher wants me to find the median of 10 inputs from the user by using iterations.
This is how I used iterations to find the sum, number of odd numbers, the max, and the number of prime numbers. But I'm stuck on finding the median.
def Main(): #main function
sum=0
odd=0
temp=0
prime=0
median=0
for i in range(10):
x=float(input("Please enter a number")) #ask user for input 10 times
sum=sum+x #adds all inputs together
if x%2!=0: #all even numbers are divisible by 2
odd=odd+1
if x>=temp: #update temp with current largest input
temp=x
for p in range (2,int(math.sqrt(x))+1):#find prime numbers
if x>=2 and x%p==0: prime=prime+1
import math
def Main(): #main function
sum=0
odd=0
temp=0
prime=0
median=0
my_list =[]
for i in range(10):
x=float(input("Please enter a number: ")) #ask user for input 10 times
sum=sum+x #adds all inputs together
if x%2!=0: #all even numbers are divisible by 2
odd=odd+1
if x>=temp: #update temp with current largest input
temp=x
for p in range (2,int(math.sqrt(x))+1):#find prime numbers
if x>=2 and x%p==0: prime=prime+1
my_list.append(x)
my_list.sort()
size =len(my_list)
if size == 1:
median = my_list[0]
elif size % 2 == 0:
size = int(size/2)
median=(my_list[size-1]+my_list[size])/2
else:
median = my_list[int(size / 2)]
print("sum is ", sum, ",odd is ", odd, ",temp is ", temp, ",prime is ", prime, "median is ", median)
Main()
First of all, as a user pointed out in a comment to your question, your method to determine prime numbers is not correct. You only should increase that counter after all factors have been checked, not after each one.
There are a few questions on StackOverflow that show how to calculate primes in python; here is a slightly improved version of your code with that error fixed (and some style improvement suggestions):
def main():
sum = 0
counter_odd = 0
max_num = None
min_num = None
counter_prime = 0
median = 0
for i in range(10):
x = float(input("Please enter a number"))
sum += x
if x % 2 != 0:
counter_odd += 1
if max_num is None or max_num < x:
max_num = x
if min_num is None or min_num > x:
min_num = x
if x == 0 or x == 1:
counter_prime += 1
elif x > 1:
if not any(x % d == 0 for d in range(2, int(math.sqrt(x)) + 1)):
counter_prime += 1
As to your main question: there are several questions on SO about finding medians in unsorted lists (that would be very similar to searching for medians without having the whole list at the beginning). Maybe search for that without the Python tag, so you get to see some algorithms without tying to a specific language.
For example, in this question you can find the suggestion to use the median of medians approach (Wikipedia).

Sum of Even Fibonacci Numbers < X

I'm working on this one and I seem to have a working solution but I have difficulty understanding its behaviour.
Here is what I have.
#!/usr/bin/python
def even_fib_sums(limit):
number = 1
last = 0
before_last = 0
total = 0
for counter in range (0,limit):
before_last = last
last = number
number = before_last + last
if not number % 2:
total += number
yield total
print sum(even_fib_sums(4000000))
I'm new to programming but it makes sense to me that this is not very effective considering I need to cycle through all 4000000 numbers in the range.
If I use the same approach in generating the Fibonacci sequence up to 5 as follows, you will see the results below.
def generate_fib(limit):
number = 1
last = 0
before_last = 0
total = 0
for counter in range (0,limit):
before_last = last
last = number
number = before_last + last
print number
generate_fib(5)
Result: 1,2,3,5,8
Of these numbers in the result, only 2 and 8 % 2 == 0.
The sum should be 10 but I am returning 12 if I am to use the first snippet above. Why so?
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
You only need to loop until you hit a fib that is > 400000 not the 4 millionth fibonacci number which your code is trying to do, you can simplify to a using generator function with sum, only yielding even numbers and breaking the loop when you hit a fibonacci number > 4000000:
def fib(n):
a, b = 0, 1
while a <= n:
a, b = b, a + b
if not b & 1:
yield b
print(sum(fib(4000000)))
It takes a fraction of a second to compute:
In [5]: timeit sum(fib(4000000))
100000 loops, best of 3: 6 µs per loop
trying to timeit even_fib_sums(4000000) is still running after a few minutes.
by using for counter in range(0, limit) you are having 'limit' iteration in your function. for example, if your 'limit' variable is 10, you won't have the sum of even fibonachi numbers that are less than 10, but you will have the sum of the first 10 fibonachi numbers that are even.
To make your code works properly, you need to remplace for counter in range(0, limit) by while last < limit, and each time you find that last is even, you add it to total.
You can probably clean up that generating function a bit. Here is how I would write it.
def fib(x):
a = 1
b = 1
yield a
yield b
a,b = b,a+b
while b<=x:
yield b
a,b = b,a+b
This will give you a generating function which will give you all Fibonacci numbers less than or equal to x (we should be a little more careful here, as we will return the first two numbers no matter what).
Then we can just do
sum(x for x in fib(4000000) if x%2==0)
You should change your code to just yield the number, not the sum or just change yield to return, and remove the sum() keyworkd like this:
def even_fib_sums(limit):
number = 1
last = 0
before_last = 0
total = 0
for counter in range (0,limit):
before_last = last
last = number
number = before_last + last
if not number % 2:
total += number
return total
print even_fib_sums(5)
In the first code snippet, you sum the total of round numbers, instead of just yielding the number. If you expect to get 10 in your first snippet for an input of 5, you should amend the code in either of the following ways (not trying to be efficient here, just to fix the problem):
...
number = before_last + last
if not number % 2:
yield number
print sum(even_fib_sums(4000000))
or
...
number = before_last + last
if not number % 2:
total += number
return total
print even_fib_sums(4000000)

Categories

Resources