how to complete id numbers generator code in python - 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()

Related

how to invoke a function in a Python app which has multiple files

I have two or three files in Python for s-expression. But I am not able to invoke the function to calulate the result of s-expression as I am not sure which function to invoke.
I have four files here:
1st file: calc.py
import sys
from parse import *
from expr import *
from calculator import *
def main():
if len(sys.argv)<2:
print('No Input!')
return
expr_list = ParseInput(sys.argv[1]).parse_to_list()
expression = Expression(expr_list)
if not expression.check_validation():
print('Not Valid Input!')
return
calculator = Calculator()
print(calculator.calculate(expression))
if __name__ == '__main__':
main()
2nd file: expr.py
class Expression(object):
def __init__(self, expr_list=None):
self.__expression = expr_list
def get_subexprs(self, expr_list):
res = []
i = 2
while i < len(expr_list)-1:
l = self.count_subexpr_length(expr_list, i)
res.append(expr_list[i:i+l])
i += l
return res
def count_subexpr_length(self, expr_list, i):
j = i+1
if expr_list[i] == '(':
count = 1
while count!= 0 and j<len(expr_list):
if expr_list[j] == ')':
count -= 1
if expr_list[j] == '(':
count += 1
j += 1
return j-i
def check_validation(self):
return self.is_valid(self.__expression)
def is_valid(self, expr_list):
if not expr_list:
return False
if len(expr_list)==1:
return self.is_integer(expr_list)
return self.is_func(expr_list)
def is_func(self, expr_list):
if len(expr_list) < 4:
return False
if expr_list[0] != '(' or expr_list[-1] != ')':
return False
if expr_list[1] not in ['add', 'multiply']:
return False
count = 0
for char in expr_list:
if char == '(':
count += 1
if char == ')':
count -=1
if count <0 :
return False
if count != 0 :
return False
for subexpr in self.get_subexprs(expr_list):
if not self.is_valid(subexpr):
return False
return True
def is_integer(self, expr_list):
return expr_list[0].isdigit()
def get_length(self):
return len(self.__expression)
def get_int(self):
if len(self.__expression) == 1:
return int(self.__expression[0])
def get_operator(self):
if len(self.__expression) > 1 :
return self.__expression[1]
def get_exprlist(self):
return self.__expression
3rd file: parse.py
class ParseInput(object):
def __init__(self, input_string=''):
self.input_string = input_string
def parse_to_list(self):
if self.input_string == '':
print('No Valid Input!')
return None
newString = ''
for char in self.input_string:
if char == '(':
newString += char + ' '
elif char == ')':
newString += ' ' + char
else:
newString += char
return newString.split()
4th file:calculator.py
from expr import *
class Calculator(object):
def __init__(self):
pass
def calculate(self, expression):
return self.calc_expression(expression)
def calc_expression(self, expression):
if not expression:
print('Sorry, you need to load expression!')
return
if expression.get_length() == 1:
return expression.get_int()
operator = expression.get_operator()
if operator == 'add':
return self.calc_add(expression)
if operator == 'multiply':
return self.calc_mul(expression)
def calc_add(self, expression):
base = 0
for subexpr in expression.get_subexprs(expression.get_exprlist()):
base += self.calc_expression(Expression(subexpr))
return base
def calc_mul(self, expression):
base = 1
for subexpr in expression.get_subexprs(expression.get_exprlist()):
base *= self.calc_expression(Expression(subexpr))
return base
The requirement says:
calc.py
Main file to run this calculator engine. Runs the engine in command line, with one valid argument as input.
Example:
$ python calc.py "123"
$ python calc.py "(add 12 12)"
However, I don't see any input expression taking input from the user in calc.py. Also I did the following in Python shell and it gives me the following error.
>>> import calc
>>> calc.py "(add 12 12)"
File "<stdin>", line 1
calc.py "(add 12 12)"
^^^^^^^^^^^^^
SyntaxError: invalid syntax
I want to know which function to invoke and how to invoke that in Python shell?
Update:
When I tried it in the command prompt, it gives me the following error:

Python function that creates max number from list of numbers

