Print right-justified list of binary numbers - python-3.x

Here is the code to convert a decimal number number to binary (DectoBin), and to print a list of all binary numbers from 1 to number (print_formatted) :
def DectoBin(number):
j=1
binary = 0
while (number != 0):
reminder = number % 2
number= int(number / 2)
binary= binary + reminder * j
j *= 10
return(binary)
def print_formatted(number):
for j in range(1, number + 1):
bin1 = DectoBin(j)
print(bin1, end='\n')
Output I get :
1
10
11
100
101
110
111
1111
Output I want (right-justified list of binary numbers) :
1
10
11
100
101
110
111
1000

See PEP 498 which introduces Literal String Interpolation. You can use it to right justify your print out:
def DectoBin(number):
j=1
binary = 0
while (number != 0):
reminder = number % 2
number= int(number / 2)
binary= binary + reminder * j
j *= 10
return(binary)
for i in range(16):
print (f'{DectoBin(i):>5}')
which produces the following output:
0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110

Define print_formatted function as following. This ensures that the binary numbers are correctly right justified with the right number of spaces before each number :
import math
def print_formatted(number):
max_bits = math.ceil(math.log2(number + 1))
for j in range(1, number + 1):
bin1 = str(DectoBin(j)).rjust(max_bits)
print(bin1, end='\n')
max_bits is the number of bits used to represent number, and rjust is used to right justify the string in a string of length max_bits.

Related

Python - How to compute the value of n+nn+nnn+nnnn with a given digit as the value of n

Write a program that computes the value of n+nn+nnn+nnnn with a given digit as the value of n.
For example, if n=9 , then you have to find the value of 9+99+999+9999
I need some pointers to make this code dynamic in nature.... Kindly let me know
taking into account k terms and a value n :
(10**np.arange(k)).cumsum().sum()*n
Example
k=4
n=1
(10**np.arange(k)).cumsum().sum()*n
#1234
I assume that parameters are:
k - the number of numbers to sum (e.g. in the title of your post
there are 4 numbers to sum),
n - the digit with increasing number number of occurrences in each
number to sum.
Then the function counting such a sum can be expressed as:
def mySum(k, n):
return n * sum([ n1 * n2 for n1, n2 in zip(
[ i + 1 for i in range(k) ],
[ 10 ** (k - i - 1) for i in range(k) ])])
E.g. mySum(4, 2) gives 2468 (2 + 22 + 222 + 2222).
Details of the above case
If k == 4, but n == 1, we can break the sum into:
1 = 1
11 = 10 + 1
111 = 100 + 10 + 1
1111 = 1000 + 100 + 10 + 1
---------------------------------------------
1234 = 1000 * 1 + 100 * 2 + 10 * 3 + 1 * 4
Note that:
[ i + 1 for i in range(k) ] yields [1, 2, 3, 4],
[ 10 ** (k - i - 1) for i in range(k) ] yields [1000, 100, 10, 1],
so multiplication of these 2 zipped lists yields [1000, 200, 30, 4]
and sum of it is 1234.
Now, if n is e.g. 2, all that remains to be done is to multiply the
abobe sum just by n and this is the result.
Can try this out. Modify the range of loop as per program.
num = int(input("Enter a number: "))
t = 0
total = 0
for a in range(4):
t = num + t*10
total = total + t
print(total)

How can you find the nth digit in a fractal number

The sequence look like this 112123123412345...
If the input is 55,it should return 1,not 10. And if the input is 56,it should return 0,not 1. You got the idea.
So we have a sequence composed of the composition of
1 1 digit 1 digit total
12 2 digits 3 digits total
123 3 digits 3*(3+1)/2 = 6 digits total
1234 4 digits 4*(4+1)/2 = 10 digits total
...
123..89 9 digits 9*(9+1)/2 = 45 digits total
123..8910 11 digits 10*(10+1)/2 + 1 = 56
123..891011 13 digits 11*(10+1)/2 + 3 = 69
123..89101112 15 digits 12*(12+1)/2 + 3*(3+1)/2 = 84 digits
This is OEIS Sequence A165145 and also see the related sequence OEIS A058183.
A formula for the total number of digits is
f(n) = n*(n+1)/2 + {(n-9)*(n-8)/2 : if n>=10} + {(n-99)*(n-98)/2 : if n>=100) + ...
Some key points f(9) = 45, f(99) = 99*100/2 + 90*91/2 = 9045, f(999) = 1,395,495.
An outline algorithm for finding the k-th digit would be
Find which part of the sequence you are in n<=9, 10 <= n <= 99, 100 <= n <= 999 by comparing k with the boundary values 45, 9045, 1395495.
Recover the value of n
Find the actual digit which will be k-f(n) along sequence for the n-th number.
If we take 10 <= n <= 99 the formula for the number of digits is
n*(n+1)/2 + (n-9)*(n-8)/2
= 1/2( n^2 + n + n^2 - 17 n + 72)
= n^2 - 8 n + 36
So given 45 < k <= 9045 we solve k = n^2 - 8 n + 36, using the quadratic formula
n = ceil( ( 8 + sqrt(64 - 4 (36 - k)))/2)
We need a different quadratic formula for k outside the range.
For example take k = 100, using the formula gives n=13. There are f(12)=84 digits for all the numbers upto 12, so the first digit of the 13th string is at position 85. So we are looking for the 16th digit. We can use the formula
digit(l) := l <= 9 ? l : (l%2==0 ? floor((l+10)/20) : ((l-11)/2)%10 )
to find the actual digit, which is 1.

