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
Related
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
The task is:
Your goal is to return multiplication table for number that is always an integer from 1 to 10.
For example, a multiplication table (string) for number == 5 looks like below:
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
My code:
def multi_table(number):
for num in range(1,11):
print (str(num) + " * " + str(number) + " = " + str(num * number))
user = int(input("Your number: "))
print(multi_table(user))
Here is what comes up:
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
None should equal '1 * 5 = 5\n2 * 5 = 10\n3 * 5 = 15\n4 * 5 = 20\n5 * 5 = 25\n6 * 5 = 30\n7 * 5 = 35\n8 * 5 = 40\n9 * 5 = 45\n10 * 5 = 50'
So the online judge seems to be checking for what you return and not what you print. So why don't you try replacing the print statement with return statement in your function definition and see if it works.
def multi_table(number):
out = ""
for num in range(1,11):
out += (str(num) + " * " + str(number) + " = " + str(num * number))
return out
I tried to solve this and it work somehow. I tweak #Anand Narayanan original code and below is the new code:
def multi_table(number):
out = ""
for num in range(1,11):
out += (str(num) + " * " + str(number) + " = " + str(num * number ) + "\n")
return out.strip()
I only added the "\n" and strip method on the out string.
I am trying to create a Top 5 leaderboard for my game in Python 3.
Here's what I have
Top_Score = open("highscore.txt", "r+")
score_list = []
print(" Top 5")
print("==========")
for line in Top_Score.readlines(): # Read lines
score_list.append(line)
score_list.sort()
for i in range(5):
print("Pos", str(i + 1), ":", score_list[i])
print("==========")
Top_Score.close()
highscore.txt
50
18
20
40
50
60
70
Output
Top 5
==========
Pos 1 : 18
Pos 2 : 20
Pos 3 : 40
Pos 4 : 50
Pos 5 : 50
==========
But how can I display element in my text file if it is lesser than the range(5) without any errors? Any help would be appreciated
Example highscore.txt
50
18
20
Example Output
Top 5
==========
Pos 1 : 18
Pos 2 : 20
Pos 3 : 50
==========
In the print loop, you need to check if the size of the list is smaller than 5. If so, only loop until the size.
So, something like this:
loop_range = 5
if len(score_list) < loop_range:
loop_range = len(score_list)
for i in range(loop_range):
print("Pos", str(i + 1), ":", score_list[i])
This can be rewritten using the min function to select the smaller of the two numbers, 5 or the size:
loop_range = min(5, len(score_list))
for i in range(loop_range):
print("Pos", str(i + 1), ":", score_list[i])
I am practicing Exercise 1.17 of SICP
#+begin_src ipython :session alinbx :results output
def fast_mul(a, b):
if b == 1: return a
else:
if even(b): return 2 * fast_mul(a, b//2)
if odd(b): return a + 2 * fast_mul(a, b//2)
def even(n):
return n % 2 == 0
def odd(n):
return n % 2 == 1
print(fast_mul(3, 7))
#+end_src
#+RESULTS:
: 21
How could I see the process of expanding and contraction by adding print as
fast_mul(3,7)
3 + 2 * fast_mul(3, 3)
3 + 2 * (3 + 2 * fast_mul(3, 1))
3 + 2 * (3 + 2 * 3)
21
It sounds like you are looking for a trace, although the defaults may take some hacking to return the specific details you are looking for, eg.
python -m trace -t fast_mul.py
In elisp, default tracing is closer to your desired output, eg.
(defun fast-mul (a b)
(if (eq 1 b) a
(+ (if (evenp b) 0 a) (* 2 (fast-mul a (/ b 2))))))
(trace-function 'fast-mul)
(fast-mul 3 7)
;; 1 -> (fast-mul 3 7)
;; | 2 -> (fast-mul 3 3)
;; | | 3 -> (fast-mul 3 1)
;; | | 3 <- fast-mul: 3
;; | 2 <- fast-mul: 9
;; 1 <- fast-mul: 21
def fast_mul(a, b, s, d):
if b == 1:
print(s,a,') '*d)
return a
else:
if even(b):
print(s+f'2 * fast_mul({a}, {b//2})',') '*d)
return 2 * fast_mul(a, b//2, s+'2 * ( ',d+1)
if odd(b):
print(s+f'{a} + 2 * fast_mul({a}, {b//2})', ') '*d)
return a + 2 * fast_mul(a, b//2,s+f'{a} + 2 * ( ',d+1)
def even(n):
return n % 2 == 0
def odd(n):
return n % 2 == 1
print(fast_mul(3, 7,'',0))
I added two more parameters in the function, s and d.
s stores the string that's carried over from the previous recursion call
d stores the depth of recursion so we can figure out how many closing brackets to add to the string.
I wrote some of the code which gives me the total of the word with the position of the English alphabet but I am looking for something that prints the line like this:
book: 2 + 15 + 15 + 11 = 43
def convert(string):
sum = 0
for c in string:
code_point = ord(c)
location = code_point - 65 if code_point >= 65 and code_point <= 90 else code_point - 97
sum += location + 1
return sum
print(convert('book'))
def convert(string):
parts = []
sum = 0
for c in string:
code_point = ord(c)
location = code_point - 65 if code_point >= 65 and code_point <= 90 else code_point - 97
sum += location + 1
parts.append(str(location + 1))
return "{0}: {1} = {2}".format(string, " + ".join(parts), sum)
print(convert('book'))
Heres the output:
book: 2 + 15 + 15 + 11 = 43
More info on string.format and string.join.