I want to make a function that creates max number from list of numbers.
list_of_numbers =[15, 56, 2]
I need in result 56215, but result is 15562.
How to make it work?
class Comporator():
def __init__(self, number):
self.number = number
def __lt__(self, other):
result_1 = str(self.number) + str(other.number)
result_2 = str(other.number) + str(self.number)
return int(result_1) < int(result_2)
def max_number(list_of_numbers):
sorted(list_of_numbers, key = Comporator, reverse = True)
return list_of_numbers
def print_number(list_of_numbers):
for i in list_of_numbers:
print(i, end='')
if __name__ == "__main__":
list_of_numbers = [int(i) for i in input().split()]
max_number(list_of_numbers)
print_number(list_of_numbers)
You need to assign sorted(list_of_numbers, key = Comporator, reverse = True) to a variable
Make following changes in the code
class Comporator():
def __init__(self, number):
self.number = number
def __lt__(self, other):
result_1 = str(self.number) + str(other.number)
result_2 = str(other.number) + str(self.number)
return int(result_1) < int(result_2)
def max_number(list_of_numbers):
list_of_numbers = sorted(list_of_numbers, key = Comporator, reverse = True)
return list_of_numbers
def print_number(list_of_numbers):
for i in list_of_numbers:
print(i, end='')
if __name__ == "__main__":
list_of_numbers = [int(i) for i in input().split()]
list_of_numbers = max_number(list_of_numbers)
print_number(list_of_numbers)

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: Recursion problems