How to generate pyramid of numbers (using only 1-3) using Python?

I'm wondering how to create a pyramid using only element (1,2,3) regardless of how many rows.
For eg. Rows = 7 ,
1
22
333
1111
22222
333333
1111111
I've have tried creating a normal pyramid with numbers according to rows.
eg.
1
22
333
4444
55555
666666
Code that I tried to make a Normal Pyramid
n = int(input("Enter the number of rows:"))
for rows in range (1, n+1):
for times in range (rows):
print(rows, end=" ")
print("\n")
You need to adjust your ranges and use the modulo operator % - it gives you the remainer of any number diveded by some other number.Modulo 3 returns 0,1 or 2. Add 1 to get your desired range of values:
1 % 3 = 1
2 % 3 = 2 # 2 "remain" as 2 // 3 = 0 - so remainder is: 2 - (2//3)*3 = 2 - 0 = 2
3 % 3 = 0 # no remainder, as 3 // 3 = 1 - so remainder is: 3 - (3//3)*3 = 3 - 1*3 = 0
Full code:
n = int(input("Enter the number of rows: "))
print()
for rows in range (0, n): # start at 0
for times in range (rows+1): # start at 0
print( rows % 3 + 1, end=" ") # print 0 % 3 +1 , 1 % 3 +1, ..., etc.
print("")
Output:
Enter the number of rows: 6
1
2 2
3 3 3
1 1 1 1
2 2 2 2 2
3 3 3 3 3 3
See:
Modulo operator in Python
What is the result of % in Python?
binary-arithmetic-operations
A one-liner (just for the record):
>>> n = 7
>>> s = "\n".join(["".join([str(1+i%3)]*(1+i)) for i in range(n)])
>>> s
'1\n22\n333\n1111\n22222\n333333\n1111111'
>>> print(s)
1
22
333
1111
22222
333333
1111111
Nothing special: you have to use the modulo operator to cycle the values.
"".join([str(1+i%3)]*(1+i)) builds the (i+1)-th line: i+1 times 1+i%3 (thats is 1 if i=0, 2 if i=1, 3 if i=2, 1 if i=4, ...).
Repeat for i=0..n-1 and join with a end of line char.
Using cycle from itertools, i.e. a generator.
from itertools import cycle
n = int(input("Enter the number of rows:"))
a = cycle((1,2,3))
for x,y in zip(range(1,n),a):
print(str(x)*y)
(update) Rewritten as two-liner
from itertools import cycle
n = int(input("Enter the number of rows:"))
print(*[str(y)*x for x,y in zip(range(1,n),cycle((1,2,3)))],sep="\n")

Finding unique triangles given in n number of triangles in python

Given n-number of triangles, we are required to find how many triangles are unique out of given triangles. For each triangle we are given three integers a, b and c (the sides of a triangle).
A triangle is said to be unique if there is no other triangle with same set of sides.
Sample Input:
7 6 5
5 7 6
8 2 9
2 3 4
2 4 3
Sample Output:
1
Explanation:
Each line is a triangle with 3 sides given. The first two triangles are identical since they have similar sides (just the orders are different). ie. the sum of all the sides for both triangles are equal.
The third triangle '8 2 9' is unique since no other triangle has the exact similar sides. So the output is 1 (total number of unique triangles)
Sample Input:
34 5 32
15 20 6
4 2 3
5 6 9
15 20 6
34 5 32
Sample Output:
2
Here the triangles '423' and '560' are unique. So the output is 2 (total number of unique triangles)
This is what I did...
n = int(input())
arr = [list(map(int, input().split())) for x in range(n)]
def uniqueTriangle(arr):
row = len(arr)
col = len(arr[0])
mp = {}
hel = {}
for i in range(row):
tri = arr[i]
tri.sort()
strA = [str(x) for x in tri]
strB = ''
strB = strB.join(strA)
if strB not in mp.values():
mo[i] = strB
else:
hell[i] = strB
count = 0
for i in range(row):
if i in mp:
val = mp.get(i)
if val not in hel.values():
count = count + 1
print (count)
Apologize for the ugly code. But how can I make this code better?
from collections import Counter
arr = [[7, 6, 5],[5, 7, 6],[8, 2, 9],[2, 3, 4],[2, 4, 3]]
def unique_triangles(arr):
counter = Counter([frozenset(a) for a in arr])
return len([res for res in counter if counter[res] == 1])
Use frozenset to mark each unique set of triangle
use collections.Counter to count the number of unique sets found in the input array
return the set appeared only once
This is what I did :
n = int(input())
l=[]
for i in range(n):
t = [int(side) for side in input().split()]
l.append(set(t))
ans=[]
for j in l:
count=0
for i in l:
if i==j:
count+=1
if count==1:
ans.append(j)
print(len(ans))

