How can I get the average of a range of inputs? - python

I have to create a program that shows the arithmetic mean of a list of variables. There are supposed to be 50 grades.
I'm pretty much stuck. Right now I´ve only got:
for c in range (0,50):
grade = ("What is the grade?")
Also, how could I print the count of grades that are below 50?
Any help is appreciated.

If you don't mind using numpy this is ridiculously easy:
import numpy as np
print np.mean(grades)
Or if you'd rather not import anything,
print float(sum(grades))/len(grades)
To get the number of grades below 50, assuming you have them all in a list, you could do:
grades2 = [x for x in grades if x < 50]
print len(grades2)

Assuming you have a list with all the grades.
avg = sum(gradeList)/len(gradeList)
This is actually faster than numpy.mean().
To find the number of grades less than 50 you can put it in a loop with a conditional statement.
numPoorGrades = 0
for g in grades:
if g < 50:
numPoorGrades += 1
You could also write this a little more compactly using a list comprehension.
numPoorGrades = len([g for g in grades if g < 50])

First of all, assuming grades is a list containing the grades, you would want to iterate over the grades list, and not iterate over range(0,50).
Second, in every iteration you can use a variable to count how many grades you have seen so far, and another variable that sums all the grades so far. Something like that:
num_grades = 0
sum_grades = 0
for grade in grades:
num_grades += 1 # this is the same as writing num_grades = num_grades + 1
sum_grades += sum # same as writing sum_grades = sum_grades + sum
Now all you need to do is to divide sum_grades by num_grades to get the result.
average = float(sum_grade)s / max(num_grades,1)
I used the max function that returns the maximum number between num_grades and 1 - in case the list of grades is empty, num_grades will be 0 and division by 0 is undefined.
I used float to get a fraction.
To count the number of grades lower than 50, you can add another variable num_failed and initialize him to 0 just like num_counts, add an if that check if grade is lower than 50 and if so increase num_failed by 1.

Try the following. Function isNumber tries to convert the input, which is read as a string, to a float, which I believe convers the integer range too and is the floating-point type in Python 3, which is the version I'm using. The try...except block is similar in a way to the try...catch statement found in other programming languages.
#Checks whether the value is a valid number:
def isNumber( value ):
try:
float( value )
return True
except:
return False
#Variables initialization:
numberOfGradesBelow50 = 0
sumOfAllGrades = 0
#Input:
for c in range( 0, 5 ):
currentGradeAsString = input( "What is the grade? " )
while not isNumber( currentGradeAsString ):
currentGradeAsString = input( "Invalid value. What is the grade? " )
currentGradeAsFloat = float( currentGradeAsString )
sumOfAllGrades += currentGradeAsFloat
if currentGradeAsFloat < 50.0:
numberOfGradesBelow50 += 1
#Displays results:
print( "The average is " + str( sumOfAllGrades / 5 ) + "." )
print( "You entered " + str( numberOfGradesBelow50 ) + " grades below 50." )

Related

Which data structure to store inputted numbers?

