Student Info Program (adding onto) How to add two methods - python

We are adding onto code that we completed last week. Our instructor gave us direction (posted at bottom) and to me and my partner, they are not very descriptive. I'm not asking for an answer to the code, but just a different and more informative description or hints at how to start these additions.
import math
class Student:
def __init__(self, name, student_id, intended_major, grade):
self.name = name
self.student_id = student_id
self.intended_major = intended_major
self.grade = grade
self._exams = []
self._quizzes = []
self._projects = []
def get_name(self):
return self.name
def get_student_id(self):
return self.student_id
def get_major(self):
return self.intended_major
def set_quizzes(self, _quizzes):
self._quizzes = _quizzes[:]
def set_exams(self, _exams):
self._exams = _exams[:]
def set_projects(self, _projects):
self._projects = _projects[:]
def get_exams_mean(self):
return float((sum(self._exams)) / max(len(self._exams), 1))
def get_exams_median(self):
if len(self._exams) == 0:
return 0
lst = sorted(self._exams)
if len(lst) % 2 == 0:
n1 = lst[int(len(lst)/2)]
n2 = lst[int(len(lst)/2)-1]
return ( n1 + n2 ) / 2
else:
return lst[int(len(lst) / 2)]
def get_exams_std_dev(self):
if len(self._exams) == 0:
return 0
mean = sum(self._exams) / len(self._exams)
total = 0
for i in self._exams:
total += (i - mean)**2
return math.sqrt(total/len(self._exams))
def get_quizzes_mean(self):
return float((sum(self._quizzes)) / max(len(self._quizzes), 1))
def get_quizzes_median(self):
if len(self._quizzes) == 0:
return 0
lst = sorted(self._quizzes)
if len(lst) % 2 == 0:
n1 = lst[int(len(lst) / 2)]
n2 = lst[int(len(lst) / 2) -1]
return ( n1 + n2 ) / 2
else:
return lst[int(len(lst) / 2)]
def get_quizzes_std_dev(self):
if len(self._quizzes) == 0:
return 0
mean = sum(self._quizzes) / len(self._quizzes)
total = 0
for i in self._quizzes:
total += (i - mean) ** 2
return math.sqrt(total / len(self._quizzes))
def get_projects_mean(self):
return float((sum(self._projects)) / max(len(self._projects), 1))
def get_projects_median(self):
if len(self._projects) == 0:
return 0
lst = sorted(self._projects)
if len(lst) % 2 == 0:
n1 = lst[int(len(lst)/2)]
n2 = lst[int(len(lst)/2)-1]
return ( n1 + n2 ) / 2
else:
return lst[int(len(lst) / 2)]
def get_projects_std_dev(self):
if len(self._projects) == 0:
return 0
mean = sum(self._projects)/len(self._projects)
total = 0
for i in self._projects:
total += (i - mean)**2
return math.sqrt(total/len(self._projects))
def set_grade_calculation_type(self):
if True:
return 0
else:
pass
def set_quiz(self, grade, number):
pass
Add stubs for the following instance methods to your Student class:
set_grade_calculation_type:
The method takes a Boolean argument: True calculates missing grades as zero;
False skips missing grades in calculations
You will need to store this value in your class
Default to True if this method is not called
set_quiz:
takes two arguments: grade and number, which identifies the quiz
If the quiz list has less than number elements, then add missing quizzes as
None
Since this is computer science, we will start with quiz 0.
For example, let's say the student has two quiz grades in list for quizzes 0
and 1 =[90, 78], and we call student.set_quiz(89,4). We are missing quizzes 2
and 3, so our updated list will be [90, 78, None, None, 89]. In the future if
we call student.set_quiz(93,2) we would have [90, 78, 93, None, 89].
set_exam: analogous to set_quiz
set_project: analogous to set_quiz

Related

I'm trying to find sum of first n palindromes using python

Here's my code:
def ispalindrome(p):
temp = p
rev = 0
while temp != 0:
rev = (rev * 10) + (temp % 10)
temp = temp // 10
if num == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (palindrome(i) == True):
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
I believe my ispalindrome() function works. I'm trying to figure out what's wrong inside my while loop.
here's my output so far:
n = 1 answer = 1,
n = 2 answer = 22,
n = 3 answer = 333 ...
I also think the runtime on this really sucks
Please help
i belive the problem is with your ispalindrom functon it returns 200 as palindrome number
def ispalindrome(p):
rev = int(str(p)[::-1])
if p == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (ispalindrome(i) == True):
print(i)
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
def is_palindrome(number):
return str(number) == str(number)[::-1]
num = int(input("Enter a number: "))
palindromes = [i for i in range(1, num) if is_palindrome(i)]
print(f"Sum of the {len(palindromes)} palindromes in range {num} is {sum(palindromes)}")

