How to print an ID number include leading zeros? - python

I'm writing an Iterator class that generate all possible ID numbers.
the issue is that I need it to print all 9 digit numbers including the ones that starts with 0 for example: 000000001 000000002 ect.
I need the output as a number and not a string, is there a way to do it?
my code:
class IDIterator:
def __init__(self):
self._id = range(000000000, 1000000000)
self._next_id = 000000000
def __iter__(self):
return self
def __next__(self):
self._next_id += 1
if self._next_id == 999999999:
raise StopIteration
return self._next_id
ID = iter(IDIterator())
print(next(ID))
print(next(ID))
print(next(ID))
output = 1
2
3
..

Python has a built in string function which will perform the left-padding of zeros
>>> before = 1
>>> after = str(before).zfill(9)
000000001
>>> type(after)
<class 'str'>
If you need the ID returned as an integer number with leading zeros preserved, I don't believe there's a way to do what you're looking for--the primitive Python type simply does not support this type of representation. Another strategy would be to store the ID's as normal integers and format with leading zeros when you need to display something to the user.
def format_id(string, length=9):
return str(string).zfill(length)

Related

Printing out a matrix out of a two dimensional list

I would like to implement the str method to nicely format the string representation of the matrix: one line per row, two characters per number (%2d) and a space between numbers. For example:
m = Matrix([[1,0,0],[0,1,0],[0,0,1]])
print(m)
1 0 0
0 1 0
0 0 1
I've tried this:
class Matrix:
def __init__(self, rows):
self.rows = rows
def __str__(self):
for element in self.rows:
for i in element:
print(i, end=" ")
print()
But my output becomes
1 2 3
4 5 6
7 8 9
None
How would I solve this? Because the none shouldn't be there.
The __str__ method has to return a string, not print it.
What you are seeing is:
The prints inside of __str__.
The return value of __str__, which is None.
To correct it, build a string in __str__ and return it.
class Matrix:
def __init__(self, rows):
self.rows = rows
def read(self):
for element in self.rows:
for i in element:
print(i, end=" ")
print('\n')
m = Matrix([[1,0,0],[0,1,0],[0,0,1]])
m.read()
You Should use something like this. Creating a new function to represent your data is good practice than trying to use the __str__ method to do your job. because you might need to handle other edge cases explicitly
Output:
1 0 0
0 1 0
0 0 1
Note: This way you can remove None at the end as well
because The first is inside function and the second is outside function. When a function doesn't return anything, it implicitly returns None.
Maybe you could do it like this?
class Matrix:
def __init__(self, rows):
self.rows = np.array(rows)
def __str__(self):
return "\n".join(np.array2string(row)[1:-1] for row in self.rows)
m = Matrix([[1,0,0],[0,1,0],[0,0,1]])
print(m)
Notice that we here convert rows to to a 2d numpy array first. If you want to avoid numpy for some reason, you can do this.
class Matrix:
def __init__(self, rows):
self.rows = rows
def __str__(self):
return '\n'.join(' '.join(map(str, row)) for row in self.rows)
m = Matrix([[1,0,0],[0,1,0],[0,0,1]])
print(m)

Python classes and definitions

Here is my python code:
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
s1.isPalindrome()
It checks to see if the input is a palindrome. I want to create a new object that has the x value 121 and when I execute the isPalindrom function, I want it to return either a true or false boolean answer.
Currently when I run this program, nothing gets outputted. I am a bit lost as to where to go from here, would appreciate help.
Just print out the return value of isPalindrome(), because if you have a line with only a return value (this case being a boolean), the compiler won't know what to do with it.
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
print(s1.isPalindrome())
You're not telling the program to print anything. Try using print to make it reveal the answer.
Along with printing results we can also make class more pythonic.
class Solution:
def __init__(self):
self.input = None
def is_palindrome(self):
if isinstance(self.input, str):
return self.input == self.input[::-1]
print("Error: Expects str input")
return False # or leave blank to return None
s1 = Solution()
print(s1.is_palindrome())
s1.input = "121"
print(s1.is_palindrome())
output
Error: Expects str input
False
True
The main idea here is divide number. let's take number 122. First of all you need store it in a variable, in this case r_num. While loop is used and the last digit of the number is obtained by using the modulus operator %. The last digit 2 is then stored at the one’s place, second last at the ten’s place and so on. The last digit is then removed by truly dividing the number with 10, here we use //. And lastly the reverse of the number is then compared with the integer value stored in the temporary variable tmp if both are equal, the number is a palindrome, otherwise it is not a palindrome.
def ispalindrom(x):
r_num = 0
tmp = x
while tmp > 0:
r_num = (r_num * 10) + tmp % 10
tmp = tmp // 10
if x == r_num:
return True
return False

Decimal number parse in Python

I have a number as in below:
.12
in my code I convert this number to string and parse it from the "point" to decimal as in below:
mydecimal = str(mydecimal_new)
whole_number = mydecimal.split('.')
main_number = whole_number[0]
#print(main_number)
additional_number = whole_number[1]
#print(additional_number)
My problem is when I try to convert this number to str python add 0 in front of the number and it keep the number as:
0.12
I want to know how can I avoid from the adding zero in front of this
Try This :
def _remove_leading_zero(value, string):
if 1 > value > -1:
string = string.replace('0', '', 1)
return string
class MyFloat(float):
def __str__(self):
string = super().__str__()
return _remove_leading_zero(self, string)
def __format__(self, format_string):
string = super().__format__(format_string)
return _remove_leading_zero(self, string)
print(MyFloat(.12))
You Can Fly to the Moon Now :))) Good Luck.

