Home > database >  How to increment a number with the form x.y.z
How to increment a number with the form x.y.z

Time:04-05

I'm having an issue with trying to increment the farthest right number in the form of x.y.z without the use of indexing. I've never worked with a float before that had more than 1 decimal point and don't know how to get this started. I think I would need to convert each individual value into an integer and then use a string to output them.

The final product needs to look something like this:

1.7.9 => 1.7.10

CodePudding user response:

There is no such thing as a "float with more than 1 decimal point". Floats are real numbers. What you are looking for can be accomplished with something like that:

>>> version = "1.7.9"
>>> parts = version.split(".")
>>> parts
['1', '7', '9']
>>> parts[2] = str(int(parts[2])   1)
>>> parts
['1', '7', '10']
>>> ".".join(parts)
'1.7.10'

CodePudding user response:

You'll have a hard time doing this with floats (you can't have 2 decimal places in a float)... I'd suggest you track the x.y.z separately as integers and then you can increment them individually:

x = 1
y = 7
z = 9

print(f"{x}.{y}.{z}")
# "1.7.9"

z  = 1

print(f"{x}.{y}.{z}")
# "1.7.10"

CodePudding user response:

You can also use an object to store x, y and z :

class xyz:
    def __init__(self, x, y, z):
        self.x, self.y, self.z = x, y, z
    
    def __str__(self):
        return f"{self.x}.{self.y}.{self.z}"

    def increment(self):
        self.z  = 1

obj = xyz(1, 7, 9)

print(obj) # 1.7.9

obj.increment()

print(obj) # 1.7.10

CodePudding user response:

First thins, you can not have two decimal places in a float, and the easiest way to solve your problem is just using indexing of str.

s = "1.7.9"
print(''.join(s[:-1] str(int(s[-1]) 1)))

But since you don't want to use indexing you can use the following code instead. But using this code is like you are using a hammer to squash a fly. So it is not recommended and this is only because you asked for a way to do it. And remember even inside those functions they use indexing to give the output.

s = "1.7.9"
t = '.'.join([str(int(x) 1 if x in s.rpartition(".") else int(x)) for x in s.split(".")])
print(t)

CodePudding user response:

You can try this out;

a = '1.7.9'
output = a[:-1]  str(int(a.split('.')[-1]) 1)
print(output)
  • Related