I am trying to make a sudoku solver that solves boards very quickly. At the moment my solver works on easy boards but never terminates on harder boards. I believe it has something to do with my recursion because easy boards do not require recursion and hard boards do. Any help is appreciated.
import sys
def rowno(i):
return i // 9
def colno(i):
return i % 9
def boxno(i):
return (i // 9 // 3 )*3 + (i // 3) % 3
def isNeighbor(i, j):
if rowno(i) == rowno(j) or colno(i) == colno(j) or boxno(i) == boxno(j):
return True
else:
return False
def getFileName():
if sys.platform == "win32":
filename = input("Filename? ")
else:
filename = sys.argv[-1]
return filename
solutionlist = []
class Board(object):
def __init__(self, puzzle):
self.puzzle = puzzle
self.board = [Cell(int(value), idx) for idx, value in enumerate(puzzle)]
self.change = False
def printAll(self):
print [cell.candidates for cell in self.board]
#return str(" ")
def update(self):
self.change = False
l = [cell for cell in self.board if len(cell.candidates) == 1]
for i in l:
for j in xrange(81):
if isNeighbor(i.dex, j) and i.dex != j:
old = self.board[j].candidates
self.board[j].delCandidate(i.value)
if len(old) != len(self.board[j].candidates):
self.change = True
def toString(self):
str1 = ''.join(str(e.value) for e in self.board)
return str1
def solved(self):
for cell in self.board:
if len(cell.candidates) != 1:
return False
return True
def solve(self):
self.change = True
while self.change == True:
self.update()
if self.solved():
solutionlist.append(self.board)
return
l = [cell for cell in self.board if len(cell.candidates) > 1]
for i in l:
for j in i.candidates:
newBoard = Board(self.toString())
curLen = 12
curCell = -1
for u in l:
if len(u.candidates)<curLen:
curLen=len(u.candidates)
curCell = u.dex
for c in newBoard.board[curCell].candidates:
newBoard.board[curCell].candidates = [int(c)]
newBoard.board[curCell].value = int(c)
newBoard.solve()
return
def __repr__(self):
l = [cell.value for cell in self.board]
return str(l)
class Cell(object):
def __init__(self, value, dex):
self.value = value
self.dex = dex
if value == 0:
self.candidates = [1,2,3,4,5,6,7,8,9]
else:
self.candidates = [int(value)]
def __str__(self):
return str(self.value)
def delCandidate(self, value):
# deletes value from candidate list
#return self.candidate.remove(value);
self.candidates = [x for x in self.candidates if x != value]
if len(self.candidates) == 1:
self.value = self.candidates[0]
easy = "700583006006001405052006083300200958500078060648010300060802500003150072215600030"
twosol = "000805200800000401705040009000100702040000000006430000030900000010006080000000000"
hard = "040090008000000070060000120030020000005839060080600700050170600000043000003000200"
#easy solution: 794583216836721495152496783371264958529378164648915327967832541483159672215647839
b = Board(hard)
print b
b.solve()
print "end of the line"
for i in solutionlist:
print [cell.value for cell in i]
print "\n"
One major issue is the line for i in l: in the solve method. Since you're recursing, you only need to fill in one cell - the recursion will take care of the rest. So instead of for i in l:, just recurse on the one cell that is the best candidate (curCell):
l = [cell for cell in self.board if len(cell.candidates) > 1]
if len(l) > 0:
newBoard = Board(self.toString())
curLen = 12
curCell = -1
for u in l:
if len(u.candidates)<curLen:
curLen=len(u.candidates)
curCell = u.dex
for c in newBoard.board[curCell].candidates:
newBoard.board[curCell].candidates = [int(c)]
newBoard.board[curCell].value = int(c)
newBoard.solve()

Infix to Postfix Converter Python 2.7

I am trying to create a infix to postfix converter in python for a homework assignment, I found multiple ones online that seem simple enough but none of them meet the requirements I need. I have to use the following classes:
class Token(object):
UNKNOWN = 0 # unknown
INT = 4 # integer
MINUS = 5 # minus operator
PLUS = 6 # plus operator
MUL = 7 # multiply operator
DIV = 8 # divide operator
FIRST_OP = 5 # first operator code
def getPrecedence(self):
if self is '(':
return 0
elif self is '+'or '-':
return 1
elif self is '*' or '/':
return 2
else:
return 3
def _init_(self, value):
if type(value) == int:
self._type = Token.INT
else:
self._type = self._makeType(value)
self._value = value
def isOperator(self):
return self._type >= Token.FIRST_OP
def _str_(self):
return str(self._value)
def getType(self):
return self._type
def getValue(self):
return self._value
def _makeType(self, ch):
if ch == '*': return Token.MUL
elif ch == '/': return Token.DIV
elif ch == '+': return Token.PLUS
elif ch == '-': return Token.MINUS
else: return Token.UNKNOWN;
I had to add the getPrecedence(): method, which returns an Integer that represents the precedence level of an operator. I also had to use the following class:
from token import Token
class Scanner(object):
EOE = ';' # end-of-expression
TAB = '\t' # tab
def __init__(self, sourceStr):
self._sourceStr = sourceStr
self._getFirstToken()
def hasNext(self):
return self._currentToken != None
def next(self):
if not self.hasNext():
raise Exception, "There are no more tokens"
temp = self._currentToken
self._getNextToken()
return temp
def _getFirstToken(self):
self._index = 0
self._currentChar = self._sourceStr[0]
self._getNextToken()
def _getNextToken(self):
self._skipWhiteSpace()
if self._currentChar.isdigit():
self._currentToken = Token(self._getInteger())
elif self._currentChar == Scanner.EOE:
self._currentToken = None
else:
self._currentToken = Token(self._currentChar)
self._nextChar()
def _nextChar(self):
if self._index >= len(self._sourceStr) - 1:
self._currentChar = Scanner.EOE
else:
self._index += 1
self._currentChar = self._sourceStr[self._index]
def _skipWhiteSpace(self):
while self._currentChar in (' ', Scanner.TAB):
self._nextChar()
def _getInteger(self):
num = 0
while True:
num = num * 10 + int(self._currentChar)
self._nextChar()
if not self._currentChar.isdigit():
break
return num
I have to write a program that converts a infix expression to a postfix expression. This program should use the Token and Scanner classes (which I have included above). The program should consist of a main function that preforms the inputs and outputs, and a class named IFToPFConverter. The main function receives a input string an creates a scanner with it. The scanner is then passed as a argument to the constructor of the converter object. The converter objects convert method is then run to convert the infix expression. This method returns a list of tokens that represent the postfix string. The main function then displays this string. Here is what I have so far:
from arrayStack import ArrayStack
from token import Token
from scanner import Scanner
class IFToPFConverter(object):
def convert(self):
opStack = Stack()
postFixList = []
while self._scanner.hasNext():
currentToken = self._scanner.next()
if currentToken in '0123456789'
postFixList.append(currentToken)
elif currentToken == '(':
opStack.push(currentToken)
elif currentToken == '*':
opStack.push(currentToken)
elif currentToken == '/':
opStack.push(currentToken)
elif currentToken == '+':
opStack.push(currentToken)
elif currentToken == '-':
opStack.push(currentToken)
elif currentToken == ')':
opStack.push(currentToken)
while not opStack.isEmpty():
def main():
sourceStr = raw_input("Please enter an expression:")
scanner = Scanner(sourceStr)
conversion = IFToConverter.convert(scanner)
return conversion
main()
I don't know where to go from here, I don't even know if what I am trying to do at in my IFToPFConverter class will work. I have seen much simpler infix to postfix converters.

Categories