how to complete id numbers generator code in python

Hi there I have a mission: to implement 10 ID numbers according to the exceptions and conditions in the code
i want that the output will be
123456782
123456790
123456808
123456816
123456824
123456832
123456840
123456857
123456865
123456873
and somehow i Can't reach the desired output, anyone can help? :)
import string
letters = string.ascii_letters
digits = string.digits
class NumNotNineLong(Exception):
def __init__(self):
pass
def __str__(self):
return "The number you provided is not nine digits long."
class NotNumber(Exception):
def __init__(self):
pass
def __str__(self):
return "The input you provided is not an integer"
class IDIterator():
increment = 1
def __init__(self,_id):
self._id = _id
def __iter__(self):
return self
def __next__(self):
while check_id_valid(str(self._id)[-9::]) == False:
self._id *= 2
self._id += IDIterator.increment
IDIterator.increment += 1
if check_id_valid(str(self._id)[-9::]):
result = str(self._id)[-9::]
self._id *= 2
self._id += 1
IDIterator.increment = 2
return result
def check_id_valid(id_number):
for letter in str(id_number):
if letter not in string.digits:
raise NotNumber
numbers = [int(i) for i in str(id_number)]
if len(numbers) != 9:
raise NumNotNineLong
set_numbers = []
for i in range(len(numbers)):
if i % 2 == 0:
set_numbers.append(numbers[i])
else:
set_numbers.append(numbers[i] * 2)
true_numbers = []
for num in set_numbers:
if num > 9:
temp = [int(i) for i in str(num)]
true_numbers.append(sum(temp))
else:
true_numbers.append(num)
if sum(true_numbers) % 10 == 0:
return True
else:
return False
def main():
result = IDIterator(123456780)
for _ in range(10):
print(result.__next__())
if __name__ == "__main__":
main()

I.D number generator

so basically i got an assignment to create a generator that will produce valid I.D numbers for citizans in my country.
a valid number is 9 digits, for each digit you need to multiply it by 1 or 2 according to the index, if the index is even, multiply the num by 1, else multiply it by 2.
after that if a curtain digit became greater than 9, change it to the sum of its digits.
if the overall sum % 10 == 0 then the num is valid.
else false.
after that they wanted me to create a class that will produce an itirator.
in the next method:
if the number that was given is valid, return it and multiply afterwards by 2 and add 1, and then check again if valid or not, if not multiply by 2 and add 2 and so on..
if from the beginning the num wasn't valid, multiply by 2 and add 1 then multiply by 2 and add 2 and so on...
import string
letters = string.ascii_letters
digits = string.digits
class NumNotNineLong(Exception):
def __init__(self):
pass
def __str__(self):
return "The number you provided is not nine digits long."
class NotNumber(Exception):
def __init__(self):
pass
def __str__(self):
return "The input you provided is not an integer"
class IDIterator():
increment = 1
def __init__(self,_id):
self._id = _id
def __iter__(self):
return self
def __next__(self):
while check_id_valid(str(self._id)[-9::]) == False:
self._id *= 2
self._id += IDIterator.increment
IDIterator.increment += 1
if check_id_valid(str(self._id)[-9::]):
result = str(self._id)[-9::]
self._id *= 2
self._id += 1
IDIterator.increment = 2
return result
def check_id_valid(id_number):
for letter in str(id_number):
if letter not in string.digits:
raise NotNumber
numbers = [int(i) for i in str(id_number)]
if len(numbers) != 9:
raise NumNotNineLong
set_numbers = []
for i in range(len(numbers)):
if i % 2 == 0:
set_numbers.append(numbers[i])
else:
set_numbers.append(numbers[i] * 2)
true_numbers = []
for num in set_numbers:
if num > 9:
temp = [int(i) for i in str(num)]
true_numbers.append(sum(temp))
else:
true_numbers.append(num)
if sum(true_numbers) % 10 == 0:
return True
else:
return False
def main():
result = IDIterator(123456780)
for _ in range(10):
print(result.__next__())
if __name__ == "__main__":
main()
my results are :
209872373
274495985
097983944
391935780
903409134
227273083
545477432
363819467
910555747
409086964
wanted results are:
209872373
863664504
569826803
339640302
473959864
544578024
356624288
466187762
040830960
487293938
save me
thank you!
My take on the problem:
class IDIterator:
def __init__(self, num):
self.__num = num
def __iter__(self):
n, num = 1, self.__num
while True:
num = int( str(num)[-9:] )
if is_valid(num):
yield '{:0>9}'.format(num)
num *= 2
num += n
n = 1
else:
num *= 2
num += n
n += 1
def is_valid(num):
s = '{:0>9}'.format(num)
if len(s) != 9:
return False
nums = [int(ch) * 2 if i % 2 else int(ch) for i, ch in enumerate(s)]
nums = [sum(int(c) for c in str(n)) for n in nums]
return sum(nums) % 10 == 0
from itertools import islice
for num in islice(IDIterator(123456780), 0, 10):
print(num)
Prints:
209872373
863664504
569826803
339640302
473959864
544578024
356624288
466187762
040830960
487293938

