calculate average grade which accept string - python-3.x

In python how to get the average, which accepts as a string input parameter and returns the average of the four scores within the string as a float.
Expected output:
input output
0, 50.4, 80.3, 95.9 = 56.5
99.9, 91.3, 99.2, 98.0 = 97.1
My output right now is
input output
0, 50.4, 80.3, 95.9 = 0
99.9, 91.3, 99.2, 98.0 = 99.9
please help me to get the expected output
grade1 = 0,50.4,80.3,95.9
grade2 = 99.9,91.3,99.2,98.0
gradeArr = [grade1, grade2]
def score_average (i):
n = len (i)
total = 0
for j in i:
total = total + j
average = total
return float (average)
print("input output")
for i in gradeArr:
average = score_averages(i)
length= len(str(i))
print(str(i)[1:length -1] + " = " + str(average))

The output is 0 and 99.9 because you are returning the first number in the list in the score_average function, since the return statement is indented into the for loop, so only the first number is added to the total and then is returned. Also, if you indent it correctly, the return statement is just returning the sum of the list, so you need to return this sum divided by n to get the average. The code should look like this:
grade1 = 0,50.4,80.3,95.9
grade2 = 99.9,91.3,99.2,98.0
gradeArr = [grade1, grade2]
def score_average (i):
n = len (i)
total = 0
for j in i:
total = total + j
average = total / n # Divide the total by n
return average
print("input output")
for i in gradeArr:
average = score_average(i)
length= len(str(i))
print(str(i)[1:length -1] + " = " + str(average))

Related

Code fails on Test case. (InterQuartile Range)

