Converting ascii text to to number and back to ascii - python

I am creating a python code which has two functions
textToNumber(t)
numberToText(n)
textToNumber(t) function takes a plain text parameter ('Hello world') and converts it to a very big number by considering ASCII values of each letter. The function looks like this:
def textToNumber (txt):
text_number = 0
for letter in txt:
text_number = (text_number * 256) + ord(letter)
return text_number
numberToText(n) takes a number and converts it to its corresponding plain text. This function is exactly opposite to the first function. It looks like this:
def numberToText (nm):
n = nm
number_text = ""
while n > 0:
part_n = int(n) & 255
number_text = chr(part_n) + number_text
n = n - part_n
n = n / 256
return number_text
So, when we use the second function within the first, it should give us the original text back. The function works fine with a small text, but gives gibberish when the text is big. I think Python has no constraint over the size of variables as long as our machine has the space. So, why does this happen? How do I solve it?
Error output:
>>> numberToText(textToNumber('Hello world'))
'Hello x\x00\x00\x00d'

Use // instead of / to get integer division.
Otherwise you get floating point numbers, and they don't have as much precision as large integers.

Related

How can I print decimal till N in python?

t=int(input())
for _ in range(t):
N=int(input())
a,b=stdin.readline().split()
z=int(a)/int(b)
x='{0:.Nf}'.format(z)
print(x)
here I want to print N decimal places of z, but I am not getting the desired result. Instead I get an error.
String interpolation doesn't work that way. The format-specifier part of the string needs to be a part of the string already -- you can't interpolate into it as part of the format function that uses it.
To do what you want, you need to create the string that will format the fraction first, and then use that.
# e.g. N = 5
fstr = "{{0:.{0}f}}".format(N)
print(fstr)
The double-braces are to "escape" the braces, i.e. you're telling Python to use it as a literal { or } instead of interpreting it as a format-string.
This gives you
{0:.5f}
Then, use fstr
# e.g. z = 22 / 7
x = fstr.format(z)
print(x)
Which gives
3.14286
Or, you can use the round() function to round z to N decimal places and then print that
You're trying to parametrically control the width of your formatting string using N, which is type int, in the middle of a string. Look at this piece of code, that hard-codes the value to 3:
thisFloat = 0.12345678
'{0:.3f}'.format(thisFloat)
and compare with this additional code:
N = 3
fstring = '{0:.'+str(N)+'f}'
fstring.format(thisFloat)
Both produce the same output because in the second example, the int N has been cast to a string.
I think here, you would have to use the round() function.
t = int(input())
for _ in range(t):
N = int(input())
a, b = stdin.readline().split()
print(round(int(a)/int(b), N))

Unicode recursion for a number