Python implementation of Determining DNA Health algorithm from HackerRank

I am trying to solve Determining DNA Health challenge from Hackerrank using python. (I have to add I am somewhat new to python 3. Still learning the language)
My solution fails for test cases 7, 8 and 9 with a message reading "Wrong Answer".
When I run the following code locally, I can confirm that for these test cases my implementation produces the expected output.
I am wondering what would be the problem.
I am a bit puzzled at the moment. Is there a problem with my implementation? If so how come it produces correct answers for 28 test cases but fails on these 3? Or is it a misleading/confusing result message from Hacker Rank, as I happen to know that people find these 3 test cases (7, 8 and 9) problematic from what I learnt from reading discussions.
Any help would be highly appreciated.
Here is the code I wrote:
from bisect import bisect_left
from bisect import bisect_right
import sys
from unittest.mock import right
class TrieNode(object):
def __init__(self):
self.subnodes = {}
self.isTerminal = False
self.indexList = []
self.healthList = []
def addSubnode(self, aChar):
if (self.subnodes.get(aChar)):
return self.subnodes[aChar]
else:
newNode = TrieNode()
self.subnodes[aChar] = newNode
return newNode
def addIndexAndValue(self, index, health):
self.isTerminal = True
self.indexList.append(index)
lastHealth = 0
healthLength = len(self.healthList)
if (healthLength>0):
lastHealth = self.healthList[healthLength-1]
self.healthList.append(lastHealth + health)
def getSubnodeFor(self, aChar):
return self.subnodes.get(aChar)
def getValueForIndexes(self, startIndex, endIndex):
listSize = len(self.indexList)
if listSize < 1:
return 0
elif listSize == 1:
if startIndex <= self.indexList[0] and endIndex >= self.indexList[0]:
return self.healthList[0]
else:
return 0
else: # listSize > 1
rightInd = bisect_left(self.indexList, endIndex)
if rightInd < listSize and endIndex < self.indexList[0]:
return 0
big = 0
if rightInd >= listSize:
big = self.healthList[listSize - 1]
else:
if endIndex >= self.indexList[rightInd]:
big = self.healthList[rightInd]
else:
big = self.healthList[rightInd-1]
leftInd = bisect_left(self.indexList, startIndex)
small = 0
if leftInd >= listSize:
return 0
else:
if startIndex <= self.indexList[leftInd]:
if (leftInd > 0):
small = self.healthList[leftInd - 1]
else:
small = 0
else:
small = self.healthList[leftInd]
return big - small
class Trie(object):
def __init__(self):
self.root = TrieNode()
def getRoot(self):
return self.root
def createTrie(self, genes, healths):
for i in range(len(genes)):
node = self.root
for c in genes[i]:
node = node.addSubnode(c)
node.addIndexAndValue(i, healths[i])
def calculateHealth(trie, d, first, last):
total = 0
dLength = len(d)
for i in range(0, dLength):
node = trie.getRoot()
for j in range(i, dLength):
node = node.getSubnodeFor(d[j])
if node != None:
if node.isTerminal:
val = node.getValueForIndexes(first, last)
total = total + val
else:
break
return total
def readFromFile(aFileName):
inputArr = None
with open('../hackerRank/src/' + aFileName, encoding='utf-8') as aFile:
inputArr = aFile.read().splitlines()
return inputArr
def runFor(fileName, minimumValue, maximumValue):
inp = readFromFile(fileName)
n = inp[0]
genes = inp[1].rstrip().split()
healths = list(map(int, inp[2].rstrip().split()))
trie = Trie()
trie.createTrie(genes, healths)
s = int(inp[3])
minVal = sys.maxsize
maxVal = -1
for fItr in range(s):
line = inp[fItr+4].split()
first = int(line[0])
last = int(line[1])
d = line[2]
val = calculateHealth(trie, d, first, last)
if val < minVal:
minVal = val
if val > maxVal:
maxVal = val
print (minVal,maxVal)
assert minimumValue == minVal
assert maximumValue == maxVal
# TextX.txt 's are simple text files, which hold test data for regarding test case
# following the file name are real expected numbers for each relevant test case
# I got those from hacker rank
runFor('Test2.txt', 15806635, 20688978289)
runFor('Test7.txt', 0, 7353994)
runFor('Test8.txt', 0, 8652768)
runFor('Test9.txt', 0, 9920592)
runFor('Test33.txt', 11674463, 11674463)
One reference that might assist can be found at:
https://gist.github.com/josephmisiti/940cee03c97f031188ba7eac74d03a4f
Please read the notes he has included.
This is the input I have been using.
6
a b c aa d b
1 2 3 4 5 6
3
1 5 caaab
0 4 xyz
2 4 bcdybc

