I created this code because I was not able to find any functional that accomplishes my requirement.
If you can reduce it will be better.
Just enter de prefix lenght from 1 to 32 and you will get the decimal mask.
This code help me with my scripts for cisco.
import math
#Netmask octets
octet1 = [0,0,0,0,0,0,0,0]
octet2 = [0,0,0,0,0,0,0,0]
octet3 = [0,0,0,0,0,0,0,0]
octet4 = [0,0,0,0,0,0,0,0]
#POW list
pow_list = [7,6,5,4,3,2,1,0]
#Introduce prefix lenght
mask = int(input("Introduce the prefix lenght: "))
#According to the number of bits we will change the array elements from 0 to 1
while mask >= 25 and mask <= 32:
octet4[mask-25] = 1
mask -= 1
while mask >= 17 and mask <= 24:
octet3[mask-17] = 1
mask -= 1
while mask >= 9 and mask <= 16:
octet2[mask-9] = 1
mask -= 1
while mask >= 1 and mask <= 8:
octet1[mask-1] = 1
mask -= 1
#Obtain the number of ones
ones1 = octet1.count(1)
ones2 = octet2.count(1)
ones3 = octet3.count(1)
ones4 = octet4.count(1)
#Summary and reuslt of each octet.
sum1 = 0
for i in range(0,ones1):
sum1 = sum1 + math.pow(2,pow_list[i])
sum1 = int(sum1)
sum2 = 0
for i in range(0,ones2):
sum2 = sum2 + math.pow(2,pow_list[i])
sum2 = int(sum2)
sum3 = 0
for i in range(0,ones3):
sum3 = sum3 + math.pow(2,pow_list[i])
sum3 = int(sum3)
sum4 = 0
for i in range(0,ones4):
sum4 = sum4 + math.pow(2,pow_list[i])
sum4 = int(sum4)
#Join the results with a "."
decimal_netmask = str(sum1) + "." + str(sum2) + "." + str(sum3) + "." + str(sum4)
#Result
print("Decimal netmask is: "+ decimal_netmask)
Result:
Introduce the prefix lenght: 23
Decimal netmask is: 255.255.254.0
As you are probably doing more than just converting CIDR to netmask, I recommend checking out the built-in library ipaddress
from ipaddress import ip_network
cidr = input("Introduce the prefix length: ")
decimal_netmask = str(ip_network(f'0.0.0.0/{cidr}').netmask)
You can simplify your code by computing the overall mask value as an integer using the formula:
mask = 2**32 - 2**(32-prefix_length)
Then you can compute the 4 8-bit parts of the mask (by shifting and masking), appending the results to a list and then finally joining each element of the list with .:
def decimal_netmask(prefix_length):
mask = 2**32 - 2**(32-prefix_length)
octets = []
for _ in range(4):
octets.append(str(mask & 255))
mask >>= 8
return '.'.join(reversed(octets))
for pl in range(33):
print(f'{pl:3d}\t{decimal_netmask(pl)}')
Output:
0 0.0.0.0
1 128.0.0.0
2 192.0.0.0
3 224.0.0.0
4 240.0.0.0
5 248.0.0.0
6 252.0.0.0
7 254.0.0.0
8 255.0.0.0
9 255.128.0.0
10 255.192.0.0
11 255.224.0.0
12 255.240.0.0
13 255.248.0.0
14 255.252.0.0
15 255.254.0.0
16 255.255.0.0
17 255.255.128.0
18 255.255.192.0
19 255.255.224.0
20 255.255.240.0
21 255.255.248.0
22 255.255.252.0
23 255.255.254.0
24 255.255.255.0
25 255.255.255.128
26 255.255.255.192
27 255.255.255.224
28 255.255.255.240
29 255.255.255.248
30 255.255.255.252
31 255.255.255.254
32 255.255.255.255
Related
I have been using the following code to get comm port addresses from BIOS in QB45:
PRINT "Hex addresses for ports 0 to 3 from BIOS."
DEF SEG = 0
FOR x = 0 TO 3
z = &H400 + x * 2
p = PEEK(z)
q = PEEK(z + 1)
a = q * &H100 + p
PRINT " COM" + STR$(x); ": " + HEX$(a)
NEXT
DEF SEG
However when I increase FOR x = 0 to 3 into FOR x = 0 to 7 it returns x378 for 4 (which is lpt1)
and 5, 6, and 7, return 0 and I need a way to read comm ports 4, 5, 6, and 7.
I know controlpanel->devicemanager->ports can read them from resources, but I want my basic QB45
program to read them. Any help? Thanks.
I have to arrange and/or fit 2d tiles into a 2d square or rectangular plane with AI algorithm using python program. Each tile has a length and width. For example if a plane is 4x3 and set of tiles is
S={(2,3),(1,2),(2,2)}
these tiles can be rotated 90 degrees in order to fit the matrix.
input
first line contains length and width of the plane
second line number of tiles
and then the length,width of the subsequent tiles
but the inputs should be tab seperated
for eg
4 3
3
2 3
1 2
2 2
output
for eg
1 1 2 2
1 1 3 3
1 1 3 3
I have trouble solving this as i have to use only standard libraries in python no NumPy and no CSP library
~Edit 2`
my code so far I cant figure out how to add algorithm without csp library or to generate grid
from sys import stdin
a = stdin.readline()
x = a.split()
rectangular_plane = [[0] * int(x[0]) for i in range(int(x[1]))]
num_of_rectangles = stdin.readline()
r_widths = []
r_lengths= []
for l in range(int(num_of_rectangles)):
b = stdin.readline()
y = b.split()
r_lengths.insert(l,y[0])
r_widths.insert(l,y[1])
I've solved task with backtracking approach and without any non-standard modules.
Try it online!
import sys
nums = list(map(int, sys.stdin.read().split()))
pw, ph = nums[0:2]
ts = list(zip(nums[3::2], nums[4::2]))
assert len(ts) == nums[2]
if sum([e[0] * e[1] for e in ts]) != pw * ph:
print('Not possible!')
else:
def Solve(*, it = 0, p = None):
if p is None:
p = [[0] * pw for i in range(ph)]
if it >= len(ts):
for e0 in p:
for e1 in e0:
print(e1, end = ' ')
print()
return True
for tw, th in [(ts[it][0], ts[it][1]), (ts[it][1], ts[it][0])]:
zw = [0] * tw
ow = [it + 1] * tw
for i in range(ph - th + 1):
for j in range(pw - tw + 1):
if all(p[k][j : j + tw] == zw for k in range(i, i + th)):
for k in range(i, i + th):
p[k][j : j + tw] = ow
if Solve(it = it + 1, p = p):
return True
for k in range(i, i + th):
p[k][j : j + tw] = zw
return False
if not Solve():
print('Not possible!')
Example input:
4 3
3
2 3
1 2
2 2
Output:
1 1 2 2
1 1 3 3
1 1 3 3
I am doing the strStr II problem on Lintcode. For the input ("abcdef","bcd"), the output is -1, which is different from the expected value, 1. I did some debug process and found that the way I did could not get the same code value for the 'bcd' in the source and 'bcd' in the target. I just don't know what's going on.
def strStr2(self, source, target):
if source is None or target is None:
return -1
m = len(target)
if m == 0:
return 0
n = len(source)
base = 1000000
power = 1
for i in range(m - 1):
power = 26 * power % base
targetcode = 0
for i in range(m):
targetcode = (targetcode * 26 + ord(target[i]) - ord('a')) % base
if targetcode < 0:
targetcode += base
sourcecode = 0
for i in range(n):
sourcecode = (sourcecode * 26 + ord(source[i]) - ord('a')) % base
if i >= m:
sourcecode = (sourcecode - ord(source[i-m]) * power - ord('a')) % base
if sourcecode < 0:
sourcecode += base
if sourcecode == targetcode:
if source[i - m + 1, i + 1] == target:
return i - m + 1
return -1
It would seem you are trying to implement Rabin-Karp algorithm. There are a few errors in your code. Here is a commented version with the fixes.
Also, I believe you would gain efficiency by reducing hash collisions if your chose 1000000 and 26 to be prime numbers instead.
def strStr2(source, target):
# There is no need to check that source and target are not None
# Also, storing lengths as m and n only makes the code harder to read
if len(target) == 0:
return 0
base = 1000000
power = 1
for i in range(len(target)): # Your range was incorrect
power = 26 * power % base
targetcode = 0
for i in range(len(target)):
# There is no need to normalize your chars at 'a'
# That would not work for uppercase anyway
targetcode = (targetcode * 26 + ord(target[i])) % base
sourcecode = 0
for i in range(len(source)):
sourcecode = (sourcecode * 26 + ord(source[i])) % base
if i >= len(target):
# In the line below was an error in your priority of operation
sourcecode = (sourcecode - ord(source[i-len(target)]) * power) % base
# you do not need to check that sourcecode is < 0, since base is > 0
if sourcecode == targetcode:
# For slicing use : instead of , in Python
if source[i - len(target) + 1:i + 1] == target:
return i - len(target) + 1
return -1
And here are a few example to show it works.
strStr2("abcdef","bcd") # 1
strStr2("aaaabcdef","bcd") # 4
strStr2("abcdef","bcda") # -1
I am implementing the A star algorithm with the Manhattan distance for the 8 puzzle. [ The solution is in spiral form]
1 2 3
8 0 4
7 6 5
In some case, going from A to B will not take the same number of steps as going from B to A.
I think this is because it does not pick the same state on the open list, when they have the same cost, thus, not expanding the same nodes.
From
7 6 4
1 0 8
2 3 5
(A -> B)
7 6 4
1 8 0
2 3 5
(B -> A)
7 6 4
1 3 8
2 0 5
Which both have the same value using Manhattan distance.
Should I explore all path with the same value?
Or should I change the heuristic to have some kind of tie-breaker?
Here is the relevant part of the code
def solve(self):
cost = 0
priority = 0
self.parents[str(self.start)] = (None, 0, 0)
open = p.pr() #priority queue
open.add(0, self.start, cost)
while open:
current = open.get()
if current == self.goal:
return self.print_solution(current)
parent = self.parents[str(current)]
cost = self.parents[str(current)][2] + 1
for new_state in self.get_next_states(current):
if str(new_state[0]) not in self.parents or cost < self.parents[str(new_state[0])][2]:
priority = self.f(new_state) + cost
open.add(priority, new_state[0], cost)
self.parents[str(new_state[0])] = (current, priority, cost)
After wasting so much time re-writing my "solve" function many different ways, for nothing,
I finally found the problem.
def get_next_states(self, mtx, direction):
n = self.n
pos = mtx.index(0)
if direction != 1 and pos < self.length and (pos + 1) % n:
yield (self.swap(pos, pos + 1, mtx),pos, 3)
if direction != 2 and pos < self.length - self.n:
yield (self.swap(pos, pos + n, mtx),pos, 4)
if direction != 3 and pos > 0 and pos % n:
yield (self.swap(pos, pos - 1, mtx),pos, 1)
if direction != 4 and pos > n - 1:
yield (self.swap(pos, pos - n, mtx),pos, 2)
It was in this function. The last if used to be "if 4 and pos > n:"
So there were unexplored states..
2 days for a "-1"
It will teach me to do more unit testing
Can anybody help me come up with an algorithm or way to decode a number to 3 characters when they are encoded in the following manner:
Each element represents 3 alphabetic characters as in the following examples:
DOG -> (3 * 26^2) + (14 * 26) + 6 = 2398
CAT -> (2 * 26^2) + (0 * 26) + 19 = 1371
ZZZ -> (25 * 26^2) + (25 * 26) + 25 = 17575
So say I have 7446 or 3290 how would I go about converting them to text?
Try this to extract the letters in reverse order:
7446 % 26 = 10
(7446 / 26) % 26 = 0
(7446 / 26 / 26) % 26 = 11
For example:
1371 % 26 = 19 (T)
(1371 / 26) % 26 = 0 (A)
(1371 / 26 / 26) % 26 = 2 (C)
CAT
The % refers to the modulo operation. x % y gives you the remainder of the division x / y.
Modulo
input = 2398
iteration = 1
while input > 0
character = input % 26
input = input - character
input = input / 26
print character