Converting int to string then back to int - string

How do I call out a particular digit from a number. For example: bringing out 6 from 768, then using 6 to multiply 3. I've tried using the code below, but it does not work.
digits = []
digits = str(input("no:"))
print (int(digits[1] * 5))
If my input is 234 since the value in[1] is 3, how can I multiply the 3 by 5?

input() returns a string (wether or not you explicitly convert it to str() again), so digits[1] is still a single character string.
You need to convert that single digit to an integer with int(), not the result of the multiplication:
print (int(digits[1]) * 5)
All I did was move a ) parenthesis there.
Your mistake was to multiply the single-character string; multiplying a string by n produces that string repeated n times.

digits[1] = '3' so digits[1] * 5 = '33333'. You want int(digits[1]) * 5.

Related

Understanding Python sequence

I am doing a hackerrank example called Flipping bits where given a list of 32 bit unsigned integers. Flip all the bits (1->0 and 0->1) and return the result as an unsigned integer.
The correct code is:
def flippingBits(n):
seq = format(n, '032b')
return int(''.join(['0' if bit == '1' else '1' for bit in seq]), 2)
I dont understand the last line, what does the ''. part do? and why is there a ,2 at the end?
I have understood most of the code but need help in understanding the last part.
what does the ''. part do
'' represents an empty string which will be used as separator to join collection elements into string (some examples can be found here)
and why is there a ,2 at the end?
from int docs:
class int(x=0)
class int(x, base=10)
Return an integer object constructed from a number or string x
In this case it will parse the string provided in binary format (i.e. with base 2) into int.
I hope the below explanation helps:
def flippingBits(n):
seq = format(n, '032b') # change the format from base 10 to base 2 with 32bit size unsigned integer into string
return int(''.join(['0' if bit == '1' else '1' for bit in seq]), 2)
# ['0' if bit == '1' else '1' for bit in seq] => means: build a list of characters from "seq" string
# in which whenever there is 1 convert it to 0, and to 1 otherwise; then
# ''.join(char_list) => means: build string by joining characters in char_list
# without space between them ('' means empty delimiter); then
# int(num_string, 2) => convert num_string from string to integer in a base 2
Notice that you can do the bit flipping by using bit-wise operations without converting to string back and forth.
def flippingBits(n):
inverted_n = ~n # flip all bits from 0 to 1, and 1 to 0
return inverted_n+2**32 # because the number is a signed integer, the most significant bit should be flipped as well

Padding with zeros in the middle of a string?

Padding a number with leading zeros has been answered here. But in my case I have a string character followed by digits. I want to add leading zeros after the string character, but before the digits, keeping the total length to 4. For example:
A1 -> A001
A12 -> A012
A123 -> A123
I have the following code that gets me what I want, but is there a shorter way to do this without using re to split my string into text and numbers first?
import re
mystr = 'A4'
elements = re.match(r"([a-z]+)([0-9]+)", mystr, re.I)
first, second = elements.groups()
print(first + '{:0>3}'.format(second))
output = A004
You could use the following to avoid using re:
def pad_center(s):
zeros = '0' * (4 - len(s))
first, *the_rest = list(s)
return first + zeros + ''.join(the_rest)
print(pad_center('A1'))
print(pad_center('A12'))
print(pad_center('A123'))
Or, if you want to use format() you could try this:
def pad_center(s):
zeros = '0' * (4 - len(s))
first, *the_rest = list(s)
return '{}{}{}'.format(first, zeros, ''.join(the_rest))
However, I am not aware of any way to add padding to the center of a string with the format string syntax without prior processing.

Finding a number sequence in an integer

Guys heres my problem:
I am trying to read an integer from the user(e.g. 12345)
How can i check if the pattern "34" exists in the first integer?
My constraint is that i cannot convert it to string and cannot use arrays.
Here is what i managed to write to print some of the patterns that exists in 12345:
import math
int1 = int(input("input an integer: "))
#I used this to find out how many digits are in the integer
count = math.ceil(math.log10(int1))
for i in range(count):
print (int1 % (10 ** (i+1)))
for i in range(count):
print (int1 // (10 ** (i+1)))
Since this seems to be homework, I won't provide an answer, but only a rough hint.
Hint: extract each digit of the number using divmod(n, 10), which returns n without the last digit and the last digit of n. Hold the current digit and the previous digit in variables and compare them with the pattern, 34, each time a new a digit is extracted.

How compiler is converting integer to string and vice versa

Many languages have functions for converting string to integer and vice versa. So what happens there? What algorithm is being executed during conversion?
I don't ask in specific language because I think it should be similar in all of them.
To convert a string to an integer, take each character in turn and if it's in the range '0' through '9', convert it to its decimal equivalent. Usually that's simply subtracting the character value of '0'. Now multiply any previous results by 10 and add the new value. Repeat until there are no digits left. If there was a leading '-' minus sign, invert the result.
To convert an integer to a string, start by inverting the number if it is negative. Divide the integer by 10 and save the remainder. Convert the remainder to a character by adding the character value of '0'. Push this to the beginning of the string; now repeat with the value that you obtained from the division. Repeat until the divided value is zero. Put out a leading '-' minus sign if the number started out negative.
Here are concrete implementations in Python, which in my opinion is the language closest to pseudo-code.
def string_to_int(s):
i = 0
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
for c in s:
if not ('0' <= c <= '9'):
raise ValueError
i = 10 * i + ord(c) - ord('0')
return sign * i
def int_to_string(i):
s = ''
sign = ''
if i < 0:
sign = '-'
i = -i
while True:
remainder = i % 10
i = i / 10
s = chr(ord('0') + remainder) + s
if i == 0:
break
return sign + s
I wouldn't call it an algorithm per se, but depending on the language it will involve the conversion of characters into their integral equivalent. Many languages will either stop on the first character that cannot be represented as an integer (e.g. the letter a), will blindly convert all characters into their ASCII value (e.g. the letter a becomes 97), or will ignore characters that cannot be represented as integers and only convert the ones that can - or return 0 / empty. You have to get more specific on the framework/language to provide more information.
String to integer:
Many (most) languages represent strings, on some level or another, as an array (or list) of characters, which are also short integers. Map the ones corresponding to number characters to their number value. For example, '0' in ascii is represented by 48. So you map 48 to 0, 49 to 1, and so on to 9.
Starting from the left, you multiply your current total by 10, add the next character's value, and move on. (You can make a larger or smaller map, change the number you multiply by at each step, and convert strings of any base you like.)
Integer to string is a longer process involving base conversion to 10. I suppose that since most integers have limited bits (32 or 64, usually), you know that it will come to a certain number of characters at most in a string (20?). So you can set up your own adder and iterate through each place for each bit after calculating its value (2^place).

int to integer list with three pairs

how can i do this integer value is converted to integerlist with three pairs from the and of the integer
input : 24889375
output : [375,889,24]
The same way you do it with one digit, except that you divide and mod by 1000 instead of 10.
You don't list the language, so this will be pseudo code. Use the mod operator (% in The following)
First number = X % 1000;
Second Number = (X/1000)%1000;
Third Number = (X/1000000)%1000;
Note that these operations are all integer operations. The above only works if the / divide operator is an integer divide. If not, truncate it before calculating the modulo.

Resources