'How would I shorten this few lines of python code? [closed]
In python how can I shorten the code below?
if x == 15:
y = 0
elif x == 14:
y = 1
elif x == 13:
y = 2
...
...
...
elif x == 0:
y = 15
Currently the solutions I've gotten are
y = 15-x
and adding a dictionary.
Solution 1:[1]
There Is A Pattern Your Code if x = 15 then y = 0 and if x = 14 then y = 1. If you just subtract x from 15 then you get the value of y. There is an equation made (if you know about math):
x+y = 15
then,
y = 15 -x
This Is The Code.
x = #value you use
y = 15 -x
Solution 2:[2]
The best practice to not use so many if
/elif
conditions is to use a dict
my_dct = {15: 0, 14: 2, 12: 3, 0: 15}
y = my_dct[x]
Solution 3:[3]
Do you mean like this?
for i in range(16,-1,-1):
y = i -1
if y == 0:
y=15
Solution 4:[4]
Does this work?
x = 0 # some number
for i in range(15,-1,-1):
if x == i:
y = 15 - i
print(y)
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 | Sharim Iqbal |
Solution 2 | Artyom Vancyan |
Solution 3 | thesonyman101 |
Solution 4 |