Algorithm to generate a unique string of a certain format

I would like to generate a sequence of strings in the same format of digits and letters positions
e.g ABC12,DEV45,UED23,...
It's also required a formula to generate the next string from the current one. for example from the string above:
f(ABC12)=DEV45
f(DEV45)=UED23
I would like to use this to generate next "look-random" unique code in a defined format. What algorithm do you suggest? Thanks a lot.
A code of the format "ABC12" is basically a 5-digit number where the first 3 digits are base-26 and the last 2 digits are decimal. There are 26×26×26×10×10 or 1,757,600 of these. Each code is easily converted to the corresponding number and back:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
ABC12 = ((( 0 * 26 + 1) * 26 + 2) * 10 + 1) * 10 + 2 = 2,812
DEV45 = ((( 3 * 26 + 4) * 26 + 21) * 10 + 4) * 10 + 5 = 215,345
UED23 = (((20 * 26 + 4) * 26 + 3) * 10 + 2) * 10 + 3 = 1,362,723
2,812 / 10 = 281 rem: 2
281 / 10 = 28 rem: 1
28 / 26 = 1 rem: 2
1 / 26 = 0 rem: 1
0 / 26 = 0 rem: 0 -> 0 1 2 1 2 -> ABC12
215,345 / 10 = 21,534 rem: 5
21,534 / 10 = 2,153 rem: 4
2,153 / 26 = 82 rem: 21
82 / 26 = 3 rem: 4
3 / 26 = 0 rem: 3 -> 3 4 21 4 5 -> DEV45
1,362,723 / 10 = 136,272 rem: 3
136,272 / 10 = 13,627 rem: 2
13,627 / 26 = 524 rem: 3
524 / 26 = 20 rem: 4
20 / 26 = 0 rem: 20 -> 20 4 3 2 3 -> UED23
To loop through the numbers from 0 to 1,757,599 in a pseudo-random way, choose a step size which only returns to zero after having gone through every number, and then calculate the next value as:
x -> (x + step) % 1,757,600
So step should have no common factors with 1,757,600:
1,757,600 = 2 * 2 * 2 * 2 * 2 * 5 * 5 * 13 * 13 * 13
and preferably be greater than 26*26*10*10 so that every digit changes with every step; so, e.g.:
step = 3^11 = 177,147
which gives this sequence:
2,812 ABC12
( 2,812 + 177,147) % 1,757,600 = 179,959 -> CRF59
(179,959 + 177,147) % 1,757,600 = 357,106 -> FHJ06
...
Here's a code example to demonstrate the method. It's a bit fiddly because JavaScript. In C-like languages where a string is basically an array of integers, the code will be more straightforward.
function nextCode(current) {
var base = [26,26,26,10,10], symbol = [65,65,65,48,48], char = [], number = 0;
for (var i = 0; i < 5; i++) {
var digit = current.charCodeAt(i) - symbol[i];
number = number * base[i] + digit;
}
number = (number + 177147) % 1757600;
for (var i = 4; i >= 0; i--) {
var remainder = number % base[i];
number = (number - remainder) / base[i];
char[i] = String.fromCharCode(symbol[i] + remainder);
}
return char.join('');
}
document.write("ABC12 → " + nextCode("ABC12"));
One of the approaches is to precalculate letter part in an array form and then combine it with the consecutive numbers. For the letter array:
start with AAA, AAB, AAC, ..., ABA, ABB, ..., ZZZ (total 17576 elements) -- all possible unique combinations;
shuffle the array -- now they are in (a) random and (b) predictive order;
from any given value -> use the next element from the array.
For the digit part, use simple counting:
start with 00;
from any given value -> increment by 1;
if the result is 100, use the next letter part -- thus each string is unique.
This provides 1757600 unique strings like ABC12.

Resources