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)
Related
I edited the post to get the word cross sum instead of factorial in it, thanks for your help.
def assignment_2():
# write a function that outputs the cross sum of a number (54321 -> 5 + 4 + 3 + 2 + 1 = 15)
number = int(input('enter a number'))
result = 0
while number:
result = result + number % 10
number = int(number / I0)
return result, number
when I call the function I get the result no problem, but the number is = 0 because its going through that loop.
That's how I call the function
result, number = assignment_2()
print(f'assignment 2: the cross sum of {number} is {result}')
Just save the value to another variable:
number = int(input('enter a number'))
orig = number
result = 0
while number:
result = result + number % 10
number = int(number / 10)
return result, orig
You'll have to save it in another variable:
number = int(...)
saved_number = number
...
return result, saved_number
Also, I should note that what you're doing here is not the factorial, but the digit sum. Factorial is the product of all numbers from 1 to the argument—for instance, 5 factorial is 5×4×3×2×1 = 120.
You can use the input value as a string to get the digit sum, your algorithm does not need to transform its input at all:
def digit_sum(x):
return sum(int(xx) for xx in str(x)), x
def assignment_2():
return digit_sum(int(input("Please enter a number ")))
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).
Please help, I cannot figure out why this code does not work. I think the first loop runs forever but I don't know why!
def NTN():
list1 = []
count = 0
number = 0
Start = input('Type Start Number')
while number != Start:
count = count + 1
number = number + count
Stop = input('Type Stop Number')
while number != Stop:
count = count + 1
number = number + count
if number != Stop:
(list1).append(number)
return (list1)
print(NTN())
You are increasing number by increasing amounts in every iteration. Here's an idea of how it is increasing. Assume Start = 4
After 1 loop, count = 1 and number = 1, increase of 1
After 2 loops, count = 2 and number = 3, increase of 2
After 3 loops, count = 3 and number = 6, increase of 3
Since number is never really equal to 4, the loop never ends. What you need probably is while number <= Start. That would terminate the loop after 3 iterations when number is past 4.
change "number != Start" and "number != Stop" to "number < Start" and "number < Stop" in all places, and it should work.
What went wrong: if Start is 2, then in the first iteration of the while loop, count becomes 0+1=1 and number becomes 0+1=1; in the second iteration, count becomes 1+1=2 and number becomes 1+2=3, which bypasses 2. Since your while loop only ends when number is equal to Start, it never ends.
A couple of side-points:
By convention Python variable and function names are lower-case.
input() returns a string; if you want a number you have to convert it ie with int() or float(). (Note: if you are using Python 2.x input() calls eval() which is really awful design - you should be using int(raw_input()) instead.)
so,
# This code assumes Python 3.x
from math import ceil, sqrt
def get_int(prompt):
"""
Prompt until an integer value is entered
"""
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter an integer!")
def tri(n):
"""
Return triangular number n,
ie the sum of (1 + 2 + ... + n)
"""
# using Gaussian sum
return n * (n + 1) // 2
def reverse_tri(t):
"""
For positive integer t,
return the least positive integer n
such that t <= tri(n)
"""
# derived by quadratic formula from
# n * (n + 1) // 2 >= t
return int(ceil(((sqrt(8 * t + 1) - 1) / 2)))
def ntn(start, stop):
"""
Return a list of triangular numbers
such that start <= tri < stop
"""
a = reverse_tri(start)
b = reverse_tri(stop)
return [tri(n) for n in range(a, b)]
def main():
start = get_int('Enter a start number: ')
stop = get_int('Enter a stop number: ')
lst = ntn(start, stop + 1) # include stop number in output
print(lst)
if __name__ == "__main__":
main()
I'm trying to write a python function number_pairs which consumes a natural positive number n, and reads in n pairs of natural positive numbers from the user. Each pair represents a value and its frequency. For each pair, the function must prompt the user to input two positive integers the value and its frequency, while indicating the index of the expected pair. The process repeats until all n pairs have been entered. At the end, the function should print the average (of Float type, with the exact string message as in the example) of the n pairs of numbers, and returns the average as well. You may assume that the user only inputs valid data.
I was thinking that maybe writing a helper function that does accumulative recursion but I missed a lot of lectures and I have no idea how to do it. This is what I have so far:
def averge_h(counter):
...
def number_pairs(n):
prompt1 = "Enter value for pair number "
prompt2 = "Enter its frequency:\n"
pn = "{0}: ".format(n)
res="Their average is: "
v = int(input(prompt1+pn))
f = int(input("Enter its frequency: "))
if n = 1:
average = (v*f)/f
else:
v = v+1
print res + str(average)
return average
You can try something like this :
def read_and_avg(sum_,n,left,i): ## left is the number of times the input is to be taken
if left == 0:
print (sum_/float(n))
return (sum_/float(n))
else:
i = i + 1
print "Enter the values for pair number "+str(i)
a = int(input())
b = int(input())
sum_ = sum_ + (a*b) ## Increment the sum
n = n + b ## Increment the total count
print sum_,n,left
return read_and_avg(sum_,n,left-1,i) ## Decrease left by 1,
def func(n):
read_and_avg(0,0,n,0)
Since you said it can only have one argument "n" take a look at this:
def number_pairs(n):
if n == 0:
return 0
else:
average = number_pairs(n-1)
print str(n) + ("st" if n == 1 else ("nd" if n == 2 else ("d" if n == 3 else "th"))) + " pair"
val = input("value: ")
frq = input("frequency: ")
print "" # added for new line
return average + (val * frq)
n = input("Enter the number of pairs: ")
print "" # added for new line
print "The average is: " + str(number_pairs(n) / n)
Output:
Enter the number of pairs: 5
1st pair
value: 1
frequency: 2
2nd pair
value: 2
frequency: 2
3d pair
value: 3
frequency: 2
4th pair
value: 4
frequency: 2
5th pair
value: 5
frequency: 2
The average is: 6
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