I need to create a function that will print the smallest, largest,and average of n amount of numbers inputed by user.
My function, so far, can print the average and largest value of n amount of numbers entered by user but I'm stuck on finding the smallest value.
This is what I have so far:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=0
l_v=0
while counter<n:
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x>l_v:
l_v=x
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
As #Padraic mentioned, the answer that your posted to your question doesn't work for positive values, since your if-statement only checks if the min value is less that 0.
To fix this, you could just assign the first inputted value to all the variables. This way you wouldn't have to use positive and negative inf variables:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=0
f_v = l_v = s_v = total =int (input("enter first value")) #first value
while counter<(n-1):
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x<s_v: #find minimum
s_v=x
elif x>l_v: #find maximum
l_v=x
print ("the smallest value is {0}".format(s_v))
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
Now your code will run without any issues:
how many?5
enter first value-1
enter next number7
enter next number0
enter next number3
enter next number2
the smallest value is -1
the largest value is 7
('the average is ', 2.2)
You could add the items to a list while the user inputs data.
When the user is done, just use min(), max(), and sum() (and maybe len()) on the list.
Keep track of the lowest number also, set the start value to float(inf) for the min and float(-inf) for the max:
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm, counter = 0, 0
while counter < n:
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
counter += 1
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
You can also use a for loop with range:
n = int(input("how many?"))
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm = 0
for i in range(n):
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
Or using a list comp:
n = int(input("how many?"))
if n > 0:
nums = [int(input("enter next number")) for _ in range(n)]
print ("the largest value is {0}".format(min(nums)))
print("the average is ", sum(nums)/ n)
print("the min value is {}".format(min(nums)))
else:
print("What? it is not possible to find the average, sorry ")
sm += x is augmented assignment which the same as doing sm = sm + x.
When verifying user input and casting you should really use a try/except to catch any exceptions:
def get_num():
while True:
try:
n = int(input("enter next number"))
# user entered valid input, return n
return n
except ValueError:
# could not be cast to int, ask again
print("Not an interger")
while True:
try:
n = int(input("how many?"))
break
except ValueError:
print("Not an interger")
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm, counter = 0, 0
while counter < n:
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
counter += 1
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
This is what I ended up doing... Just kind of worked it out myself through trial and error.
I really appreciate the answers! Gives me a different way of looking at the problem!
Answer:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=1
l_v=0
s_v= 0
f_v = int (input("enter first value"))
while counter<n:
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x<f_v:
s_v=x
elif x>l_v:
l_v=x
print ("the smallest value is {0}".format(s_v))
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
Related
This question already has answers here:
Min and Max of a List (without using min/max function)
(11 answers)
Closed 3 months ago.
I am trying to find the maximum and minimum without using the min and max functions. But the maximum is only displaying the first number. Any help?
My code:
count = 0
total = 0.0
num = float(input("Enter the number: "))
maximum = num
minimum = num
while num = 0:
count = count + 1
total = total + num
num = float(input("Enter the number: "))
if num < minimum:
minimum = num
else:
num > maximum
maximum = num
if count == 0:
print("Invalid Entry.")
else:
print("Average Number:", round(total/count, 1))
print("Minimum Number:", minimum)
print("Maximum Number:", maximum)
You did not intended the if condition that is why it is not working
I have modified the code for getting 6 numbers one after one try this
count = 0
total = 0.0
num = float(input("Enter the number: "))
maximum = num
minimum = num
while count < 5:
count = count + 1
total = total + num
num = float(input("Enter the number: "))
if num < minimum:
minimum = num
else:
num > maximum
maximum = num
if count == 0:
print("Invalid Entry.")
else:
print("Average Number:", round(total/count, 1))
print("Minimum Number:", minimum)
print("Maximum Number:", maximum)
count = 0
total = 0.0
num = None
maximum = -float("inf")
minimum = float("inf")
# No need to do the 1st round outside the loop
while num != 0:
num = float(input("Enter the number: "))
count += 1
total += num # += is more concise
# This block needs to be in the while loop
if num < minimum:
minimum = num
if num > maximum: # elif is fine if you initialize minimum and maximumwith the 1st value of num
maximum = num
if count == 0:
print("Invalid Entry.")
else:
print("Average Number:", round(total/count, 1))
print("Minimum Number:", minimum)
print("Maximum Number:", maximum)
I'm not quite sure what you are trying to accomplish here. If your first input is anything other than 0, you will set the variables maximum and minimum to that non-zero number. You will skip the while loop and if statement. If you don't get an error, it will probably just spit out the maximum and minimum being the same number. Can you provide more detail as to what you are trying to do?
you need to check the minimum and maximum for every number. so this part must be in while loop:
if num < minimum:
minimum = num
if num > maximum
maximum = num
also while condition doesn't seem right. you are assigning 0 to num every time. you probably meant num!=0. in this case when user inputs 0 the program terminates.
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).
This is just an introductory class code, and i'm wondering how to find the max of all the next_value variable and compare it to the first_value to print the maximum. My if statement is close but I'm not sure how to fix it
maximum = 0.0
value = int(input("Enter the number of values to process: "))
first_value = float(input("First value: "))
next_value_total = 0
for i in range(1, value):
next_value = float(input("Next value: "))
next_value_total += next_value
if first_value <= next_value:
maximum = next_value
elif first_value > next_value:
maximum = first_value
total = next_value_total + first_value
print("The total is {:.1f}".format(total))
print("The maximum is {:.1f}".format(maximum))
I will try to keep my answer as clean and simple as possible:
value = int(input("Enter the number of values to process: "))
first_value = float(input("First value: "))
total = first_value
maximum = first_value
for i in range(1, value):
next_value = float(input("Next value: "))
total += next_value
if maximum <= next_value:
maximum = next_value
print("The total is {:.1f}".format(total))
print("The maximum is {:.1f}".format(maximum))
I would just put the values in a list and get the sum and max later, like so:
value = int(input("Enter the number of values to process: "))
values = []
for i in range(value):
next_value = float(input("Next value: "))
values.append(next_value)
print("The total is {:.1f}".format(sum(values)))
print("The maximum is {:.1f}".format(max(values)))
However, if you want to keep the same structure:
maximum = 0.0
value = int(input("Enter the number of values to process: "))
first_value = float(input("First value: "))
next_value_total = 0
maximum = first_value # Note: initialize the maximum here
for i in range(1, value):
next_value = float(input("Next value: "))
next_value_total += next_value
if next_value > maximum:
maximum = next_value
total = next_value_total + first_value
print("The total is {:.1f}".format(total))
print("The maximum is {:.1f}".format(maximum))
You can also replace if next_value > maximum: maximum = next_value with just maximum = max(maximum, next_value).
If you used a list instead you could use sum() and max() respectively:
num_values = int(input("Enter the number of values to process: "))
values = []
for i in range(1, num_values + 1):
value = float(input("Please enter value %d: " % i))
values.append(value)
print("The total is {:.1f}".format(sum(values)))
print("The maximum is {:.1f}".format(max(values)))
Example Usage:
Enter the number of values to process: 3
Please enter value 1: 4.0
Please enter value 2: 5.6
Please enter value 3: 7.2324234
The total is 16.8
The maximum is 7.2
Try it here!
An Emirp is a prime number whose reversal is also a prime. For
example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps.
Write a program that prints out the first N emirps, five on each line.
Calculate the first N emirp (prime, spelled backwards) numbers, where
N is a positive number that the user provides as input.
Implementation Details
You are required to make use of 2 functions (which you must write).
isPrime(value) # Returns true if value is a prime number. reverse
(value) # Returns the reverse of the value (i.e. if value is 35,
returns 53). You should use these functions in conjunction with logic
in your main part of the program, to perform the computation of N
emirps and print them out according to the screenshot below.
The general outline for your program would be as follows:
Step 1: Ask user for positive number (input validation) Step 2:
Initialize a variable Test to 2 Step 3: While # emirps found is less
than the input:
Call isPrime with Test, and call it again with reverse(Test).
If both are prime, print and increment number of emirps found. Test++ Hint - to reverse the number, turn it into a string and then
reverse the string. Then turn it back into an int!
MY CODE:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
count = 0
while(test < value):
if( value % test == 0):
count+=count
test+=test
if(count == 0):
return 1
else:
return 0
def reverse(value):
reverse = 0
while(value > 0):
reverse = reverse * 10 + (value % 10)
value = value / 10
return reverse
n = float(input("Please enter a positive number: "))
while(count < n):
i+=i;
if(isPrime(i)):
if(isPrime(reverse(i))):
print("i" + "\n")
count+=count
if((count % (5)) == 0 ):
print("\n")
where are the mistakes?
UPDATED CODE BUT STILL NOT RUNNING:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
def reverse(value):
return int(str(value)[::-1])
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
There are a lot of issues with your code. I altered the function isPrime. There is among other no need for count here and if you want to increment test by 1 every loop use test +=1:
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
return 1
There is an easy way to reverse digits by making value a string in reversed order and to convert this into an integer:
def reverse(value):
return int(str(value)[::-1])
You among other have to assign the input to i. n in your code is a constant 5. You have to increment i by one in any condition and increment the count by one if i is an emirp only:
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
def emrip_no(num):
i=0
j=0
for i in range(1,num+1):
a=0
for j in range(1,i+1):
if(i%j==0):
a+=1
if(a==2):
print("Number is a prime number")
k=0
l=0
rv=0
while(num!=0):
r=num%10
rv=(rv*10)+r
num=num//10
print("It's reverse is: ",rv)
for k in range(1,rv+1):
b=0
for l in range(1,k+1):
if(k%l==0):
b+=1
if(b==2):
print("It's reverse is also a prime number")
else:
print("It's reverse is not a prime number")
n=int(input("Enter a number: "))
emrip_no(n)
Basically, I need to take input unless a negative number is entered and then print the sum of scores along with some other statistics and all. Question has now been resolved.
nums=[]
total= 0
count= 0
while x >= 0:
x = int(input("Enter a number (enter -1 to terminate): "))
if x <= 100:
total = total + x
count+=1
nums.append(x)
if x>100:
print("Invalid entry.")
x = int(input("Enter a number (enter -1 to terminate): "))
print(nums)
print("Number of scores: ", len(nums))
It looks like the 2nd input should be at the end of the while loop
while x >= 0:
if x <= 100:
total = total + x
count+=1
nums.append(x)
if x>100:
print("Invalid entry.")
x = int(input("Enter a number (enter -1 to terminate): "))
That gives the first value a chance to get processed, and means that the final -1 won't be appended