How to break down a negative number into its constituents using python? - python

I have a function here which converts a number to its constituents.
def breakdown(number):
res = []
multiplier = 1
while number != 0:
digit = (number % 10)*multiplier
number = number//10
multiplier = multiplier*10
res.append(digit)
res.reverse()
return res
Example breakdown(8541) gives [8000, 500, 40, 1].
This program works fine for any positive number, but goes into an infinite loop when provided with a negative integer. Any ideas on how to make it work with any number?
Sample:
Input: breakdown(-4562) should give output: [-4000,-500,-60,-2]

The way the // operator works is that it will round DOWN the quotient. That means that the infinite loop is caused during negative numbers because it will never be 0, it will always be -1.
A potential solution to your problem is to have an if statement that checks whether or not the number is negative, and multiply the digit by -1, while performing the operations as if it were a positive number:
def breakdown(number):
if number > 0:
sign = 1
else:
number *= -1
sign = -1
res = []
multiplier = 1
while number != 0:
digit = (number % 10)*multiplier
number = number//10
multiplier = multiplier*10
res.append(digit * sign)
res.reverse()
return res

Converting my comment to an answer (pardon the silly function name, I'll let you rename them):
def breakdown_possibly_negative_number(number):
return [-x for x in breakdown(-number)] if number < 0 else breakdown(number)
where breakdown is your function. This converts the negative number to positive and takes the negation of the constituent parts while passing positive numbers through unaltered.

Related

how to divide sum of number by digit on number? [duplicate]

This question already has answers here:
Sum the digits of a number
(11 answers)
Write the digits of a number into an array
(4 answers)
Closed 4 months ago.
how to divide num of digit by digit number?
e.g : 4228 is true because 4+2+2+8=16 can divide by 4, 2, 8
3425 false because 3+4+2+5=14 can't divide by 3, 4, 2, 5
numbers = int(input('input number : '))
result = 0
# NUM of digit
while numbers > 0 :
digit = numbers % 10
result = result + digit
numbers = numbers // 10
factors = result
#factors of "NUM of digit"
for factor_result in range(1,factors + 1) :
if factors % factor_result == 0 :
print(factor_result)
please help me;(
thank you a lot:))
A simple way to do it is to calculate the sum of the digits then check if the modulo is 0.
In python, we could parse the number to a str, then convert every digit (which is a single char) back to an int and create a list of these digits
input_numbers = int(input('input number : '))
# parse the number to a str, then map each char back to an integer
# and create a list of int for each digit
numbers = list(map(int, str(input_numbers )))
Now, just use the built-in sum() method to get the result you wish. The next part is just a loop over every digit on the numbers list and check the module.
result = sum(numbers)
is_divisible = True
for number in numbers:
if number == 0 or result % int(number) != 0:
is_divisible = False
print(is_divisible)
From your description it sounds like you want a function like this
# determine if sum of integers comprising an integer is divisible by its part
def divisor_check(num):
# check that input num is integer
if not isinstance(num,int):
print('warning: input is not an integer')
return False
# break num into component integers by convert to string first
stringafied_num = str(num)
# split the string-afied num to get component integers
components = [*stringafied_num]
# evaluate the components to get integers back
components = [eval(v) for v in components]
# sum components
total=sum(components)
# try dividing total by each component
for c in components:
if total%c != 0:
return False
return True
This function breaks up the input into its component integers, sums them, and computes the desired divisor check.
If you evaluate this function for your examples you get the desired results
divisor_check(4228) --> True
divisor_check(3425) --> False
num = 4220
res = [int(x) for x in str(num)]
can_devided = True
for r in res:
if r == 0:
continue
if sum(res) % r != 0:
can_devided = False
print (can_devided)

Reversing an integer using recursion in Python