This is a challenge from 10 Day statistics on Hackerrank.(https://www.hackerrank.com/challenges/s10-interquartile-range/problem?h_r=next-challenge&h_v=zen)
Task :
Task
The interquartile range of an array is the difference between its first (Q1) and third (Q3) quartiles (i.e., Q3 - Q1).
Given an array,X, of n integers and an array, F, representing the respective frequencies of X's elements, construct a data set, S, where each xi occurs at frequency fi. Then calculate and print S's interquartile range, rounded to a scale of 1 decimal place (i.e., 12.3 format).
Following is my code.
n = int(input())
x = list(map(int, input().split()))
f = list(map(int, input().split()))
s = []
for i in range(len(x)):
j = f[i]
for k in range(j):
s.append(x[i])
n = len(s)
s.sort()
if n%2 == 0:
Q21 = s[n//2]
Q22 = s[n//2 - 1]
Q2 = (Q21 + Q22) / 2
else:
Q2 = s[n//2]
LH = s[:n//2]
if n%2==0:
UH = s[n//2:]
else:
UH = s[n//2+1:]
Q1_len = len(LH)
Q3_len = len(UH)
if Q1_len%2 == 0:
Q11 = LH[Q1_len//2]
Q12 = LH[Q1_len//2 - 1]
Q1 = (Q11 + Q12) / 2
else:
Q1 = LH[Q1_len//2]
if Q3_len%2 == 0:
Q31 = UH[Q3_len//2]
Q32 = UH[Q3_len//2 - 1]
Q3 = (Q31 + Q32) / 2
else:
Q3 = UH[Q3_len//2]
print(round(Q3 - Q1,1))
# print(int(Q2))
# print(int(Q3))
Here is the test case: with std input.
5
10 40 30 50 20
1 2 3 4 5
Expected output:
30.0
My code output:
30.0 # I get this output on my code editor but not on Hackerrank
Can someone help me on this where I am wrong ?
I get the output what is expected but it shows as failed.
print(float(Q3 - Q1))
Basically is the answer.

Recursion function inn python

I am trying to understand the recursion function. I would like to know how that answer is coming with steps
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
results are this just want to know how its coming
1
3
6
10
15
21
The function computes the sum of all numbers between 0 and n, and prints intermediate results. The first 1 is 0+1, the 3 = 0+1+2, 6 = 0+1+2+3, 10 = 0+1+2+3+4, ...
To understand a recursive function, you need 2 points : how is the recursive call done, and when does the recursion stop.
The recursive call is given by result = k+tri_recursion(k-1)and the recursion stops when k <= 0and returns 0. So if we assume only positive numbers, we could describe tri_recursion so:
tri_recursion(k) = k + tri_recursion(k-1) if k > 0
tri_recursion(0) = 0
So tri_recursion(k) = k + tri_recursion(k-1) = k + (k-1) + tri_recursion(k-2) = k + (k-1) + (k-2) + tri_recursion(k-3) ... = k + (k-1) + (k-2) + ... + 0
So tri_recursion(k) is the sum of all numbers between 0 and k.
Note that the sum on all numbers between 0 and k equals k*(k+1) / 2 so tri_recursion(6) = 6 * 7 / 2 = 21

I want to add two extremely large numbers in python which even bignum can't handle

I am new in python,I want to add two extremely large numbers in python which even bignum can't handle. I can take these two numbers as a string and then can calculate from the end and as like we used to do in old school addition process. we can take the carriage and add it to the next numbers and so on.
Please assist.
The question seemed interesting enough for a Christmas Day coding snack.
Here's my implementation using many of the builtins in Python.
reversed is used to iterate over the digit sequences from right to left, i.e. like we would when computing on paper
zip_longest "fills" in the sequences' ends with zeroes (as we would ignore digits on paper)
divmod computes the carried-forward value and the current digit in a single call.
The result is reversed, so it's once more reversed to be least-significant-digit-last, and stray zeroes on the left are removed using lstrip.
It does not handle negative numbers, though.
from itertools import zip_longest
def add(a, b):
out = []
a = [int(c) for c in str(a)]
b = [int(c) for c in str(b)]
carry = 0
for ca, cb in zip_longest(reversed(a), reversed(b), fillvalue=0):
carry, digit = divmod(ca + cb + carry, 10)
out.append(str(digit))
return "".join(reversed(out)).lstrip("0")
a = 9999 ** 29
b = 3725241 ** 9
assert add(a, b) == str(a + b)
I achieved that after 3 hours of work. :)
def add_func(num1,num2):
res_list = []
number1 = str(num1)
number2 = str(num2)
length1 = len(str(number1))
length2 = len(str(number2))
if(length1 > length2):
while(length1 > length2):
number2 = '0' + number2
length2 += 1
if(length2 > length1):
while(length2 > length1):
number1 = '0' + number1
length1 += 1
i = max(length1,length2)
carry = 0
while(i > 0):
if(int(number1[i-1]) + int(number2[i-1]) + carry > 9):
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list.insert(0,(result[-1]))
carry = 1
if(i==1):
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list[0]= result
elif(int(number1[i-1]) + int(number2[i-1]) > 9):
result = str(int(number1[i-1]) + int(number2[i-1]))
res_list.insert(0,(result[-1]))
carry = 1
else:
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list.insert(0,(result[-1]))
carry = 0
i -=1
final_output = ('').join(res_list)
return final_output
print(add_func(9999**29,3725241**9))

Time and memory limit exceeded - Python3 - Number Theory

I am trying to find the sum of the multiples of 3 or 5 of all the numbers upto N.
This is a practise question on HackerEarth. I was able to pass all the test cases except 1. I get a time and memory exceeded error. I looked up the documentation and learnt that int can handle large numbers and the type bignum was removed.
I am still learning python and would appreciate any constructive feedback.
Could you please point me in the right direction so I can optimise the code myself?
test_cases = int(input())
for i in range(test_cases):
user_input = int(input())
sum = 0
for j in range (0, user_input):
if j % 3 == 0:
sum = sum + j
elif j % 5 == 0:
sum = sum + j
print(sum)
In such problems, try to use some math to find a direct solution rather than brute-forcing it.
You can calculate the number of multiples of k less than n, and calculate the sum of the multiples.
For example, with k=3 and n=13, you have 13 // 3 = 4 multiples.
The sum of these 4 multiples of 3 is 3*1 + 3*2 + 3*3 + 3*4 = 3 * (1+2+3+4)
Then, use the relation: 1+2+....+n = n*(n+1)/2
To sum the multiples of 3 and 5, you can sum the multiples of 3, add the sum of the multiples of 5, and subtract the ones you counted twice: the multiples of 15.
So, you could do it like this:
def sum_of_multiples_of(k, n):
"""
Returns the sum of the multiples of k under n
"""
# number of multiples of k between 1 and n
m = n // k
return k * m * (m+1) // 2
def sum_under(n):
return (sum_of_multiples_of(3, n)
+ sum_of_multiples_of(5, n)
- sum_of_multiples_of(15, n))
# 3+5+6+9+10 = 33
print(sum_under(10))
# 33
# 3+5+6+9+10+12+15+18 = 78
print(sum_under(19))
# 78

Python logic isn't yielding the correct answer and I'm having difficulty with developing the context

Values including height = 10, number = 2, and bounciness = 6 should come to 25.6 feet, but I'm getting 23.2 feet. Can someone help me understand where my logic is screwed up please?
import math
# User inputs are set up
height = int(input("Enter the height of the ball: "))
number = int(input("Enter the number of bounces of the ball: "))
bounciness = int(input("Enter the height for each successive bounce: "))
count = 0
# Calculation
for count in range(bounciness):
count = (height * bounciness)/100
distance = height + count
bounceSum = number * bounciness
total = count + distance + bounceSum
# Results
print("The ball has traveled a total distance of", total, "feet.")
If you look at the calculation in the for loop, this is what happens in the first iterations (and ones after that too):-
count = 10*6/100 = 0.6
distance = 10 + 0.6 = 10.6 (count is 0.6 here because of the line above)
bounceSum = 2*12 = 12
total = 0.6 + 10.6 + 12 = 23.2
The problem with the logic in your code is the variable count. There are 3 different definitions of it and they keep overwriting the other:
count = 0 above the for loop
count which ranges from 0 to bounciness-1
count = (height*bounciness)/100
I think I fixed it...
import math
# User inputs are set up
height = int(input("Hello, please enter the height of the ball: "))
number = int(input("Next, enter the number of bounces of the ball: "))
bounciness = int(input("Now enter the height for each successive bounce: "))
index = 0
# Calculation
for index in range(bounciness):
index = bounciness * 0.6
distance = height + (bounciness * number)
total = index + distance
# Results
print("The ball has traveled a total distance of", total, "feet.")
print("Good bye")

Resources