I want to get any number. e.g: 14892. And return it as 25903
(according to each character's unicode value)
This is what I have so far:
def convert(n):
if len(n)>0:
x = (chr(ord(str((int(n[0])+1)))))
return x
def convert(n):
return int(''.join([str(int(elem)+1)[-1] for elem in str(n)]))
You could use a list comprehension.
To perform this transformation, you need to get each digit and add one to it, with 10 wrapping around to 0. The simple way to do that wrapping is to use the modulus operator. We can also use integer division and modulus to extract the digits, and we can do both operations using the built-in divmod function. We store the modified digits in a list, since the simple way to combine the digits back into a single number needs the digits in reverse order.
def convert(n):
a = []
while n:
n, r = divmod(n, 10)
a.append((r + 1) % 10)
n = 0
for u in reversed(a):
n = 10 * n + u
return n
# Test
print(convert(14892))
output
25903
That algorithm is fairly close to the usual way to do this transformation in traditional languages. However, in Python, it's actually faster to do this sort of thing using strings, since the str and int constructors can do most of their work at C speed. The resulting code is a little more cryptic, but much more compact.
def convert(n):
return int(''.join([str((int(c) + 1) % 10) for c in str(n)]))
You could convert the number to a string, use the translate function to swap out the numbers, and convert back to integer again:
>>> t=str.maketrans('1234567890','2345678901')
>>> x = 14892
>>> y = int(str(x).translate(t))
>>> y
25903

how to remove middle characters in a string in python

I really do not know how to figure it out!!!
remove_middle_character("apple")
'aple'
remove_middle_character("banana")
'bana'
remove_middle_character("discount")
‘disunt‘
”“”
Since it's probably classwork, I'm not going to give you the code (which you would be unwise using anyway since your educational institution probably knows about Stack Overflow and would catch you out with plagiarism). Instead, I'll provide guidance on what you need to know.
If the string or of size two or less (we handle this early so that we don't have to worry about edge cases in the following steps), just return an empty string.
Otherwise, if the length of the string is odd, get the length x, and return the first x // 2 (the // operator is integer division) characters concatenated with the character starting at x // 2 + 1.
Otherwise, return the first x // 2 - 1 characters concatenated with the characters starting at x // 2 + 1.
In terms of turning that into code:
you can get the length of a string x with len(x);
you can get the first n characters with x[:n];
you can get the characters starting at m with x[m:];
you can concatenate strings with +; and
you can test if a value p is even by using if (p % 2) == 0 (and, of course, odd numbers will cause (p % 2) == 1 to evaluate as true).
That should be all you need to write the code yourself.
Using all the excellent suggestions above, I suggest a refactored approach where the edge conditions mentioned by paxdiablo and enhanced by mhawke are catered for but remove the need for using an if-else statement.
As you can see from paxdiablo if the string length is odd (the modulo function returns 1) the fist part of the string is:
x // 2 (subtract 0).
If the string length is even (the modulo function returns 0) the fist part of the string is:
x // 2 - 1 (subtract 1).
In both cases (odd and even length), the second part of the string is:
x // 2 + 1
So we need to subtract the reverse of what the modulo 2 of the string length would give us. We can do this by making an even length odd and an odd length even. One possible way is: mod = (len(s) + 1) % 2. So a possible solution might look like:
def remove_middle_character(s):
h = len(s)//2
mod = (len(s) + 1) % 2
return s[:h - mod] + s[h + 1:]
if __name__ == "__main__":
print(remove_middle_character(""))
print(remove_middle_character("x"))
print(remove_middle_character("xy"))
print(remove_middle_character("apple"))
print(remove_middle_character("banana"))
print(remove_middle_character("discount"))

I need help making a program in python that turns an integer into 8-bit binary

Ive been give a task, it is as follows:
write a function called decToBin that takes in an integer and converts it to an 8-bit binary number represented as a string
As I am new to this im very lost! Having no introduction to my task as thrown me off a little and I really need some help!
I have tried the following code:
#function
def decTobin(integer)
return bin
#main program
decToBin(3)
decToBin(4)
decToBin(5)
However I had no sucess, could someone point me in the right direction, it would be much appreciated, thank you!
Please try to keep your questions tidy. Also, judging from your other questions, you should look at some basic python tutorials. Happy coding!
Try to learn about base conversions. Here is a great place to find a step by step walkthrough for doing it manually.
You will need to use the modulo (%) operator. The modulo operator is a binary operator, meaning it has two inputs. You use it like so:
a % b
It returns the remainder when a is divided by b:
10 % 7 = 3
The following code will do what you need:
def decToBin(x):
if x == 0:
return "00000000"
bits = []
while x:
bits.append(str(x % 2))
x >>= 1
return "".join(bits).zfill(8)
I will explain line by line.
def decToBin(x):
This declares the function.
if x == 0:
return "00000000"
This returns a string of eight zeros if the input is zero. We need this because the while loop only operates when x is not equal to zero.
bits = []
This initializes the array of bits. During the while loop, we will add to this with the append function.
while x:
This begins a while loop, which runs until x is false (or zero).
bits.append(str(x % 2))
This adds to the bits array the remainder when x is divided by 2. str() converts it to a string.
x >>= 1
>>= 1 Shifts the bits in x to the right one time like so:
Before: 1 1 0 1 0 1
After: 0 1 1 0 1 0
It is the same as dividing by 2, without keeping the remainder.
return "".join(bits).zfill(8)
Breakdown:
"abc".join(l)
Joins all the strings in list l, separating it with abc.
"2345".zfill(i)
adds zeros to the beginning of a string until there are i numbers. So
return "".join(bits).zfill(8)
returns the array of bits as one string, and pads the beginning until there are eight characters.

Convert to different positional notation in Python 3

I'm trying to write a function that allows me to convert a number from a certain positional notation to another one of choice, from binary all the way to *hexa*trigesimal base numbers. In order to do so I first need to be able to convert my initial number (given as a string) to a decimal number to make further conversion easier.
However, my function appears to have a mistake.
What I have:
def decimal(number, base1):
number_dec = 0
val = '0123456789abcdefghijklmnopqrstuvwxyz'
if base1 != 10:
for digit in number[::-1]:
factor = val.find(digit)
for exp in range(0, len(number)):
number_dec += factor * base1 **exp
else:
number_dec = number
return number_dec
If I enter, for instance:
decimal('4d2', 16)
The function returns '5187' instead of the correct '1234'.
Where is the mistake?
You perform the entire loop for every digit:
for exp in range(0, len(number)):
number_dec += factor * base1 **exp
If you don't have to roll out your own, you could just use the built-in facility:
In [2]: int('4d2', 16)
Out[2]: 1234

Categories

Resources