Which data structure is best for calculating average of inputted numbers ?
I used an array, but it feels clumsy.
Is there a more standard way to do this?
import os
def getGrades():
g = input("How many tests?")
numGrades = int(g)
grades = []*numGrades
for x in range(numGrades):
t = int(input("Enter Grade #" + str(x+1) + ": "))
grades.append(t)
avgGrades(grades)
def avgGrades(a):
total = 0
count = 0
for t in a:
total = total + t
count = count + 1
avg = total / count
print (f"average is: {avg}")
getGrades()
There is a statistics module which you can use:
import statistics
def get_grades_avg():
g = input("How many tests?")
num_grades = int(g)
grades = [] * num_grades
for x in range(num_grades):
grades.append(int(input("Enter Grade #" + str(x + 1) + ": ")))
return statistics.mean(grades)
avg = get_grades_avg()
print('avg: {}'.format(avg))
Using Python list is well. Maybe trying some built-in functions for getting average grade would be more easily.
Assume grades is a list store some grade.
sum(grades) / len(grades)
You can use something like this:
def average_factory():
count_numbers = 0
sum_numbers = 0
def wrapper(number):
nonlocal count_numbers
nonlocal sum_numbers
sum_numbers += number
count_numbers += 1
return sum_numbers / count_numbers
return wrapper
def get_number(message):
str_number = input(message)
try:
return int(str_number)
except (ValueError, TypeError):
print('Invalid number, please try again')
return get_number(message)
def get_average_of_all_tests():
count_tests = get_number('How many tests? ')
get_average = average_factory()
average = 0
for test_number in range(1, count_tests + 1):
number = get_number('Enter Grade #{test_number}: '.format(test_number=test_number))
average = get_average(number)
return average
Yes this solution seems a little complex with average factory. But I think storing all value just for calculating average is not so good idea. Storing only count and sum of grades is better.
If you have any question about solution feel free to ask me about it.
numpy or scipy offer good facilities for this.
store your numbers in an numpy.array([]).
To obtain your mean, numpy.mean(<yourarray>)
Your code would look like:
import numpy
import os
def getGrades():
g = input("How many tests?")
numGrades = int(g)
grades = []*numGrades
for x in range(numGrades):
t = int(input("Enter Grade #" + str(x+1) + ": "))
grades.append(t)
yourArray = numpy.array(grades)
return numpy.mean(yourArray)

Why variables need to be declare but sometimes don't in Python?

