Find the biggest number formed by digits of input numer - python

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)))

Related

How to capture the first digit while converting a decimal number to binary digit using naive recursion?

I am trying to convert a decimal number to a binary digit in the below way using recursion.
def getbin(x: int, s: str):
if int(x/2) > 0:
y = int(x/2)
s += str(y % 2)
print(f'int(x/2): {int(x/2)}, y: {y}, st: {s}')
getbin(y, s)
elif int(x/2) == 1:
s += '11'
return s
if __name__ == '__main__':
print(getbin(28, ''))
But when I call this, I can see in the output that the first digit of the binary number is not getting captured.
I ran two test cases:
For the number 28, the expected output should be 00111 but the output is 0111:
For the number 5, the output should be 101 but the output is 01
Could anyone let me know what is the mistake I am making here and how can I correct it ?
Your problem is that you are testing against x/2 instead of testing against x. Thus you lose the most significant bit of the result. Try something like this:
def getbin(x: int, s: str):
s += str(x % 2)
y = x // 2
if y > 0:
return getbin(y, s)
return s
Note also that you need to reverse the result of getbin to get the correct binary string.

Reverse digits in a number

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)
````````````````````````````````````````````````````

How to split a returned integer: (Trying to find recurrences within it)

This might be a very simple question, but it's giving me a lot of trouble.
Code:
def search_likes(passed_list): #passed_list contains links to find below
print("Found",len(passed_list),"videos, now finding likes.")
x = 0
print("Currently fidning likes for video",x,".")
while x< len(passed_list):
likeFINDER = []
r = requests.get(passed_list[0])
soup= BeautifulSoup(r.content, 'lxml')
d_data = soup.find_all("span", {"class": "yt-uix-button-content"}) #Location of the number i'm looking for
likeFINDER.append(d_data)
str1= ''.join(str(e) for e in likeFINDER) #Converts the list into a string
likeNUMBER= (int(''.join(list(filter(lambda x: x.isdigit(), str1))))) #Removes string and leaves integers
x+=1 #count
Output:
845528455314391440
I would like to split the code where it begins to repeat itself. Ie ['84552','8455314391440']
If you have any insight on how to do this I would really appreciate it!
Thanks,
Ben
Given a string s containing your numbers, and a number n that is the size of the repetition you want to find, then you can do:
s.find(s[:n], n)
This finds the index of the first occurrence, after the start of the string, that is equal to the first n characters of the string. For example:
s = str(845528455314391440)
n = 3
r = s.find(s[:n], n)
print(r)
Output:
5
You can then use that to split the string and turn the parts into numbers:
a, b = int(s[:r]), int(s[r:])
print(a, b)
Output:
84552 8455314391440
All combined into a function, accounting for numbers without repitition:
def split_repeat(i, n):
s = str(i)
r = s.find(s[:n], n)
if r == -1:
return None
else:
return int(s[:r]), int(s[r:])
Usage:
print(split_repeat(845528455314391440, 3))
print(split_repeat(876543210, 3))
print(split_repeat(1122, 3))
Output:
(84552, 8455314391440)
None
None
Here is a simple example that will show yo how you can match the numbers of how ever many of the first few digits you need to. This example will use the first 2 digits.
we can turn the numbers into strings then use string_name[:2] where 2 is the number of digits from the front you want to match. I am using the number 11 to match my list of numbers but this is only for an example.
Let me know if you have any question:
set_list = []
var1 = 11012314
for i in range(1000):
set_list.append(i)
for item in set_list:
x = str(item)
y = str(var1)
if x[:2] == y[:2]:
print(item)
When you run this code you will see numbers printed to the console that match the first two digits to our variable with the value 11.
you can do :
def myfunc(num):
a=str(num)
for i in range(len(a)):
l1=a[:i]
l2=a[i:]
if l1 in l2:
b=l1
return [int(b), int(a[len(b):])]
that will give you :
>>> myfunc(845538455314391440)
[84553, 8455314391440]

numerology .. how to shorten code..?

