Reputation: 3
I'm trying to learn python with learning by doing way, but i have a problem with my code. Trying to do a code, where you input IP and code will check, if IP is in the ips.txt file, but when i add for example "192.168.0.10" and in file already is "192.168.0.100" then it will show, that "192.168.0.10" is in txt file, because "10" is part of the "100" number.
The same example is "dog" and "dogs", "dog" is basically inside "dogs", so it will tell that dog is in file...
Can you help me with it? Thanks
IPs = IPs.read()
IP = input("Check IP: ")
if IP in IPs:
print("IP is in the list.")
else:
print("IP is not in the list.") ```
Upvotes: 0
Views: 63
Reputation: 4073
IPs.read()
produces a string. This means when you perform IP in IPs
, it's checking whether the string IP
is a substring of IPs
(it performs a substring search
). In your situation, notice "" in IPs
, "1" in IPs
and ".1" in IPs
will all evaluate to True
.
What you want is IPs
to be a list of strings, which can achieved via:
IPs = IPs.read().splitlines()
This reads the input and splits the string by newlines, so if the text files contains:
192.168.0.10
192.168.0.9
192.168.0.7
IPs will be:
["192.168.0.10", "192.168.0.9", "192.168.0.7"]
So now, when you do IP in IPs
it will linear search
for the value IP
in IPs
. Linear search takes O(n)
time, where n
is the length of the list. If the order of IPs
doesn't matter and you're making a lot of lookups, I recommend turning the list into a set via IPs = set(IPs.read().splitlines())
. This way, when you do IP in IPs
, the time to lookup is constant, no matter the size of the list (aka program go zoom).
Upvotes: 1