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
Related
So, the function works with no errors, but the output for min2(2nd lowest value) in the list is incorrect. I cant seem to find the solution.
Python 3.8.6
def max2min2(list1):
max1=list1[0]
min1=list1[0]
max2=None
min2=None
for item in list1:
if item>max1:
max2=max1
max1=item
elif max2==None or max2<item:
max2=item
if item<min1:
min2=min1
min1=item
elif min2==None or min2>item:
min2=item
return max2,min2
list1 = [1,2,3]
max2,min2=max2min2(list1)
print(min2,max2) # 1 2
With the simple input list of [1,2,3] the output of maxmin2 is (1,2), although the expected output is (2,2).
Now if this does not to need to be speed optimized, simple way would be just take a set of the numbers, sort them, and take the second element from each end:
vals = [1,1,3,2,2]
filtered_vals = sorted(set(vals))
and then
# Second lowest
In [37]: filtered_vals[1]
Out[37]: 2
# Second highest
In [36]: filtered_vals[-2]
Out[36]: 2
add some Exception and special case handling if needed.
A simple and readable solution is to sort the list first, then directly index the values you want. I added a unique argument which specifies whether you want to look at the number values (most intuitive) or keep duplicate values in the list (so that the second highest number in [1,2,2] is 2).
def second_lowest_and_highest_using_sort(nums, unique=True):
if unique:
nums = list(set(nums))
if len(nums) == 1:
raise ValueError('Second lowest/highest number is undefined for a list of length 1.')
nums = sorted(nums)
return (nums[1], nums[-2])
A more verbose approach without sorting first:
def second_lowest_and_highest(nums, unique=True):
if unique:
nums = list(set(nums))
if len(nums) == 1:
raise ValueError('Second lowest/highest number is undefined for a list of length 1.')
lowest, highest = float('inf'), float('-inf')
second_lowest, second_highest = None, None
low_delta, high_delta = float('inf'), float('inf')
for num in nums:
low_delta_new = num - lowest
if low_delta_new < 0:
second_lowest = lowest
lowest = num
elif low_delta_new <= low_delta:
second_lowest = num
low_delta = low_delta_new
high_delta_new = num - highest
if high_delta_new > 0:
second_highest = highest
highest = num
elif high_delta_new <= high_delta:
second_highest = num
high_delta = high_delta_new
return (second_lowest, second_highest)
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 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?
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)