Home > Blockchain >  How to increment a number with the form x.y.z with the use of indexing and all numbers to the right
How to increment a number with the form x.y.z with the use of indexing and all numbers to the right

Time:04-06

I'm having trouble with trying to increment a specific number that is in the form x.y.z using an index and making all numbers to the right of it become 0.

The final product should look like this:

4.2.11 => 4.3.0

I've tried putting x.y.z into a list so I can retrieve any value I want with an index but can't make them increment in any way.

CodePudding user response:

Convert the number to a list with split, and convert the list items to ints so you can increment one of them; then convert back to str and join to produce a string in the original format.

>>> def bump(version, index):
...     nums = [int(i) for i in version.split(".")]
...     nums[index]  = 1
...     nums[index 1:] = [0] * (len(nums) - index - 1)
...     return ".".join(str(i) for i in nums)
...
>>> bump("4.2.11", 1)
'4.3.0'
>>> bump("4.2.11", 0)
'5.0.0'
>>> bump("4.2.11", 2)
'4.2.12'

CodePudding user response:

Keep the digits in a list and make a class to encapsulate the behaviour.

class X:
    def __init__(self,x):
        self.digits = [int(n) for n in x.split('.')]
    def __getitem__(self,item):
        return self.digits[item]
    def __setitem__(self,item,value):
        self.digits[item] = value
        for i in range(item 1,len(self.digits)):
            self.digits[i] = 0
    def __str__(self):
        temp = '.'.join('{}' for _ in self.digits)
        return temp.format(*self.digits)

>>> x = X('4.3.11')
>>> str(x)
'4.3.11'
>>> x[1]  = 1
>>> str(x)
'4.4.0'
>>> x[0]  = 1 
>>> str(x)    
'5.0.0'
>>>
  • Related