I want to write a program that asks a user how many numbers they wish to process, then ask for that many numbers. Then it will find the total and the maximum of the numbers processed. Example output:
Enter the number of values to process: 5
First value: 3
Next value: 9.2
Next value: -2.5
Next value: 0.25
Next value: 6
The total is 15.95
The maximum is 9.20
One thing I am lost on is that if if I have the code for num in (1, 3)
and num gets assigned multiple values, how do I extract both those values?
Set example_list = list(), then do a for loop where each time you ask for input and add the value to the list via example_list.append(input_response).
Extract the values back out using the same for loop to cycle through the list.
example_list = list()
total = 0
max_value = 0
for stored_number in example_list:
# Ask for input and store in input_response variable
example_list.append(input_response)
# Here is where you could add the values to a counter variable,
# as well as check whether they are the maximum
total += stored_number
if stored_number > max:
max_value = stored_number
# Display results
For what you want, you could also just use the built-in functions max and sum:
max_value = max(example_list)
total = sum(example_list)
# ask how many
quantity = int(raw_input("Enter the number of values to process: "))
# ask for numbers and store them in list
numbers = [float(raw_input("Enter number " + str(each) + " : ")) for each in range(0,quantity)]
#print result
print "The total is " + str(sum(numbers)) + " and the maximum is " + str(max(numbers))
Related
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 5 months ago.
Suppose that you entered 3 5 2 5 5 5 0 and input always ends with the number 0, the program finds that the largest number is 5 and the occurrence count for 5 is 4.
Input: i enter 3 5 2 5 5 5 0 and it shows nothing as result
Code:
currentnum = int(input('Enter Numbers List, to end enter 0: '))
maxx = 1
while currentnum > 0:
if currentnum > maxx:
max = currentnum
count = 1
elif currentnum == maxx:
count += 1
print('The Largest number is:', int(maxx), 'and count is', int(count))
Python doesn't have thunks.
currentnum = int(input('Enter Numbers List, to end enter 0: '))
This sets currentnum to the result of running int on the value returned by the input call. From this point on, currentnum is an int.
while currentnum > 0:
if currentnum > maxx:
max = currentnum
count = 1
elif currentnum == maxx:
count += 1
In this loop, you never take any more input, or reassign currentnum, so the loop will carry on forever, checking the same number over and over again.
If you assigned to currentnum at the end of your loop, you could take input in one-number-per-line. However, you want a space-separated input format, which can be better handled by iterating over the input:
numbers = [int(n) for n in input('Enter numbers list: ').split()]
max_num = max(numbers)
print(f"The largest number is {max_num} (occurs {numbers.count(max_num)} times)")
(Adding the 0-termination support is left as an exercise for the reader.)
Another, similar solution:
from collections import Counter
counts = Counter(map(int, input('Enter numbers list: ')))
max_num = max(counts, key=counts.get)
print(f"The largest number is {max_num} (occurs {counts[max_num]} times)")
I recommend trying your approach again, but using a for loop instead of a while loop.
Okay. So one of the most important things to do while programming is to think about the logic and dry run your code on paper before running it on the IDE. It gives you a clear understanding of what is exactly happening and what values variables hold after the execution of each line.
The main problem with your code is at the input stage. When you enter a value larger than 0, the loop starts and never ends. To make you understand the logic clearly, I am posting a solution without using any built-in methods. Let me know if you face any issue
nums = []
currentnum = int(input('Enter Numbers List, to end enter 0: '))
while currentnum > 0:
nums.append(currentnum)
currentnum = int(input('Enter Numbers List, to end enter 0: '))
max = 1
count = 0
for num in nums:
if num > max:
max = num
count = 1
elif num == max:
count += 1
print('The Largest number is:', max, 'and count is', count)
Now this can not be the efficient solution but try to understand the flow of a program. We create a list nums where we store all the input numbers and then we run the loop on it to find the max value and its count.
Best of luck :)
Use the standard library instead. takewhile will find the "0" end sentinel and Counter will count the values found before that. Sort the counter and you'll find the largest member and its count.
import collections
import itertools
test = "3 5 2 5 5 5 0 other things"
counts = collections.Counter((int(a) for a in
itertools.takewhile(lambda x: x != "0", test.split())))
maxval = sorted(counts)[-1]
maxcount = counts[maxval]
print(maxval, maxcount)
to make sure that operation stops at '0', regex is used.
counting is done by iterating on a set from the input using a dict comprehension.
import re
inp = "3 5 2 5 5 5 0 other things"
inp = ''.join(re.findall(r'^[\d\s]+', inp)).split()
pairs = {num:inp.count(num) for num in set(inp)}
print(f"{max(pairs.items())}")
Why not do it this way?
print(f"{max(lst)} appears {lst.count(max(lst))} times")
So my task is simple: I am to make two functions,
one which takes input from a user as a list of integers. (User enters how many entries, then begins entering them individually)
second function reads that list and returns how many times a chosen value was found in that list.
For some reason when combining these functions, the count does not stay at 0 and count whenever x is seen in the list; it just jumps to whatever the initial entry count was.
code is as follows:
def get_int_list_from_user():
list1 = []
numNums = int(input("Enter number count: "))
for x in range(numNums):
nextval = int(input("Enter a whole number: "))
list1.append(nextval)
return list1
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for target_val in int_list:
count += 1
print("Target counted ", count, "time(s)")
return count
Over here is where I've tried different ways of calling the functions, but each time just ends up with the same result.
list1 = my_functions.get_int_list_from_user()
count = my_functions.count_target_in_list(int_list=list1)
I also tried this:
my_functions.count_target_in_list(int_list=my_functions.get_int_list_from_user())
This statement does not do what you think it does:
for target_val in int_list:
That essentially erases the original value passed into the function, and instead runs through the whole list, one element at a time. So, count will always be equal to the length of the list. You wanted:
for val in int_list:
if val == target_val:
count += 1
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for target_val in int_list:
count += 1
print("Target counted ", count, "time(s)")
return count
instead, using this logic, you need to compare the loop values with the target value. in the code above the target value will be overridden by the iteration of the loop.
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for value in int_list:
if target_val == value :
count += 1
print("Target counted ", count, "time(s)")
return count
This question already has answers here:
Minimum, Maximum and Average in a single iteration
(2 answers)
Closed 12 months ago.
I need to write a program where you can only input 10 numbers, and from those 10 numbers it then will print the minimum number out of the 10 inputted numbers and then print average of all the numbers.
Instructions: Write a program that reads 10 integers and displays its
minimum and average.
What I have so far:
c=1
min=int(input("a number>1: "))
while c<10:
v=int(input("a number>2: "))
print (min)
print (v)
if min>v:
min=v
c += 1
d = sum(int(min+v)
print (d)
print ("Minimum number: " + str(min))
Or this:
a = 0
b = int(input("a number>1: "))
while a < 10:
c = int(input("a number>1: "))
d = int(input("a number>1: "))
e = int(input("a number>1: "))
f = int(input("a number>1: "))
g = int(input("a number>1: "))
h = int(input("a number>1: "))
i = int(input("a number>1: "))
j = int(input("a number>1: "))
k = int(input("a number>1: "))
a += 1
if (b>c and b<d and b<e and b<f and b<g and b<h and b<i and b<j and b<k):
print ("Minimum is" + str (b))
# c =
# a += 1
#print(min)
If you find yourself writing really annoying repetitive code like:
if (b>c and b<d and b<e and b<f and b<g and b<h and b<i and b<j and b<k):
you should step back and ask yourself if there is a better way. Sometimes you have to write annoying code, but for something like finding a minimum value or sum…well, you have to know python programmers aren't doing this every time…there's got to be a better way.
So if you have a list of numbers like [1, 2, 3] rather than bunch of variables like a = 1; b = 2 you can simply use min(list) to find the smallest. So instead of defining all these variables use a data structure like a list and for each input append() to the list. In the end you'll have a tidy list of 10 numbers to work with and a large set of tools python gives you like len(), min(), sum() etc.
numbers = [] # put you numbers in a list
while len(numbers) < 10:
i = int(input("a number>1: "))
numbers.append(i)
print("Numbers: ", numbers)
print ("Minimum is: %d " % min(numbers)) # then you can call min and sum
print ("Sum is: %d" % sum(numbers))
Of course there are a lot of ways to do this.
From here I assume you could figure out the average.
You can create two variables; one that will hold the sum of the numbers (in which at the end, you just divide that number by 10) and another that will hold the minimum value.
We will set the min and sum to the first number then create a loop to obtain the next 9 numbers using the function range(start, end) which would count from start to end-1 (whatever value you pass as the second parameter, will not be included in the loop).
Then in the loop, you can allow the user to enter the number in which you will: add it to the sum variable and set it has the minimum if it is less than the current value of the min variable.
min = int(input('Enter a number > 1: '))
sum = min
for i in range(0, 9):
number = int(input('Enter a number > 1: '))
sum += number
if number < min:
min = number
average = sum / 10
print('Minimum:', str(min))
print('Average:', str(average))
I wrote this program to find sum and average, and got "Variable not defined" error. Can anyone solve it?
a=int(input("Total Numbers you will input for calculation: "))
Sum = 0 # Running Totalis b
for x in range (a-1):
c=int(input("Enter your input number {0}.".format(x+1)) # c is for next number
Sum = Sum + c
Total=b/10 # For Total
print("Total sum of the number you entered is {0} and their average is {1},".format(b,d))
In your code that prints out the sum and average, you refer to the variables b and d, neither of which actually exist. That is the cause of your immediate problem, the "Variable not defined" issue.
The sum of the numbers is stored in the Sum variable which you should use rather than b. The average is not calculated anywhere unless your calculation for Total is meant to do this but, if that's the case, you should choose a more appropriate name and calculate it correctly (dividing by a rather than by ten).
On top of that, your use of range is incorrect. You should be using a rather than a-1, since range(n) already gives you the values 0 .. n-1, a toal of n different items.
So, with all that in mind, and using some better (self-documenting) variable names (and catching the problem of entering a non-positive count), you could opt for something like:
count = int(input("Total Numbers you will input for calculation: "))
if count > 0:
sumOfNums = 0
for x in range(count):
num = int(input("Enter your input number {0}.".format(x+1))
sumOfNums += num
avgOfNums = sumOfNums / count
print("Total sum of the number you entered is {0} and their average is {1},".format(sumOfNums, avgOfNums))
Have a look at below:
a=int(input("Total Numbers you will input for calculation: "))
sum = 0 # Running Totalis b
for x in range (a):
c=int(input("Enter your input number {0}.".format(x+1)))
sum +=c
avg=sum / a # For Total
print("Total sum of the number you entered is {0} and their average is {1},".format(sum,avg))
I would like for this to stop at 20. By which I mean, when it asks you to input another number it should stop after the 20th time.
Currently I have an accumulating counter that when it reaches 20 it prints the "Enter one more number". It does this at the 20th time, but afterwards it keeps going with asking you to input more numbers. I would like it to stop asking for input after the 20th time.
Thanks. This is apart of a larger homework problem.
def main ():
print()
print("Finds the lowest, highest, average, and total to 20 numbers.")
print()
number, count, numberlist = getnumber()
print("Stop.")
def getnumber ():
count = 0
numberlist = []
for count in range(20):
count = count + 1
number = float(input("Please enter another number : "))
numberlist.append(number)
while count != 20:
number = float(input("Please enter one more number : "))
numberlist.append(number)
return number, count
main()
You could do this as follows:
def get_numbers(count=20):
numbers = []
numbers.append(float(input("Please enter a number : "))) # first
for _ in range(count-2):
numbers.append(float(input("Please enter another number : "))) # next 18
numbers.append(float(input("Please enter one more number : "))) # last
return numbers
Note that with a for loop you don't need to manually increment the loop counter. Also, there is no need to return count; you already know how many there will be.
First of all, note that you are not changing value of count inside while loop - that is why it never stops. After for is executed count is exactly 19 and never reaches 20 after that.
Second of all, you do not need while at all - for loop will work for 20 iterations and stop
def getnumber ():
count = 0
numberlist = []
for count in range(20):
count = count + 1
number = float(input("Please enter another number : "))
numberlist.append(number)
return number, count, numberlist
Here is another option (your approach extended)
limit = 5
def main ():
print("Finds the lowest, highest, average, and total to {} numbers.".format(limit))
numbs = getnumber()
print(numbs)
print("lowest:", min(numbs))
print("highest:", max(numbs))
print("avg:", sum(numbs)/len(numbs))
print("total:", sum(numbs))
print("Stop.")
def getnumber ():
numberlist = []
for count in range(limit):
if count == limit-1:
number = float(input("Please enter one more number : "))
numberlist.append(number)
else:
number = float(input("Please enter another number : "))
numberlist.append(number)
return numberlist
main()
Output
Finds the lowest, highest, average, and total to 5 numbers.
[6.0, 3.0, 8.0, 4.0, 2.0]
('lowest:', 2.0)
('highest:', 8.0)
('avg:', 4.6)
('total:', 23.0)
Stop.
There are some problems with the code you posted. First of you should indent the return statement so it is part of getnumber. Secondly you return two values but unpack three values in main. If I fix those two things the code works. The reason that count is 20 after the for loop is that you declare count outside the loop, so on each iteration count will be set to the next integer and then incremented once more by
count = count + 1
If you did not have the extra increment inside the loop, count would be 19 after the for loop terminates because range(N) does not include N.
And you can rewrite the code with a list comprehension to get a very concise version
def getnumber(prompt, n):
return [float(input(prompt)) for _ in range(n)]
This will give you a list of the numbers.