I know that Python variables could be used when it first declared like Example 1, but when I try Example 2 without the line total = 0, it will appear NameError: 'name' total is not defined. Why?
Example 1
dmil = float(input("Enter the distance (miles): "))
dis = dmil * 1.61
print("The distance in miles {} is equal to {} in
kilometer.".format(dmil,dis))
Example 2
total = 0 #why I necessarily need this?
for i in range (1,4):
h = float(input("Enter the {} height: ".format(i)))
total = h + total
avg = total/3
print("The average height of the 3 cousins is ",avg)
It really confused me when I type programmes, is there a definition about when should I declare var at first and when should not?
total = h + total is intending to add the value of h to what total currently is.
Without having previously stated what total currently is, there is no value to add h.
In simpler terms, if you remove the total = 0 statement, walk through the code line-by-line and when you reach total = h + total, what should h + total be, it's undefined.
total = 0 is not a declaration per se: it's an initialization. It is needed because when you get to the line
total = h + total
the value of total on the RHS would be unknown. Python tries to look up the value and finds nothing by that name at that point in your program, so it complains.

numerology .. how to shorten code..?

I have written this code for finding the numerological value of a name. Is there any way in which i can shorten the code, or nest one loop inside the other?
alphabets = {"A":1,"I":1,"J":1, "Q":1,"Y":1,"B":2,"K":2,"R":3,"C":3,"G":3,"L":3,"S":3,"D":4,"M":4,"T":4,"H":5,"E":5,"N":5,"X":5,"U":6,"V":6,"W":6,"O":7, "Z":7,"P":8,"F":8}
word =input("your numerology score is :") #since i am using python 3 to code this
def digit_sum(n):
#prepare a list of numbers in n convert to string and reconvert
numbers=[]
for digit in str(n):
numbers.append(int(digit))
# add up the total of numbers
total=0
for number in numbers:
total += number
return total
def numerology(word):
total = 0
for letter in word.upper():
total += alphabets[letter]
total = digit_sum(total)
return total
print (numerology(word))
To understand what is meant by numerological value, please see https://en.wikipedia.org/wiki/Numerology#Latin_alphabet_systems.
alphabets = {"A":1,"I":1,"J":1, "Q":1,"Y":1,"B":2,"K":2,"R":3,"C":3,"G":3,"L":3,"S":3,"D":4,"M":4,"T":4,"H":5,"E":5,"N":5,"X":5,"U":6,"V":6,"W":6,"O":7, "Z":7,"P":8,"F":8}
name = "this is a sample name"
digits = str(sum([alphabets[l] for l in name.upper() if l in alphabets.keys()]))
numerological_value = int(digits) % 9
if numerological_value == 0:
numerological_value = 9
print(numerological_value)
Comprehensions allow you to have a short hand for creating various data types.
In this case you want to build generators.
This is as you don't need to build every number before reducing the list, to a single number.
Wrapping one in sum can allow you to significantly shorten digit_sum. Which can become:
def digit_sum(n):
return sum(int(digit) for digit in str(n))
You can also change numerology to be a little shorter, if you combine the addition and assignment.
def numerology(word):
total = 0
for letter in word.upper():
total = digit_sum(total + alphabets[letter])
return total
If you want, you can use functools.reduce to make this span a total of six lines.
def numerology(word):
return functools.reduce(
lambda a, b: sum(int(digit) for digit in str(a + b)),
(alphabets[letter] for letter in word.upper()),
0
)
One-liner for laughs.
alphabets = {"A":1,"I":1,"J":1, "Q":1,"Y":1,"B":2,"K":2,"R":3,"C":3,"G":3,"L":3,"S":3,"D":4,"M":4,"T":4,"H":5,"E":5,"N":5,"X":5,"U":6,"V":6,"W":6,"O":7, "Z":7,"P":8,"F":8}
print("Your numerology score is "+ str((int(sum([alphabets[l] for l in input("Type your name:").upper() if l in alphabets.keys()])) % 9) or 9))
this one !!!
a= input()
b= 0
c= len(a)
d= {"a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9, "j":10, "k":11, "l":12, "m":13, "n":14, "o":15, "p":16, "q":17, "r":18, "s":19, "t":20, "u":21, "v":22, "w":23, "x":24, "y":25, "z":26, " ":0}
for i in range(c):
b= b+d[a[i]]
print(b)
gematria
i'm sure you can chain the reducer functions a bit better but...
const charMap = {A:1, J:1, S:1, B:2, K:2, T:2, C:3, L:3, U:3, D:4,
M:4, V:4, E:5, N:5, W:5, F:6, O:6, X:6, G:7, P:7, Y:7, H:8,
Q:8, Z:8, I:9, R:9};
let name = prompt ("Type your name in CAPS"); //for example: TOM
let wordScore = Array.from(name).reduce((nameScore, element) => {
let curValue = charMap[element]
return (nameScore + curValue)
},0)
let finalScore = Array.from(String(wordScore), Number).reduce((score, element) => {
return score > 10 ? score + element : score
})
alert(finalScore)

How do I print out the sum of a list given certain constraints

I'm trying to print the sum of a list generated through raw_input.
The numbers in the list must be between 1 and 1000, inclusive. The length of the list must be below 1000.
here is my code thus far:
initial_list = raw_input()
integer= initial_list.split(' ')
if len(integer) <= 1000:
for i in integer:
if i >= 1 and i<=1000:
actual_integer = map( int, integer)
print sum(actual_integer)
This does not print anything. Any suggestions and/or alternatives?
If I understand your objective correctly, you've got all the right ideas, you just need to re-order your logic a little and make sure you are clear in your head about when you're dealing with a list of values and when you're dealing with a single value.
You may wish to consider your variable naming, too, as good names can help you keep track of whether the variable has a type with multiple values or single values. I've updated your code with that in mind
initial_list = raw_input().split() # split(' ') works, but you don't actually need the ' ',
# split() on its own does the same job here
if len(initial_list) <= 1000:
actual_integers = map(int, initial_list) #Moved to here. Note that
#actual_integers is a list
#so for the following comparison
#you just want to look at the max
#and min (individual values)
if min(actual_integers) >= 1 and max(actual_integers) <= 1000:
print sum(actual_integers)
else: #Just added two nice messages to the user if it doesn't print out.
print 'integers must be in range 1-1000 inclusive'
else:
print 'your list must have 1000 integers or fewer'
This code here does what you need but there is no error checking.
initial_list = raw_input() # there should be some prompt text
# no error checking
integer = initial_list.split(' ')
# no output for lists > 1000
if len(integer) <= 1000:
print sum(filter(lambda i: 0 < i <= 1000, map(int, integer)))
The output
$ python test.py
1 2 3 1500 0
6
If I understand your question correctly, this maybe what you're looking for.
This code will prompt the input and append the input to the list lst until lst will have 1000 elements. It will only take an input if the input is a number between 1 and 1000 and it will give you the sum after every input.
lst = []
while len(lst) <= 999:
initial_list = raw_input('Input numbers between 1 and 1000:')
if initial_list.isdigit() and int(initial_list) <= 1000 and int(initial_list) >= 1:
lst.append(int(initial_list))
print 'List:', lst #prints the list
total = sum(lst)
print 'List Sum:', total #prints the list sum
else:
print 'Input must be numbers between 1 and 1000'
Output:
Input numbers between 1 and 1000:12
List: [12]
List Sum: 12
Input numbers between 1 and 1000:45
List: [12, 45]
List Sum: 57
Input numbers between 1 and 1000:156
List: [12, 45, 156]
List Sum: 213
Input numbers between 1 and 1000:256
List: [12, 45, 156, 256]
List Sum: 469
Input numbers between 1 and 1000:

convert following iterative code to recursive Python

6174 is known as Kaprekar's constant[1][2][3] after the Indian mathematician D. R. Kaprekar. This number is notable for the following property:
Take any four-digit number, using at least two different digits. (Leading zeros are allowed.)
Arrange the digits in descending and then in ascending order to get two four-digit numbers, adding leading zeros if necessary.
Subtract the smaller number from the bigger number.
Go back to step 2.
Dattaraya Ramchandra Kaprekar
number="0011"
print(" helo world, lets do this: " , number)
i = 0
while number != "6174":
sortedS = sorted(number)
String[] sortedString = array[4] av strangen number
reversed = sorted(number, reverse=True)
sortedIntMin = int(sortedS[0]+sortedS[1]+sortedS[2]+sortedS[3])
reversedIntMax = int(reversed[0]+reversed[1]+reversed[2]+reversed[3])
i += 1
number = str(reversedIntMax - sortedIntMin)
reversedIntMax - sortedIntMin
print("det behovdes " , i , "iterationer for processen")
This is my unsuccessful attempt
def Kaprekar(number, i):
if number == 6174:
return
elif number != 6174:
sortedString = sorted(number)
reversedString = sorted(number, reverse=True)
sortedIntMin = int(sortedString[0]+sortedString[1]+sortedString[2]+sortedString[3])
reversedIntMax = int(reversedString[0]+reversedString[1]+reversedString[2]+reversedString[3])
num = reversedIntMax - sortedIntMin
print("processen kors", num )
return 1 + Kaprekar(str(num), i)
print(" helo world, lets do this: ")
print("det behovdes " , Kaprekar("1547", 0) , "iterationer for processen")
there are three things that are wrong: -
You don't need i. remove it from function definition.
The variable you are passing is a string and you are comparing it with an integer, convert it to a string while comparing.
You need to return 1 when number='6174', while you are returning None.
Also, it can be done a bit clearer if list is joined after sorted and it can be directly converted to integer, (thanks endzior for the edit)
try this : -
def Kaprekar(number):
if number == '6174':
return 1
elif number != '6174':
sortedString = ''.join(sorted(number))
reversedString = ''.join(sorted(number, reverse=True))
sortedIntMin = int(sortedString)
reversedIntMax = int(reversedString)
num = reversedIntMax - sortedIntMin
print("processen kors", num )
return 1 + Kaprekar(str(num))
print(" helo world, lets do this: ")
print("det behovdes " , Kaprekar("1547") , "iterationer for processen")
number is a string, so in the first 2 if statements :
if number == '6174':
return 1
else:
And as in another answer i variable is not needed here.

Categories

Resources