'How to increment a number with the form x.y.z with the use of indexing and all numbers to the right of it become 0
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.
Solution 1:[1]
Only converting the one needed number to int, and by default incrementing the last number:
def increment(version, index=-1):
nums = version.split('.')
v = int(nums[index])
nums[index:] = '0' * len(nums[index:])
nums[index] = str(v + 1)
return '.'.join(nums)
print(increment("4.2.11", 0)) # => 5.0.0
print(increment("4.2.11", 1)) # => 4.3.0
print(increment("4.2.11", 2)) # => 4.2.12
print(increment("4.2.11")) # => 4.2.12
Solution 2:[2]
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'
Solution 3:[3]
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'
>>>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kelly Bundy |
| Solution 2 | Samwise |
| Solution 3 |