Having trouble calling the parent class method from child class

I've started trying to learn Python after working with Java for the past year and decided to work on a couple class projects I've done and to write them in Python. I am getting an AttributeError at line 102, stating my super object has no attribute 'area'.
I've looked through different posts of how it's done, and I can't seem to figure out why this isn't working correctly for me after following other solutions.
It's a simple program that takes in input from the user, parses it, then depending on the shape type, will call the methods of the appropriate object type, then calculates and prints it out. For example, an input would be "R 3/4 5-7", supposed to weigh 8.37, or "P 1/4 5-6 2-3", supposed to weigh 126.07.
import math
class Shipment:
_weight = 0
def weight(self):
return self._weight
def frac_in_feet(self, frac):
thick_frac = frac.replace('/', "")
print("number is: ", thick_frac)
numerator = int(thick_frac[0])
denominator = int(thick_frac[1])
fraction_of_an_inch = numerator / denominator
return self.in_feet(0, fraction_of_an_inch)
def feet_and_inches_in_feet(self, feet_and_inches):
a = feet_and_inches.replace('-', "")
print("number is: ", a)
feet = int(a[0])
inches = int(a[1])
return self.in_feet(feet, inches)
def in_feet(self, feet, inches):
inches /= 12
print(feet + inches)
return feet + inches
def get_value_in_feet(self, str):
i = str.find('/')
j = str.find('-')
if i == -1:
value = self.feet_and_inches_in_feet(str)
if j == -1:
value = self.frac_in_feet(str)
return value
def add_item(self, quantity, description):
desc_values = description.replace(" ", "")
values = []
shape_letter = desc_values[0]
i = 1
j = 4
for r in range(int(len(desc_values) / 3)):
print("r is: ", r)
values.append(self.get_value_in_feet(desc_values[i:j]))
i += 3
j += 3
if shape_letter == 'P':
if len(values) != 3:
raise ValueError("Plate needs three dimensions. ")
shape = Plate(values[0], values[1], values[2])
elif shape_letter == 'R':
if len(values) != 2:
raise ValueError("Rod needs two dimensions")
shape = Rod(values[0], values[1])
else:
raise ValueError("Shape letter ", shape_letter, " not recognized.")
self._weight += quantity * shape.weight()
return shape
class SteelShape:
_length = 0
_weight = 0
def length(self, length):
_length = length
def length(self):
return self._length
def weight(self, weight):
self._weight = weight
def weight(self):
return self._weight
class CalcShape(SteelShape):
_area = 0
def area(self, area):
self._area = area
def weight(self):
return self._area * self.length() * 489
class Rod(CalcShape):
def __init__(self, diameter, length):
radius = diameter / 2
super(CalcShape, self).area(math.pi * radius**2)
super(CalcShape, self).length
class Plate(CalcShape):
def __init__(self, thick, width, length):
super(CalcShape, self).area(thick * width)
super(SteelShape, self).length(length)
values = []
shipment = Shipment()
shape = SteelShape()
line = input("Enter shape and dimensions: ")
shape = shipment.add_item(1, line)
if isinstance(shape, Plate):
print("Plate weighs ", shape.weight())
elif isinstance(shape, Rod):
print("Rod weighs ", shape.weight())
print("Total shipment weight: ", shipment.weight())
# R 3/4 5-7: supposed to weigh 8.37
# P 1/4 5-6 2-3: supposed to weigh 126.07
I think replacing the super and instead using staticmethod is a better choice. See here:
https://stackoverflow.com/a/735978/10416716
Hope this helps.

Categories