I want to reverse digits in a number in python. Here are my two implementations.
One: convert the number into string and reverse each char in it
number = 2376674032
number_s = str(number)
index = len(number_s) - 1
str_list = []
while index > -1:
str_list.append(number_s[index])
index -= 1
result = int("".join(str_list))
print(result)
Two: using simple mathematics
number = 2376674032
N = 0
K = number
R = number % 10
while K > 0:
N = N*10 + R
K = K // 10
R = K % 10
result = N
print(result)
As I'm pretty new to python programming, so could someone help me with the following questions:
with the first approach, will "".join(str_list) produce a new string with each list element? if so is a better way to concatenate strings in python(something similar to StringBuffer in java)
which of the implementations is better from performance perspective?
You can reverse a string using -1 as the step in a slice. So this works:
number = 2376674032
number_s = str(number)
reverse_s = number_s[::-1]
reversed = int(reverse_s)
you want to reverse a number …..input it as string format , and do this:
number="8374783246837"
revnumber=number[::-1]
Done
a = 1234
a = int("".join(reversed(str(a))))
This will give a = 4321
reversed functions returns an iterable object.
If we do :
a = list(reversed(str(a)))
it will return [“3”,”2″,”1″]. We have then joined it and converted into int.
To make the number an integer type, we have to use the int function, as below:
numbers=str(123456)
#or numbers="123456"
print((int(numbers[::-1])))
print((type(int(numbers[::-1]))))
output:
654321
<class 'int'>
We can do this in a single line as well using [::-1]
print(int(str(int(input()))[::-1]))
#here is my answer . you can do it using simple recursion
# count digits recursively
def reverse_digits(n):
# base case
if n == 0:
pass
#recursive case
else:
print(n%10,end='')
return reverse_digits(n//10)
# reverse 123
reverse_digits(123)
````````````````````````````````````````````````````
Related
I'm trying to count the amount of numbers that are length of 5 and has exactly two repeating numbers (where zero can be leading like 00123). What I did:
def checkNumber(num):
temp = [0] * 10
for d in map(int, str(num)):
temp[d] += 1
contains_two_unique_digits = False
for d in temp:
if d > 2:
return False
if d == 2:
if contains_two_unique_digits:
return False
contains_two_unique_digits = True
return True
counter = 0
for num in range(10000,100000):
counter += checkNumber(num)
print(counter)
But of course it does not count the cases with a leading zeros. How can I add them here? Python does not allow 001234 numbers.
The zfill method of the str type might be of help.
>>> "123".zfill(5)
'00123'
>>> "123456789".zfill(5)
'123456789'
To convert an int to a str, simply use str:
>>> str(123)
'123'
If you NEED to accept integers in python, then you are correct that no solution can be made. If you can accept a string and treat the values inside as integers, then you can definitely make it happen. A integer or float with leading zeros will always cause an error in Python.
def checkNumber(string_input):
# is it a string?
if not isinstance(string_input, str):
string_input = str(string_input)
# does it have five characters?
if not len(string_input) == 5:
raise ValueError('You must enter a string of length 5.')
counter_list = [0] * 10
# iterate over the string and count how many of each integer we have
for value in string_input:
if value.isdigit():
counter_list[int(value)] += 1
# check to see if any of them have identically two
for value_count in counter_list:
if value_count == 2:
return True
return False
print(checkNumber('01234'))
If you want to iterate over numbers by their digit representation, then itertool.product() will likely be more useful. itertools.product(string.digits, repeat=5) will yield each of the numbers you need, as digit tuples.
Taking advantage of collections.Counter can also help here, and avoids the flag / loop logic.
from collections import Counter
from itertools import product
from typing import Tuple
import string
def has_two_repeats(digits: Tuple[str, ...]):
counts = Counter(digits).values()
return (
# no digits occur more than 2 times
sum(count > 2 for count in counts) == 0 and
# one digit occcurs two times
sum(count == 2 for count in counts) == 1
)
def all_two_repeats_five_digits() -> int:
return sum(
has_two_repeats(digits)
for digits in product(string.digits, repeat=5)
)
print(all_two_repeats_five_digits())
I am practicing an algorithm on a website.
I want to add data(number) comma(,) every 3 digit.
But 'a', which variable I made, can't be the collect answer.
But 'b', which variable I searched, is the collect answer.
Can you tell me why 'a' is not the same as 'b'
length = 8
data = "12421421"
inv_result = []
for index in range(length):
if index % 3 == 0:
inv_result.append(',')
inv_result.append(str(data[index]))
else:
inv_result.append(str(data[index]))
result = inv_result[::-1]
#first comma delete
result.pop()
a = ''.join(result)
b = format(int(datas),",")
print(a)
print(b)
print(a == b)
result is
12,412,421
12,421,421
False
Your problem is that you didn't reverse the data in the beginning. The following (slightly cleaned up) code works:
length = 8
data = "12421421"
inv_data = data[::-1]
inv_result = []
for index in range(length):
if index % 3 == 0:
inv_result.append(',')
inv_result.append(str(inv_data[index]))
result = inv_result[::-1]
#first comma delete
result.pop()
a = ''.join(result)
b = format(int(data),",")
print(a)
print(b)
print(a == b)
because you are making it backwards with this line:
result = inv_result[::-1]
If you didn't reverse the order, then you would have the right order.
result = inv_result
result.pop(0) # remove first character which is a comma
But this only works if the number of digits is a multiple of three. For example, if your digits were 1234, then doing it this way would result in 123,4 instead of the desired 1,234.
So you have to reverse the string in the beginning or go through it in reverse order. Then leave the later inversion and pop() like you had it.
for index in range(length):
if index % 3 == 0:
inv_result.append(',')
inv_result.append(str(inv_data[-1-index]))# count from -1 to more negative, equivalent to going backwards through string
result = inv_result[::-1]
#first comma delete
result.pop()
A solution with comprehension:
data = "12421421"
len_data = len(data)
triplets_num = len_data // 3
remainder = len_data % 3
triplets = [data[:remainder]] if remainder else []
triplets += [data[remainder+i*3:remainder+3+i*3] for i in range(triplets_num)]
result = ','.join(triplets)
print(result)
I am trying to write my own code for generating permutation of items represented by numbers. Say 4 items can be represented by 0,1,2,3
I've seen the code from itertools product. That code is pretty neat. My way of coding this is using binary or ternary,... My code below only works for bits of less than 10. Part of this code split the str using list(s). Number 120 in base 11 is 1010, splitting '1010' yields, 1,0,1,0. For it to work correctly, I need to to split to 10, 10. Is there a way around this and still work with the rest of the code?
Alternatively, what is a recursive version for this? Thanks
aSet = 11
subSet = 2
s = ''
l = []
number = aSet**subSet
#finding all permutation, repeats allowed
for num in range(number):
s = ''
while num//aSet != 0:
s = str(num%aSet) + s
num = num//aSet
else:
s = str(num%aSet) + s
s = s.zfill(subSet)
l.append(list(s))
Indeed, the problem with using a string, is that list(s) will chop it into individual characters. You should not create a string at all, but use a list for s from the start:
aSet = 11
subSet = 2
l = []
number = aSet**subSet
#finding all permutation, repeats allowed
for num in range(number):
s = []
for _ in range(subSet):
s.insert(0, num%aSet)
num = num//aSet
l.append(s)
I tried running the following code. I tried returning value of j also but it just doesn't work.
def reverse(n):
j=0
while(n!=0):
j=j*10
j=j + (n%10)
n=n/10
print(j)
reverse(45)
Here is a program to reverse a number
def reverse(n):
v = []
for item in reversed(list(str(n))):
v.append(item)
return ''.join(v)
print(reverse("45"))
returns
54
The reverse() function creates an array, adds each digit from the input to said array, and then prints it as plain text. If you want the data from that as an integer then you can replace the return command to this at the end of the function
return int(''.join(v))
Actually, you made one mistake only: for Python 3 you need to use an integer division: n = n // 10.
Here is the correct code without str and list:
def reverse(n):
j = 0
while n != 0:
j = j * 10
j = j + (n%10)
n = n // 10
print(j)
reverse(12345)
Here is the correct code for Python 3:
import sys
def reverse(x):
while x>0:
sys.stdout.write(str(x%10))
x = x//10 # x = x/10 (Python 2)
print() # print (Python 2)
number = 45
int(str(number)[::-1])
a = 1234
a = int("".join(reversed(str(a))))
print a
This will give a = 4321
reversed functions returns an iterable object. If we do :
a = list(reversed(str(a)))
it will return [“3”,”2″,”1″]. We have then joined it and converted into int.
I am trying to write a function that return the biggest number formed by the digits from an input integer number.
So if the input = 123584
output should be = 854321
My code is -
def maxNumber(inputNumber):
x = len(str(inputNumber))
max_number = []
result= []
while(x>0):
max_number.append(inputNumber%10)
inputNumber = inputNumber/10
x -= 1
while(x<(len(str(max_number)))):
result.append(max(max_number))
x += 1
return result
print maxNumber(1238675)
and off-course the output is not as I want. Please help. I am eager to learn all possible way to do it.
def maxNumber(inputNumber):
return int(''.join(sorted(str(inputNumber), reverse=True)))
The biggest number is formed by sorting the digits in descending order. This can be achived using the rverse=True parameter to sorted():
def max_digit_permutation(n):
return int("".join(sorted(str(n), reverse=True)))
This is more reliable than most answers given so far ;-)
def max_number(n):
s = str(n)
digits = sorted(s, reverse=n>0)
return int(''.join(digits))
print max_number(231)
print max_number(-231)
print max_number(+231)
And good point - I missed the option of doing it with number alone - here it is for completeness. :)
from math import *
def max_number(n):
digit_count = int(log(abs(n+1),10)) + 1
digits = sorted([(n / 10 ** (x - 1) % 10) for x in range(digit_count,0,-1) ], reverse=True)
return reduce(lambda x, y:10*x + y, digits)
print max_number(1000)
print max_number(999)
print max_number(2345128)
print max_number(231)
sort the string of number, reverse it, join it and convert to int
>>> x=123584
>>> int(''.join(sorted(str(x))[::-1]))
854321
You could just treat the number as a list of single digits and then sort the list in decreasing order.
What about something like this:
num = str(123584)
int(''.join(sorted(num, reverse=True)))