How to get number of decimal places

How would I do the following:
>>> num_decimal_places('3.2220')
3 # exclude zero-padding
>>> num_decimal_places('3.1')
1
>>> num_decimal_places('4')
0
I was thinking of doing:
len((str(number) if '.' in str(number) else str(number) + '.').rstrip('0').split('.')[-1])
Is there another, simpler way to do this?
You can use a regex to parse value, capture the decimal digits and count the length of the match, if any:
import re
def num_decimal_places(value):
m = re.match(r"^[0-9]*\.([1-9]([0-9]*[1-9])?)0*$", value)
return len(m.group(1)) if m is not None else 0
this is a bit less "raw" than splitting the string with multiple if else, not sure if simpler or more readable, though.
The best and the most Pythonic way to achieve this is:
import decimal
x = '56.001000'
x = x.rstrip('0') # returns '56.001'
x = decimal.Decimal(x) # returns Decimal('0.001')
x = x.as_tuple().exponent # returns -3
x = abs(x) #returns 3
Above code can be written in simpler way as:
>>> x = '56.001000'
>>> abs(decimal.Decimal(x.rstrip('0')).as_tuple().exponent)
3
Below is the list of used functions for more reference:
str.rstrip(): Return a copy of the string with trailing characters removed.
decimal.Decimal(): Construct a new Decimal object based from value.
x.as_tuple(): Returns a namedtuple of the format: DecimalTuple(sign=0, digits=(1,), exponent=-3)
abs(): Return the absolute value of a number.
You dont need regex, you can convert to float and convert back to string! this automatically will remove the zeroes :
>>> def convertor(s):
... try :
... int(s.rstrip('0').rstrip('.'))
... return 0
... except:
... return len(str(float(s)).split('.')[-1])
...
>>> convertor('4.0230')
3
>>> convertor('4.0')
0
>>> convertor('4')
0
you could also just try something like:
try:
return len(str(num).split('.')[1].rstrip('0'))
except
return 0
By string process:
Check . is present in number string or not.
If Not present then return 0.
If present the split number string by . and get second item from the split result.
Remove 0 from the right side.
Return len of item.
code:
>>> def dCount(no_str):
... if "." in no_str:
... return len(no_str.split(".")[1].rstrip("0"))
... else:
... return 0
...
>>> dCount("2")
0
>>> dCount("2.002")
3
>>> dCount("2.1230")
3
>>> dCount("2.01230")
4
>>>
import re
def f(s):
ls = s.split('.', 1)
if len(ls) == 2 and re.match(r'\d*$', ls[1]):
return len(ls[1].rstrip('0'))
return 0
assert f('12') == 0
assert f('12.') == 0
assert f('12.1') == 1
assert f('12.100006') == 6
assert f('12.1.3') == 0
assert f('12.1abc') == 0
assert f('12.100000') == 1
The Decimal type is perfect for this, you can implement num_decimal_places() as follows:
from decimal import Decimal
def num_decimal_places(value: str):
return -Decimal(value).normalize().as_tuple().exponent
It works as follows: Decimal(value) parses the string, including exponent notation, then .normalize() strips any trailing zeros from the internal representation. .as_tuple().exponent contains the number of decimal places the internally stored integer is shifted to the left, so negative numbers specify the number of places to the right of the decimal.
You could try using the Decimal function in python:
abs(Decimal(string_value).as_tuple().exponent)
as explained in
Easy way of finding decimal places

How to count the number of letters in a string with a list of sample?

value = 'bcdjbcdscv'
value = 'bcdvfdvdfvvdfvv'
value = 'bcvfdvdfvcdjbcdscv'
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
How to count the number of letters in a string with a list of sample? I get nothing in my python shell when I wrote the above code in my python file.
There is a built-in method for this:
value.count('c')
functions need to be called, and the return values need to be printed to the stdout:
In [984]: value = 'bcvfdvdfvcdjbcdscv'
In [985]: count_letters(value, 'b')
Out[985]: 2
In [987]: ds=count_letters(value, 'd') #if you assign the return value to some variable, print it out:
In [988]: print ds
4
EDIT:
On calculating the length of the string, use python builtin function len:
In [1024]: s='abcdefghij'
In [1025]: len(s)
Out[1025]: 10
You'd better google it with some keywords like "python get length of a string" before you ask on SO, it's much time saving :)
EDIT2:
How to calculate the length of several strings with one function call?
use var-positional parameter *args, which accepts an arbitrary sequence of positional arguments:
In [1048]: def get_lengths(*args):
...: return [len(i) for i in args]
In [1049]: get_lengths('abcd', 'efg', '1234567')
Out[1049]: [4, 3, 7]
First you should probably look at correct indenting and only send in value. Also value is being overwritten so the last one will be the actual reference.
Second you need to call the function that you have defined.
#value = 'bcdjbcdscv'
#value = 'bcdvfdvdfvvdfvv'
value = 'bcvfdvdfvcdjbcdscv'
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
x = count_letters(value, 'b')
print x
# 2
This should produce the result you are looking for. You could also just call:
print value.count('b')
# 2
In python, there is a built-in method to do this. Simply type:
value = 'bcdjbcdscv'
value.count('c')

Categories