I have written this code for finding the numerological value of a name. Is there any way in which i can shorten the code, or nest one loop inside the other?
alphabets = {"A":1,"I":1,"J":1, "Q":1,"Y":1,"B":2,"K":2,"R":3,"C":3,"G":3,"L":3,"S":3,"D":4,"M":4,"T":4,"H":5,"E":5,"N":5,"X":5,"U":6,"V":6,"W":6,"O":7, "Z":7,"P":8,"F":8}
word =input("your numerology score is :") #since i am using python 3 to code this
def digit_sum(n):
#prepare a list of numbers in n convert to string and reconvert
numbers=[]
for digit in str(n):
numbers.append(int(digit))
# add up the total of numbers
total=0
for number in numbers:
total += number
return total
def numerology(word):
total = 0
for letter in word.upper():
total += alphabets[letter]
total = digit_sum(total)
return total
print (numerology(word))
To understand what is meant by numerological value, please see https://en.wikipedia.org/wiki/Numerology#Latin_alphabet_systems.
alphabets = {"A":1,"I":1,"J":1, "Q":1,"Y":1,"B":2,"K":2,"R":3,"C":3,"G":3,"L":3,"S":3,"D":4,"M":4,"T":4,"H":5,"E":5,"N":5,"X":5,"U":6,"V":6,"W":6,"O":7, "Z":7,"P":8,"F":8}
name = "this is a sample name"
digits = str(sum([alphabets[l] for l in name.upper() if l in alphabets.keys()]))
numerological_value = int(digits) % 9
if numerological_value == 0:
numerological_value = 9
print(numerological_value)
Comprehensions allow you to have a short hand for creating various data types.
In this case you want to build generators.
This is as you don't need to build every number before reducing the list, to a single number.
Wrapping one in sum can allow you to significantly shorten digit_sum. Which can become:
def digit_sum(n):
return sum(int(digit) for digit in str(n))
You can also change numerology to be a little shorter, if you combine the addition and assignment.
def numerology(word):
total = 0
for letter in word.upper():
total = digit_sum(total + alphabets[letter])
return total
If you want, you can use functools.reduce to make this span a total of six lines.
def numerology(word):
return functools.reduce(
lambda a, b: sum(int(digit) for digit in str(a + b)),
(alphabets[letter] for letter in word.upper()),
0
)
One-liner for laughs.
alphabets = {"A":1,"I":1,"J":1, "Q":1,"Y":1,"B":2,"K":2,"R":3,"C":3,"G":3,"L":3,"S":3,"D":4,"M":4,"T":4,"H":5,"E":5,"N":5,"X":5,"U":6,"V":6,"W":6,"O":7, "Z":7,"P":8,"F":8}
print("Your numerology score is "+ str((int(sum([alphabets[l] for l in input("Type your name:").upper() if l in alphabets.keys()])) % 9) or 9))
this one !!!
a= input()
b= 0
c= len(a)
d= {"a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9, "j":10, "k":11, "l":12, "m":13, "n":14, "o":15, "p":16, "q":17, "r":18, "s":19, "t":20, "u":21, "v":22, "w":23, "x":24, "y":25, "z":26, " ":0}
for i in range(c):
b= b+d[a[i]]
print(b)
gematria
i'm sure you can chain the reducer functions a bit better but...
const charMap = {A:1, J:1, S:1, B:2, K:2, T:2, C:3, L:3, U:3, D:4,
M:4, V:4, E:5, N:5, W:5, F:6, O:6, X:6, G:7, P:7, Y:7, H:8,
Q:8, Z:8, I:9, R:9};
let name = prompt ("Type your name in CAPS"); //for example: TOM
let wordScore = Array.from(name).reduce((nameScore, element) => {
let curValue = charMap[element]
return (nameScore + curValue)
},0)
let finalScore = Array.from(String(wordScore), Number).reduce((score, element) => {
return score > 10 ? score + element : score
})
alert(finalScore)

How to reverse an int in python?

I'm creating a python script which prints out the whole song of '99 bottles of beer', but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.
This is my full script,
def reverse(str):
return str[::-1]
def plural(word, b):
if b != 1:
return word + 's'
else:
return word
def line(b, ending):
print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)
for i in range(99, 0, -1):
line(i, "of beer on the wall")
line(i, "of beer"
print reverse("Take one down, pass it around")
line(i-1, "of beer on the wall \n")
I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.
Without converting the number to a string:
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
You are approaching this in quite an odd way. You already have a reversing function, so why not make line just build the line the normal way around?
def line(bottles, ending):
return "{0} {1} {2}".format(bottles,
plural("bottle", bottles),
ending)
Which runs like:
>>> line(49, "of beer on the wall")
'49 bottles of beer on the wall'
Then pass the result to reverse:
>>> reverse(line(49, "of beer on the wall"))
'llaw eht no reeb fo selttob 94'
This makes it much easier to test each part of the code separately and see what's going on when you put it all together.
Something like this?
>>> x = 123
>>> str(x)
'123'
>>> str(x)[::-1]
'321'
best way is
x=12345
a=str(x)[::-1]\\ In this process i have create string of inverse of integer (a="54321")
a=int(a) \\ Here i have converted string a in integer
or
one line code is
a=int(str(x)[::-1]))
def reverse(x):
re = 0
negative = x < 0
MAX_BIG = 2 ** 31 -1
MIN_BIG = -2 ** 31
x = abs(x)
while x != 0:
a = int(x % 10)
re = re * 10 + a
x = int(x // 10)
reverse = -1 * re if negative else re
return 0 if reverse < MIN_BIG or reverse > MAX_BIG else reverse
this is for 32 - bit integer ( -2^31 ; 2^31-1 )
def reverse_number(n):
r = 0
while n > 0:
r = (r*10) + (n % 10)
print(r)
r *=10
n //= 10
return r
print(reverse_number(123))
You can cast an integer to string with str(i) and then use your reverse function.
The following line should do what you are looking for:
def line(b, ending):
print reverse(str(b)) or reverse('No more'), plural(reverse('bottle'),reverse(str(b))), reverse(ending)
Original number is taken in a
a = 123
We convert the int to string ,then reverse it and again convert in int and store reversed number in b
b = int("".join(reversed(str(a))))
Print the values of a and b
print(a,b)
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
This code will not work if the number ends with zeros, example 100 and 1000 return 1
def reverse(num):
rev = 0
while(num != 0):
reminder = num % 10
rev = (rev * 10 ) + reminder
num = num // 10
print ("Reverse number is : " , rev )
num=input("enter number : ")
reverse(int(num))
#/ always results into float
#// division that results into whole number adjusted to the left in the number line
I think the following code should be good to reverse your positive integer.
You can use it as a function in your code.
n = input() # input is always taken as a string
rev = int(str(n)[::-1])
If you are having n as integer then you need to specify it as str here as shown. This is the quickest way to reverse a positive integer
import math
def Function(inputt):
a = 1
input2 = inputt
while(input2 > 9):
input2 = input2/10
a = a + 1
print("There are ", a, " numbers ")
N = 10
m = 1
print(" THe reverse numbers are: ")
for i in range(a):
l = (inputt%N)/m
print(math.floor(l), end = '')
N = N*10
m = m*10
print(" \n")
return 0
enter = int(input("Enter the number: "))
print(Function(enter))
More robust solution to handle negative numbers:
def reverse_integer(num):
sign = [1,-1][num < 0]
output = sign * int(str(abs(num))[::-1])
An easy and fast way to do it is as follows:
def reverse(x: int|str) -> int:
reverse_x = int(''.join([dgt for dgt in reversed(num:=str(x)) if dgt != '-']))
if '-' in num:
reverse_x = -reverse_x'
return reverse_x
First we create a list (using list comprehension) of the digits in reverse order. However, we must exclude the sign (otherwise the number would turn out like [3, 2, 1, -]). We now turn the list into a string using the ''.join() method.
Next we check if the original number had a negative sign in it. If it did, we would add a negative sign to reverse_x.
Easily you can write this class:
class reverse_number:
def __init__(self,rvs_num):
self.rvs_num = rvs_num
rvs_ed = int(str(rvs_num)[::-1])
print(rvs_ed)
You can use it by writing:
reverse_number(your number)
I have written it in a different way, but it works
def isPalindrome(x: int) -> bool:
if x<0:
return False
elif x<10:
return True
else:
rev=0
rem = x%10
quot = x//10
rev = rev*10+rem
while (quot>=10):
rem = quot%10
quot = quot//10
rev = rev*10+rem
rev = rev*10+quot
if rev==x:
return True
else:
return False
res=isPalindrome(1221)

Categories

Resources