patternpythonMinor
Linear Probing in Python
Viewed 0 times
probinglinearpython
Problem
About to get back into coding, so I implemented linear probing in Python. How did I do? Anything unnecessary? Am I using "global" right? I originally wanted to use an array with a fixed length, but couldn't get it to work.
list = ["x", "x", "x", "x", "x", "x", "x"]
state = 0
def main():
#tests
linearProbing(1)
linearProbing(1)
linearProbing(1)
print(list)
def linearProbing(x):
global state
global list
c = x % len(list)
while state != 1:
if list[c] == "x":
list[c] = x
state = 1
elif c == 0:
c = len(list) - 1
else:
c -= 1
state = 0
if __name__ == '__main__':
main()Solution
Am I using "global" right?
It would be better to not use
by wrapping this in a class,
with
so an instance could reference them with
How did I do?
So it should be a boolean value,
set to
as it shadows a built-in with the same name.
A quick tip: you can write
In any case, duplicating
It would be better to put the value
and reuse that everywhere.
It would be better to not use
global at all,by wrapping this in a class,
with
state and list as attributes,so an instance could reference them with
self.state, for example.How did I do?
state is used as a boolean.So it should be a boolean value,
set to
False instead of 0 and True instead of 1 values.list is not a good name for a variable,as it shadows a built-in with the same name.
A quick tip: you can write
["x", "x", "x", "x", "x", "x", "x"] simpler as ["x"] * 7.In any case, duplicating
"x" in multiple places (first when you initialize list, and then later in linearProbing), is not great.It would be better to put the value
"x" in a variable, say FREESPOT = "x",and reuse that everywhere.
Context
StackExchange Code Review Q#91734, answer score: 3
Revisions (0)
No revisions yet.