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
Related
I just want to know if there is a simple way to convert an int(negative number) to a list
Example
a = -2021
result : [-2,0,2,1]
def numberToList(n):
# base case
if n == 0:
return []
# recurse
return numberToList(n // 10) + [ n % 10 ]
def numberInput(n):
if n < 0:
n = numberToList(abs(n))
n[0] = n[0] * -1
return n
else:
return numberToList(n)
Just use a function like this:
from typing import List
def num_list(num: int) -> List[int]:
if num == 0:
return []
ns = [int(i) for i in str(num).lstrip('-')]
if num < 0:
ns[0] *= -1
return ns
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()
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
The question is this :
Write a Python function to find all the Strong numbers in a given list of numbers.
Write another function to find and return the factorial of a number. Use it to solve the problem.
Note: 0!=1
The code I tried so far :
def factorial(number):
sum1=0
temp=number
while(number):
i=1
f=1
r=number%10
while(i<=r):
f=f*i
i=i+1
sum1=sum1+f
number=number//10
return sum1
return temp
def find_strong_numbers(num_list):
for item in num_list:
for number in range(1,item+1):
if(sum1==temp):
print(number)
num_list=[145,375,100,2,10]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
Expected output : [145, 2]
I am facing error which is :
NameError: name 'sum1' is not defined
import math
def factorial(number):
if number == 0:
return 1
else:
return number * factorial(number-1)
def find_strong_numbers(num_list):
strongNumbersList = []
for item in num_list:
currentNumber = item
digits = []
while currentNumber > 0:
digits.insert(0, currentNumber % 10)
currentNumber = currentNumber // 10
if sum(map(factorial, digits)) == item:
strongNumbersList.append(item)
return strongNumbersList
num_list=[145,375,100,2,10]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
import math
def factorial(number):
if number == 0:
return 1
else:
return number * factorial(number-1)
def find_strong_numbers(num_list):
strongNumbersList = []
for item in num_list:
currentNumber = item
digits = []
while currentNumber > 0:
digits.insert(0, currentNumber % 10)
currentNumber = currentNumber // 10
if sum(map(factorial, digits)) == item:
if item==0:
break
strongNumbersList.append(item)
return strongNumbersList
num_list=[145,375,100,2,10,40585,0]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
List item
MyFunctions file file -
def factList(p,n1):
counter = 1
while counter <= n1:
if n1 % counter == 0:
p.append(counter)
counter = counter + 1
def isPrime(lst1,nbr):
factList(lst1, nbr)
if len(lst1) == 2:
return True
else:
return False
def nextPrime(nbr1):
cnt1 = 1
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 = 0
Filetester file -
nbr1 = 13
nextPrime(nbr1)
print nbr1
My isPrime function already works I'm tring to use my isPrime function for my nextPrime function, when I run this I get
">>>
13
" (when using 13)
">>> " (When using 14)
I am supposed to get 17 not 13. And if I change it to a composite number in function tester it gets back in a infinite loop. Please only use simple functions (the ones I have used in my code).
This is NOT the right way to do this, but this is the closest adaptation of your code that I could do:
def list_factors_pythonic(number):
"""For a given number, return a list of factors."""
factors = []
for x in range(1, number + 1):
if number % x == 0:
factors.append(x)
return factors
def list_factors(number):
"""Alternate list_factors implementation."""
factors = []
counter = 1
while counter <= number:
if number % counter == 0:
factors.append(counter)
return factors
def is_prime(number):
"""Return true if the number is a prime, else false."""
return len(list_factors(number)) == 2
def next_prime(number):
"""Return the next prime."""
next_number = number + 1
while not is_prime(next_number):
next_number += 1
return next_number
This would be helpful:
def nextPrime(number):
for i in range(2,number):
if number%i == 0:
return False
sqr=i*i
if sqr>number:
break
return True
number = int(input("Enter the num: ")) + 1
while(True):
res=nextPrime(number)
if res:
print("The next number number is: ",number)
break
number += 1
I don't know python but if it's anything like C then you are not assigning anything to your variables, merely testing for equality.
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 == cnt1 + 1
Should become
while cnt1 == 1:
nbr1 = nbr1 + 1 << changed here
if isPrime(lst2,nbr1):
cnt1 = cnt1 + 1 << and here
Well this code help you
n=int(input())
p=n+1
while(p>n):
c=0
for i in range(2,p):
if(p%i==0):
break
else:c+=1
if(c>=p-2):
print(p)
break
p+=1
this code optimized for finding sudden next prime number of a given number.it takes about 6.750761032104492 seconds
def k(x):
return pow(2,x-1,x)==1
n=int(input())+1
while(1):
if k(n)==True:
print(n)
break
n=n+1