I am trying to read in a text file of integers, make it a list, compute the average of all integers, compute the average of all non-negative integers, print max and min. I was able to compute the average of all integers but am having difficulty getting the average of all non-negative integers and the max and min.
Here is what I have so far:
file = open("numberlist.txt", "r")
sum = 0
list = []
for num in file:
list.append(num)
poslist = []
for number in file:
x = int(number)
if x > 0:
poslist.append(x)
sum += number
posavg = sum / len(poslist)
print("The number of non-negative integers is ", len(poslist))
print("The average of the non-negtive integers is ", posavg)
If the numbers are separated by spaces
(or, as I understand from your code, by new lines)
this is a very short and "Pythonic" task!
First, let's read the entire file into numbers
and also have the file close automatically:
with open('numberlist.txt') as f:
nums = [int(x) for x in f.read().split() if int(x) >= 0]
After the previous 2 line you have all the non-negative
numbers in a list called nums!
Now, the average would be:
avg = sum(nums) / len(nums)
And the min/max would be:
minNum, maxNum = min(nums), max(nums)
And that's all!
Now, I pushed as much Python as I think is possible
into this task, so by understanding this code you make
a leap in Python!
This keeps most of your code and adds the non-negative part to it (perhaps should be called positive instead? :)
file = open("numberlist.txt", "r")
sum = 0
nonNegativeTotal = 0
nonNegativeCount = 0
list = []
for num in file:
list.append(num)
for number in list:
x = int(number)
if x >= 0:
nonNegativeCount += 1
nonNegativeTotal += x
sum += x
avg = sum/len(list)
avgNonNegative = nonNegativeTotal/nonNegativeCount
print("The number of integers is ", len(list))
print("The overall average is ", avg)
print("The number of non-negative numbers is ", nonNegativeCount)
print("The non-negative average is ", avgNonNegative)
list.sort()
print("The minimum number is ", list[0])
print("The maximum number is ", list[-1])
For the min and max you could do:
minNum, maxNum = min(list), max(list)
Related
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)
Apologies, first time poster, and beginner python user.
The problem asks the following:
Write a Python program that allows the user to enter any number of nonnegative floating-point values. The user terminates the input list with any negative value. The program then prints the sum, average (arithmetic mean), maximum, and minimum of the values entered. The terminating negative value is not used in the computations.
I pretty much have most of it, have tried a few different ways, and can not seem to get it to compute the average and sum correctly. (can not get it without the negative number to terminate, or also makes the average negative, or the same as the sum value)
I am considering starting over and using a def function call. ??
I also was starting to get somewhere with try-except statements, but that fell apart as well.
Any advice in the right direction is appreciated!
First...
num = []
tot = 0
big = None
small = None
while True:
numbers = float(input('Enter a positive number, negative to stop: '))
tot += numbers
if big is None or numbers > big:
big = numbers
if small is None or numbers < small:
small = numbers
if numbers < 0:
break
avg = tot / numbers
print('Sum is:', tot)
print('Average is:',avg)
print('Maximum is:',big)
print('Minimum is:',small)
and if I change a few things I get the average to be positive instead of negative, but still is the same value as minimum, just some snippets...
tot = 0
big = None
small = None
count = 0
while True:
length = count + 1
#etc, etc...then trying to do...
avg = tot/length
#or...
avg =str(tot/length)
but still stuck.
num = []
tot = 0
small = None
avg = None
big = None
while True:
numbers = float(input('Enter a positive number, negative to stop: '))
if numbers < 0:
break
tot +=numbers
num.append(numbers)
if small== None and big == None and avg == None:
small=numbers; big=numbers; avg = numbers
else:
small = min(small, numbers)
small = max(big, numbers)
if len(num) > 0:
avg = tot / len( num)
print('Sum is:', tot)
print('Average is:',avg)
print('Maximum is:',big)
print('Minimum is:',small)
num = []
tot = 0
small = None
avg = None
big = None
while True:
numbers = float(input('Enter a positive number, negative to stop: '))
if numbers < 0:
break
tot +=numbers
num.append(numbers)
if len(num) > 0:
avg = tot / len( num)
big = max(num)
small = min(num)
print('Sum is:', tot)
print('Average is:',avg)
print('Maximum is:',big)
print('Minimum is:',small)
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).
i am creating a python program, to allow a user to input numbers and find the total, average, highest and lowest of the numbers inputted. my teacher has told me to improve the program by removing the first and last number(which i have now done ) inputted into the list and not to use the min and max functions.I am confused on how doing so.
totalList=[]
TotalNum = int(input("Please enter how many numbers are to be entered:"))
Change=TotalNum
Input=0
Total=0
while TotalNum>0:
TotalNum = TotalNum - 1
Input = int(input("Enter Number: "))
totalList.append(Input)
Total = Total +Input
while 1 == 1:
totalList = totalList[1:-1]
TotalList = totalList
print("Total:" ,Total)
print("Average:",Total/Change)
print("Highest:",max(TotalList))
print("Lowest:",min(TotalList))
When removing the first and last numbers of the list, since lists are zero-indexed in python (meaning the first number is at index 0), you'll want to change totalList = totalList[1:-1] to start from 0, making it totalList = totalList[0:-1].
However, we may want to use those first and last numbers when searching for the maximum and minimum numbers in the list. So, I think what your teacher may have meant was to use the first and last numbers as min and max, and update them as you search through the list.
I will show you finding the minimum, and then using the same idea you can find the maximum.
min_num = TotalList[0]
max_num = TotalList[-1]
for i in TotalList:
if i < min_num:
i = min_num
# print("Highest:",max_num)
print("Lowest:", min_num)
Note: You don't need the infinite while 1 == 1: loop, delete it.
def find_low(nums, index):
lowest = None
lowNum = float("inf")
for num in nums:
if num < lowNum:
lowNum = num
lowest = num
highest = None
highNum = -float("inf")
for num in nums:
if num > highNum:
highNum = num
highest = num
Used = []
newL = []
for num in range(lowest, highest + 1):
if num in nums and not num in Used:
newL.append(num)
Used.append(num)
return newL[index - 1]
numbers = [1,2,3,4,5]
print(find_low(numbers, 1))
#The second paramter, 1, finds the lowest number, not 0
I have a school work that requires finding the average and the min and max, but I have no clue how to find the min and max, the teacher said we cant use the built in min max in python and also no sorting.I already got the average, just need to do the min and max, here is my code.
import random
import math
n = 0
with open("numbers2.txt", 'w') as f:
for x in range(random.randrange(10,20)):
numbers = random.randint(1,50) #random value between 1 to 50
f.write(str(numbers) + "\n")
print(numbers)
f = open("numbers2.txt", 'r')
fr = f.read()
fs = fr.split()
length = len(fs)
sum = 0
for line in fs:
line = line.strip()
number = int(line)
sum += number
print("The average is :" , sum/length)
Add the below lines to your code.
fs = fr.split()
print(min(int(i) for i in fs))
print(max(int(i) for i in fs))
Update:
min_num = int(fs[0]) # Fetches the first item from the list and convert the type to `int` and then it assigns the int value to `min_num` variable.
max_num = int(fs[0]) # Fetches the first item from the list and convert the type to `int` and then it assigns the int value to `max_num` variable.
for number in fs[1:]: # iterate over all the items in the list from second element.
if int(number) > max_num: # it converts the datatype of each element to int and then it check with the `max_num` variable.
max_num = int(number) # If the number is greater than max_num then it assign the number back to the max_num
if int(number) < min_num:
min_num = int(number)
print(max_num)
print(min_num)
If there is a blank line exists inbetween then the above won't work. You need to put the code inside try except block.
try:
min_num = int(fs[0])
max_num = int(fs[0])
for number in fs[1:]:
if int(number) > max_num:
max_num = int(number)
if int(number) < min_num:
min_num = int(number)
except ValueError:
pass
print(max_num)
print(min_num)
Maybe you could find the max and the min by searching into a number list:
numbers=[1,2,6,5,3,6]
max_num=numbers[0]
min_num=numbers[0]
for number in numbers:
if number > max_num:
max_num = number
if number < min_num:
min_num = number
print max_num
print min_num
If you learn how to think about these types of problems, it should all fall into place.
If you have no numbers, what is the min/max?
If you have one number,
what is the min/max?
If you have n numbers, where n is greater than
1, what are the min and max?