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?
Related
What's wrong with this code? Please, do not use built-in functions
Also, could you add condition for int(k) < int(size)
numbers = list()
size = input("Enter the size of an array: ")
for i in range(int(size)):
n = input("number: ")
numbers.append(int(n))
print(numbers)
k = input("k = ")
max = numbers[0]
top = list()
for j in range(int(k)):
for x in numbers:
if x > max:
max = x
top.append(max)
del numbers[numbers.index(max)]
print(top)
Here is the corrected version of your code:
size = int(input("Enter the size of an array: ")) # Ask the user for the amount of values that will be entered
numbers = [int(input("number: ")) for _ in range(size)] # Use a list comprehension to store each input
k = int(input("k = ")) # The number of greatest values to be printed
top = list() # List to store the greatest values
for i in range(0, k): # For every unit in the number of greatest values
max = numbers[0] # Set the maximum to any value, I chose index 0 to avoid IndexError
for j in numbers: # For every number in the list of numbers
if j > max: # If that number is greater than max
max = j # Set max to that number and repeat
top.append(max) # Add the gratest to the top list
numbers.remove(max) # Now remove the greatest so we can proceed to find the next greatest
print(top) # Print our result!
Please note that it is a bad practice to name any of your variables the names of built-in functions, so maybe change your max to mx.
You want to have largest k numbers in the list right?
You could just sort the array and take the last k elements with a backwards iteration. Because after you sort, the largest numbers will be at the end.
The algorithm would be as follows:
0. Take the array through a for loop # You seem to have done this
Sort the array (Python has a native sort function, but let's just define a simple bubble sort function as you said no libraries)
Initialize a list or a k-tuple to hold largest numbers
Starting from index = array.length - 1 iterate to index = array.length - 1 - k
Insert each element to the k-tuple in step 2.
In Python, it would be:
def kLargestNumbers(array,k):
### Considering the input array is taken
bubbleSort(array) ## if native python lib is available change it to sort()
largest_k_numbers = list()
for i in range(len(array)-1, len(array)-1-k,-1):
largest_k_numbers.append(array[i])
return largest_k_numbers
def bubbleSort(array):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] < arr[j+1] :
arr[j], arr[j+1] = arr[j], arr[j+1]
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 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)
I'm currently having an issue with my code. The program works properly but for some reason when I enter all positive numbers I receive an error for the last function. The last function is removing all the negative numbers from the list.
i=0
numList = []
x = int(input("Please enter number from -9999 to end:"))
while x > -9999:
i = i + 1
numList.insert(i,x)
x = int(input("Please enter number from -9999 to end:"))
if x == -9999:
print("The list of numbers entered:",(numList))
newList = numList[:]
secList = numList[:]
def posNumAvg(newList):
for e in newList[:]:
if e < 0:
newList.remove(e)
def negNumAvg(secList):
for y in secList[:]:
if y > 0:
secList.remove(y)
posNumAvg(newList)
negNumAvg(secList)
mydict = {'AvgPositive':(sum(newList)//len(newList)),'AvgNonPos': (sum(secList)//len(secList)),'AvgAllNum':(sum(numList)//len(numList))}
print("The dictionary with averages is:",mydict)
You are trying to compute the average of an empty list, which is not defined (specifically, the list's length is zero so you end up dividing by zero).
You need to decide what you want to do in that case and handle it specifically.
As an aside, you can rewrite
for e in newList[:]:
if e < 0:
newList.remove(e)
as
newList = [e for e in newList if e >= 0]
NOte: Never modify the list when you iterating over it. Let me make some changes to your code
numList = []
while True:
x = int(input("Please enter number from -9999 to end:")
if x == -9999:
print("The list of numbers entered:",(numList))
break
# you don't need i here, used append to insert element at last of list
# insert is used to insert a element at specific position
numList.append(x)
def posNumAvg(gotList):
list_negative = [] # will contain negative number
for e in gotList:
if e < 0:
list_negative.append(e)
return list_negative
def negNumAvg(gotList):
list_positive = [] # will contain positive number
for y in gotList:
if y >= 0:
list_positive.append(y)
return list_positive
list_positive = posNumAvg(numList)
list_negative = negNumAvg(numList)
mydict = {'AvgPositive':(sum(list_positive)//len(list_positive)),'AvgNonPos': (sum(list_negative)//len(list_negative)),'AvgAllNum':(sum(numList)//len(numList))}
print("The dictionary with averages is:",mydict)
you can get positive and negative number from one function: see this code
def neg_poss(gotList):
list_positive = [] # will contain positive number
list_negative = [] # will contain negative number
for y in gotList:
if y >= 0:
list_positive.append(y)
else:list_negative.append(y)
return list_positive,list_negative
list_positive,list_negative = neg_post(numList)