While practicing recursion I came across a question to reverse an integer using recursion. I tried to do the question without converting the integer into a string.
I was able to solve the question partially but the output would always come without any of the zeroes from the original input. Below is the code I came up with:
def reverseNumber(n):
if (n//10) == 0:
return n
lastDigit = n%10
ans = reverseNumber(n//10)
nod = 0
for i in str(ans):
nod += 1
return (10**nod)*lastDigit + ans
Upon inspection I could see that this was happening because when lastDigit is 0 it only returned the reversed integer from the recursive call i.e input 4230 will give 324.
But this also meant that all zeroes between the original input would also get removed as we went deeper in the recursive calls.
So please tell me how to modify this code so that zeroes in the original input are not removed while reversing.
You probably need just this:
def rev(n):
if n>0:
return str(n%10)+rev(n//10)
else:
return ''
reverseNumber should return an int and accept positive and negative numbers.
The simplest way to fix your code, without handling negative numbers, is:
def reverseNumber(n):
if n == 0:
return 0
lastDigit = n%10
n //= 10
return int(str(lastDigit) + str(reverseNumber(n))) if n else lastDigit
for test in (0, 123, 120):
print(test, reverseNumber(test))
Prints:
0 0
123 321
120 21
Yes! The reverse of 120 is 21 when you are dealing with int types as opposed to str types.
Another implementation that does handle negative numbers takes a whole different approach:
I have broken this out into two functions. Function rev is a generator function that assumes that it is being called with a positive, non-negative number and will recursively yield successive digits of the number in reverse. reverseNumber will join these numbers, convert to an int, adjust the sign and return the final result.
def reverseNumber(n):
def rev(n):
assert n >= 0
yield str(n % 10)
n //= 10
if n != 0:
yield from rev(n)
if n == 0: return 0 # special case
x = int(''.join(rev(abs(n))))
return x if n >= 0 else -x
tests = [0, 132, -132, 120]
for test in tests:
print(test, reverseNumber(test))
Prints:
0 0
132 231
-132 -231
120 21
For all non-negative n, when n < 10 it is a single digit and already the same as its reverse -
def reverse(n = 0):
if n < 10:
return str(n)
else
return str(n%10) + rev(n//10)
you can also try the following Python3 code. It will cover positive and negative integers to be reversed as integers - not as strings ...
x = int(input("What integer shall be reversed? "))
n = abs(x) # ... to handle negative integers
r = 0 # ... will hold the reversed int.
while n > 0: # Recursion part reversing int.
r = (r * 10) + (n % 10) # using '%' modulo
n = int(n / 10) # and a 'dirty way' to floor
if x < 0: # Turn result neg. if x was neg.
return (r * -1)
else:
return r # Keep result pos. if x was pos.
This approach will leave your zeros in the middle of the integer intact, though it will make any zero at the end of the initial number vanish - rightfully so as integers do not start with a zero. ;))

Squaring every integer in a number in the same order as number

x = int(input('num: '))
result = 0
power = -1
while x != 0:
digit = x % 10
digit = digit**2
if digit > 9:
power += 2
else:
power += 1
result = result + digit * (10**power)
x //= 10
print(result)
Basically, I want to square every digit in an integer. For example, 984 should be 816416 or 405 should be 16025.
The interesting thing is that if I write result = result + digit * (10**power) on the eighth line and make the power = 0, then I get the correct result. However, it sounds illogical to me because I think that we should first decide whether digit > 9 or not. I mean, writing result = result + digit * (10**power) before the if statement is weird to me. So, could the code I shared work by editing some parts in this form? If not, could you explain why I should write it on the eighth line?, thanks.
Here the problem is that you are squaring your digit variable before the if condition which will fail if your digit is any value less than 10. For example, for just number 4, your value of digit variable will be 16 and thus power will be 1 and your result would be 160 then.
And you need to have it at the eight line before the if statement because, the if statements determine your power variable and your value wont shift and add to the result variable instead. For example - for 45 you would want the output to be 1625, but if you call the statement before the if condition, the power will be 0 and thus you will get a result of 185(25+160) instead of 1625.
x = int(input('num: '))
result = 0
power = 0
while x != 0:
digit = x % 10
digit2 = digit**2
result = result + digit2 * (10**power)
if digit2 > 9:
power += 2
else:
power += 1
x //= 10
print(result)
This should work.
Alternatively, you can directly manipulate the nature of input number is indeed a string, which you can start working on:
>>> squares = [int(x)*int(x) for x in input('Enter a number: ')]
Enter a number: 984
>>> squares
[81, 64, 16]
>>> result = int(''.join(map(str, squares)))
>>> result
816416

Validate Credit Card Number Using Luhn Algorithm Python

I am trying to implement Luhn algorithm in Python. Here is my code
def validate(n):
if len(str(n)) > 16:
return False
else:
if len(str(n)) % 2 == 0:
for i in str(n[0::2]):
digit = int(str(n[i])) * 2
while digit > 9:
digit = sum(map(int, str(digit)))
dig_sum = sum(map(int, str(n)))
return True if dig_sum % 10 == 0 else False
elif len(str(n)) % 2 != 0:
for i in str(n[1::2]):
digit = int(str(n[i])) * 2
while digit > 9:
digit = sum(map(int, str(digit)))
dig_sum = sum(map(int, str(n)))
return True if dig_sum % 10 == 0 else False
I keep getting the error
TypeError: 'int' object has no attribute '__getitem__
Following is python implementation of Lunh Algorith to detect a valid credit card number. Function takes a number as string and return whether its valid credit card or not.
Its based on the steps mentioned in the following link: https://www.codeproject.com/Tips/515367/Validate-credit-card-number-with-Mod-algorithm
Step 1 - Starting with the check digit double the value of every other digit (right to left every 2nd digit)  
Step 2 - If doubling of a number results in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers.
Step 3 - Now add the un-doubled digits to the odd places
Step 4 - Add up all the digits in this number
If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid. 
def luhn(ccn):
c = [int(x) for x in ccn[::-2]]
u2 = [(2*int(y))//10+(2*int(y))%10 for y in ccn[-2::-2]]
return sum(c+u2)%10 == 0
#Test
print(luhn("49927398716"))
It is hard to tell without the complete error message, but it is likely because you confused in some places where you put the indexing and where you put the string conversion, for example: for i in str(**n[1::2]**) and digit = int(str(**n[i]**)) * 2
A good way to handle it is to just create a temporary variable n_str = str(n), and use it instead of str(n) over and over again.

Luhn checksum method; separating two digits and finding the sum of that list

I am currently trying to use the luhn method to determine whether a credit card is valid or not in python and here is what I have so far:
print('What is your Credit Card number? :) (please put a space between each number)')
a = [int(x) for x in input().split()]
lengthy = len(a)
print(lengthy)
a.reverse()
print(a)
listx2 = []
listx1 = []
for x in range(len(a)):
modulus = x % 2
print(x, a[x])
if modulus != 0:
listx2.append(a[x]*2)
else:
listx1.append(a[x])
print(listx2)
print(listx1)
I don't know how to do the next step which is getting the sum of all of the digits of the numbers multiplied by two.(listx2) I have looked at different programs with the luhn method but I just can't seem to pick that part out. Thanks!
This is my interpretation of the Luhn algo.
def luhn(sequence):
digits = [int(digit) for digit in str(sequence)] # converts a full string of nums to a list comp of individual numbers
odd = digits[-1::-2] # string stepping (-1) indicates last item in list (-2) means to travel back another 2
even = digits[-2::-2]
checksum = 0
checksum += sum(odd)
evenmod = []
for digit in even:
if digit * 2 > 9:
digit = digit * 2
digit = int(str(digit)[0]) + int(str(digit)[1])
else:digit = digit * 2
evenmod.append(digit)
checksum += sum(evenmod)
if checksum % 10 == 0:
return True
else:
return False
print luhn(378282246310005)
print luhn(111111111111111)
print luhn(4751290083628479)
print luhn(5573485043994670)
Separate the even and the odd indeces to separate lists, then use a for statement to loop through the list, multiplying the list entries by two.
Notice the if statement that catches the issue with (e.g) 8 * 2 = 16.
Use sum:
summed_x2 = sum(listx2)

Categories

Resources