Python function that creates max number from list of numbers - python

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)

Related

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

Recursive Hexadecimal Conversion Python 3

I've made a hexadecimal converter to practice recursion/recursive thinking. I, however, The recurssion doesn't appear to be happening as the functions seems to just output the result of 9 as of current.The code is as follows:
import math
curr=0
def convert(x):
L=len(x)
L-=1
sol=0
if L == 0:
return 0
else:
if x[curr]==["A","a"]:
v=10
elif x[curr]==["B","b"]:
v=11
elif x[curr]==["C","c"]:
v=12
elif x[curr]==["D","d"]:
v=13
elif x[curr]==["E","e"]:
v=14
elif x[curr]==["F","f"]:
v=15
else:
v=int(x[curr])
sol+=((v)*(16**(L-1)))
return sol + convert(x[curr+1])
def main():
print(convert('98A'))
main()
You were setting L = len(x) everytime you call the function. Here is one solution:
import math
def convert(x, L):
c = len(x) - 1
sol=0
if L > c:
return 0
else:
if (x[L]=="A" or x[L]=="a"):
v=10
elif (x[L]=="B" or x[L]=="b"):
v=11
elif (x[L]=="C" or x[L]=="c"):
v=12
elif (x[L]=="D" or x[L]=="d"):
v=13
elif (x[L]=="E" or x[L]=="e"):
v=14
elif (x[L]=="F" or x[L]=="f"):
v=15
else:
v=int(x[L])
sol+=((v)*(16**(c - L)))
print(sol)
return sol + convert(x, L + 1)
def main():
print(convert('98A', 0))
main()
You can use something like this:
class HexMap:
# mapping char to int
d = { hex(n)[2:]:n for n in range(16)}
def convert(x):
s = 0
# use reverse string and sum up - no need for recursion
for i,c in enumerate(x.lower()[::-1]):
s += HexMap.d[c]*16**i
return s
def main():
print(convert('98A'))
main()
Output:
2442
Recursive version:
# class HexMap: see above
def convert(x):
def convert(x,fak):
if not x:
return 0
else:
return HexMap.d[x[-1]]*16**fak + convert(x[:-1],fak+1)
return convert(x.lower(),0)
def main():
print(convert('98A'))
main()
Same output.

How to improve performance of this python code?

I am solving a puzzle (Finding if there exists an input for a given automata for which no matter what the starting state is, final state would be same everytime) and have written following python code. A few testcases are written in check method in the code. For these cases program is running fairly fast. However, for testcases where 50 lists(nodes) are present, the programis taking forever to execute. I am storing intermediate results to use further as well. Can someone please review the code and give suggestions on how to increase the performance of the code?
from itertools import product
from copy import deepcopy
class Node:
def __init__(self,id):
self.id = id
self.dict = {}
def __str__(self):
return str(id) + " : " + str(self.dict)
def __repr__(self):
return str(id) + " : " + str(self.dict)
def tryDelete(nodes,_len):
for id in nodes:
y = deepcopy(nodes)
x = y[id]
del y[id]
for id,node in y.items():
for input,result in node.dict.items():
if result == x:
if x.dict[input] == x:
node.dict[input] = node
else:
node.dict[input] = x.dict[input]
pass
if pathPossible(y,_len ,False) == -1:
return x.id
return -2
target = {}
def FindTarget(node,p):
if len(p) == 1:
return node.dict[p[0]]
if node not in target or p not in target[node]:
x = FindTarget(node,p[:-1]).dict[p[-1]]
if node not in target:
target[node] = {}
target[node][p] = x
return target[node][p]
def allSatisy(nodes,p):
x = None
for key,node in nodes.items():
if x is None:
x = FindTarget(node,p)
elif FindTarget(node,p) != x:
return False
return True
def allPossiblePaths(l,n):
#x = int(((l+1)*(l+2))/2)
for i in range(1, n+1):
for p in product(range(l),repeat=i):
yield p
def pathPossible(nodes,_len ,isItereate=True):
i = 1
isFound = False
for p in allPossiblePaths(_len,len(nodes)):
if allSatisy(nodes,p):
isFound = True
break
if isFound:
return -1
elif not isItereate:
return -2
else:
return tryDelete(nodes,_len)
def answer(li):
nodes = {}
for i in range(len(li)):
nodes[i] = Node(i)
for i in range(len(li)):
for j in range(len(li[i])):
nodes[i].dict[j] = nodes[li[i][j]]
return pathPossible(nodes,len(nodes[0].dict))
def check(li,ans):
# each item in the list is a node, each item i-th in the inner list tells to what node the transition happens for input i
x = answer(li)
print(str(li) + " : " + str(ans) + " : " + str(x))
def main():
check([[2,1],[2,0],[3,1],[1,0]],-1)
check([[1,2],[1,1],[2,2]],1)
check([[1,3,0],[1,0,2],[1,1,2],[3,3,3]],-1)
if __name__ == '__main__':
main()
UPDATE: I have done few code changes, but still this needs some review from you guys. Changed code:
from itertools import product
from copy import deepcopy
class Node:
def __init__(self,id):
self.id = id
self.dict = {}
def __str__(self):
return str(self.id) + " : " + str(self.dict)
def __repr__(self):
return str(self.id) + " : " + str(self.dict)
def tryDelete(nodes,_len):
for i in range(len(nodes)):
y = nodes[:]
x = y[i]
del y[i]
tNodes = []
for node in y:
for input,result in node.dict.items():
if result == x:
node.tDict = deepcopy(node.dict)
if x.dict[input] == x.id:
node.dict[input] = node
else:
node.dict[input] = x.dict[input]
if pathPossible(y,_len ,False) == -1:
return x.id
for n in tNodes:
n.dict = n.tDict
del n.tDict
return -2
target = {}
def FindTarget(node,p):
if len(p) == 1:
return node.dict[p[0]]
if node not in target or p not in target[node]:
x = Gnodes[FindTarget(node,p[:-1])].dict[p[-1]]
if node not in target:
target[node] = {}
target[node][p] = x
return target[node][p]
def allSatisy(nodes,p):
x = None
for node in nodes:
if x is None:
x = FindTarget(node,p)
elif FindTarget(node,p) != x:
return False
return True
def allPossiblePaths(l,n):
#x = int(((l+1)*(l+2))/2)
for i in range(1, n + 1):
for p in product(range(l),repeat=i):
yield p
def pathPossible(nodes,_len ,isItereate=True):
i = 1
isFound = False
for p in allPossiblePaths(_len,len(nodes)):
if allSatisy(nodes,p):
isFound = True
break
if isFound:
return -1
elif not isItereate:
return -2
else:
return tryDelete(nodes,_len)
Gnodes = []
def answer(li):
Gnodes[:] = []
for i in range(len(li)):
Gnodes.append(Node(i))#[i] = Node(i)
for i in range(len(li)):
for j in range(len(li[i])):
Gnodes[i].dict[j] = li[i][j]
return pathPossible(Gnodes,len(Gnodes[0].dict))
def check(li,ans):
x = answer(li)
print(str(li) + " : " + str(ans) + " : " + str(x))
def main():
check([[2,1],[2,0],[3,1],[1,0]],-1)
check([[1,2],[1,1],[2,2]],1)
check([[1,3,0],[1,0,2],[1,1,2],[3,3,3]],-1)
if __name__ == '__main__':
main()
There is a wonderful graph library called NetworkX. It deals with creating graphs and path finding. You specify what edges or paths exist in your Graph and you can find paths using a plethora of algorithms like breadth first search, or A*, and many others in the algorithms section. The best way to optimize your time is code reuse.
https://networkx.github.io

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()

Categories