swap output the order of the digits - python

I have one code here
and need to change the order of the digits
import math
def sucet_cisel(number):
bla: int = 0
while number > 0:
xyzpremenna = number % 10
bla += xyzpremenna
number = (number - xyzpremenna) / 10
return bla
def digit_root(n):
if n == 0: return 0
return (n - 1) % 9 + 1
if __name__ == '__main__':
n = int(input("od čisla:"))
m = int(input("do čisla:"))
for i in range(1,m + 1):
sucet: int = math.floor(sucet_cisel(n*i))
t=(n*i)*(2)
x=' ';
print(n,"*",i,"=",n*i,(x*4),"*2","=",t,sep='')
they need to add () to this code so that in each result where there are 4 numbers they are moved
therefore print (t) need this script to run at that number
t=(ni)(2)
and the result of this to turn into this code
val = list(str(i))
digit = val.pop(-3)
new = int(''.join(val+[digit]))
od čisla:2554
do čisla:4505
2554*4505=11505770 *2=23011540
23011540
23011405
the script stops at the number I enter where is the problem?
20*1=20 *2=40
20*2=40 *2=80
20*3=60 *2=120
20*4=80 *2=160
20*5=100 *2=200
20*6=120 *2=240
20*7=140 *2=280
20*8=160 *2=320
20*9=180 *2=360
20*10=200 *2=400
20*11=220 *2=440
20*12=240 *2=480
20*13=260 *2=520
20*14=280 *2=560
20*15=300 *2=600
20*16=320 *2=640
20*17=340 *2=680
20*18=360 *2=720
20*19=380 *2=760
20*20=400 *2=800
this makes a code if I give
n = int (input ("from number:"))
m = int (input ("to number:"))
n20
m20
however, if in this script there is i
val = list (page (s))
digit = val.pop (-3)
new = int (''. join (val + [digit]))
does it calculate only one result where is the error?

Very similar to the answer from Tim Roberts, but using slices and format strings.
n = 12345678
s = str(n)
x = int(f"{s[:-5]}{s[::-1][:4]}")
s is '12345678', s[:-5] is '1234', s[::-1] is '87654321', and s[::-1][:4] is '8765'. Put it all together and x is 12348765.

OK, let's rewrite your problem to "given a number of greater than 4 digits, I want that same number but with all permutations of the last 4 digits.
import itertools
def permute(number):
val = str(number)
prefix = val[:-4]
for combo in itertools.permutations(val[-4:]):
yield int(prefix+''.join(combo))
print(list(permute(12345678)))

Related

sum of every other digit and doubling the rest

I'm working on a card number check code, for now I created a function that asks for the card number and checks if it is 8 digits or not (it has to be 8) and then calls another function that will do the math and check if the card is valid. For this function:
Starting from the rightmost digit, form the sum of every other digit. For example, if the card number is 1234 5678, then you form the sum 8 + 6 + 4 + 2 = 20
Double each of the digits that were not included in the preview step and then add all digits of the resulting numbers. For example, the digits that were not included are 7 5 3 1, we double the, 14 10 6 2, and then we sum each digit, 1 + 4 + 1 + 0 + 6 + 2 = 14
Add the sums of the two steps, 20 + 14 = 34, if the last digit is 0 then the card is valid, otherwise it is not valid (which is our case)
My problem is that I don't know how to iterate and get the sum of every other digit or double the other number which were not included in step 2. My thought was to use a while loop but then what?
EDIT: since some answers used lists... we didn't study lists yet, so I should not use it, we are only allowed to use sample stuff, loops, functions, etc.. even sum(map()) we didn't study
That is my code for now (its not much but just thought put it anyway)
def getCard():
CardInput = int(input("Enter your 8 digit credit card number: "))
if len(CardInput) == 8:
CardCheck(CardInput)
else:
print("Invalid Input: Should be exactly 8 digits!")
getCard()
def CardCheck(CardNumber):
Position = 0
Sum = 0
DoubleSum = 0
FinalSum = 0
while CardNumber >= 0:
Position += 1
So, the ugly way of doing is, you can write a for loop and use indexing for access specific elements
for i in range(len(CardInput)):
# it will iterate from 0 to 7
print(CardInput[i]) # here you get ith element
if i % 2 == 1:
print("I am other!") # you can sum your things here into another variable
Or with while:
while position < len(CardInput):
print(CardInput[position])
position += 1
It assumes CardInput is str, so I recommend to not convert it earlier.
However pythonic way would be
sum(map(int, CardInput[1::2])))
CardInput[1::2] returns list of every second element starting from second (0 is first).
map converts every element to in.
sum sums elements.
prompt = "Enter the eight-digit number: "
while True:
number = input(prompt)
if len(number) == 8 and number.isdigit():
break
prompt = "Oops, try again: "
first_digits = number[1::2] # If the user entered '12345678', this will be the substring '2468'
first_sum = sum(map(int, first_digits)) # Take each digit (character), map it to a single-digit integer, and take the sum of all single-digit integers
second_digits = number[0::2] # If the user entered '12345678', this will be the substring '1357'
doubled_ints = [int(char) * 2 for char in second_digits] # Take each digit (character), turn it into an integer, double it, and put it in a list.
second_sum = sum(map(int, "".join(map(str, doubled_ints)))) # Merge all integers in 'doubled_ints' into a single string, take each character, map it to a single digit integer, and take the sum of all integers.
total_sum = first_sum + second_sum
total_sum_last_digit = str(total_sum)[-1]
is_valid_card = (total_sum_last_digit == '0')
if is_valid_card:
print("Your card is valid (total sum: {})".format(total_sum))
else:
print("Your card is NOT valid (total sum: {})".format(total_sum))
def getCard():
CardInput = input("Enter your 8 digit credit card number: ")
if len(CardInput) == 8:
CardCheck(CardInput)
else:
print("Invalid Input: Should be exactly 8 digits!")
getCard()
def CardCheck(CardNumber):
list_CardNumber = [x for x in "25424334"]
Sum = sum(int(x) for x in list_CardNumber[1:8:-2])
DoubleSum = 2*sum(int(x) for x in list_CardNumber[0:8:-2])
FinalSum = Sum + DoubleSum
if str(FinalSum)[-1] == "0":
print("Valid Input")
else:
print("Invalid Input")
To get you started, you should check out enumerate(), it'll simplify things if you're just going to use loops by giving you easy access to both the index and value every loop.
step1 = 0
for i, x in enumerate(number):
if i % 2:
print('index: '+ str(i), 'value: '+ x)
step1 += int(x)
print('step 1: ', step1)
Output:
index: 1 value: 2
index: 3 value: 4
index: 5 value: 6
index: 7 value: 8
step 1: 20
You can use:
# lets say
CardNumber = '12345678'
# as mentioned by kosciej16
# get every other digit starting from the second one
# convert them to integers and sum
part1 = sum(map(int, CardNumber[1::2]))
# get every other digit starting from the first one
# convert them to integers and double them
# join all the digits into a string then sum all the digits
part2 = sum(map(int,''.join(list(map(lambda x: str(int(x)*2), CardNumber[0::2])))))
result = part1 + part2
print(result)
Output:
34
Edit:
Only with loops you can use:
# lets say
CardNumber = '12345678'
total_sum = 0
for idx, digit in enumerate(CardNumber):
if idx % 2 == 1:
total_sum += int(digit)
else:
number = str(int(digit)*2)
for d in number:
total_sum += int(d)
print(total_sum)
output:
34
Since you need to iterate over the digits, it's actually easier IMO if you leave it as a string, rather than converting the input to an int; that way you can just iterate over the digits and convert them to int individuall to do math on them.
Given an 8-digit long string card, it might look like this, broken into steps:
even_sum = sum(int(n) for n in card[1::2])
double_odds = (2 * int(n) for n in card[0::2])
double_odd_sum = sum(int(c) for do in double_odds for c in str(do))
All together with some logic to loop while the input is invalid:
def get_card() -> str:
"""Returns a valid card number, or raises ValueError."""
card = input("Enter your 8 digit credit card number: ")
if len(card) != 8 or not card.isdecimal():
raise ValueError("Invalid input: Should be exactly 8 digits!")
card_check(card)
return card
def card_check(card: str) -> None:
"""Raises ValueError if card checksum fails, otherwise returns None."""
even_sum = sum(int(n) for n in card[1::2])
double_odds = (2 * int(n) for n in card[::2])
double_odd_sum = sum(int(c) for do in double_odds for c in str(do))
if (even_sum + double_odd_sum) % 10:
raise ValueError("Card checksum failed!")
while True:
try:
print(f"{get_card()} is a valid card number!")
except ValueError as e:
print(e)

Binary addition program in python

I am writing a binary addition program but am unsure as to why when the inputs start with a zero the output is incorect.The output is also incorrect when the program has to add zeros to the start of one of the inputs to make them the same length.
a = input('Enter first binary number\t')
b = input('Enter second binary number\t')
carry = 0
answer = ""
length = (max(len(a),len(b))) - min(len(a),len(b))
if b > a:
a = length * '0' + a
elif a > b:
b = length * '0' + b
print(a)
print(b)
for i in range(len(a)-1, -1, -1):
x = carry
if a[i] == '1': x += 1
else: x = 0
if b[i] == '1': x += 1
else: x = 0
if x % 2 == 1: answer = '1' + answer
else: answer = '0' + answer
if x < 2: carry = 0
else: carry = 1
if carry == 1: answer = '1' + answer
print(answer)
What an excellent opportunity to explore some Boolean Logic.
Adding binary like this can be done with two "half adders" and an "or"
First of all the "Half Adder" which is a XOR to give you a summed output and an AND to give you a carry.
[EDIT as per comments: python does have an XOR implemented as ^ but not as a "word" like and not or. I am leaving the answer as is, due to the fact it is explaining the Boolean logic behind a binary add]
As python doesn't come with a XOR, we will have to code one.
XOR itself is two AND's (with reversed inputs) and an OR, as demonstrated by this:
This would result is a simple function, like this:
def xor(bit_a, bit_b):
A1 = bit_a and (not bit_b)
A2 = (not bit_a) and bit_b
return int(A1 or A2)
Others may want to write this as follows:
def xor(bit_a, bit_b):
return int(bit_a != bit_b)
which is very valid, but I am using the Boolean example here.
Then we code the "Half Adder" which has 2 inputs (bit_a, bit_b) and gives two outputs the XOR for sum and the AND for carry:
def half_adder(bit_a, bit_b):
return (xor(bit_a, bit_b), bit_a and bit_b)
so two "Half Adders" and an "OR" will make a "Full Adder" like this:
As you can see, it will have 3 inputs (bit_a, bit_b, carry) and two outputs (sum and carry). This will look like this in python:
def full_adder(bit_a, bit_b, carry=0):
sum1, carry1 = half_adder(bit_a, bit_b)
sum2, carry2 = half_adder(sum1, carry)
return (sum2, carry1 or carry2)
If you like to look at the Full Adder as one logic diagram, it would look like this:
Then we need to call this full adder, starting at the Least Significant Bit (LSB), with 0 as carry, and work our way to the Most Significant Bit (MSB) where we carry the carry as input to the next step, as indicated here for 4 bits:
This will result is something like this:
def binary_string_adder(bits_a, bits_b):
carry = 0
result = ''
for i in range(len(bits_a)-1 , -1, -1):
summ, carry = full_adder(int(bits_a[i]), int(bits_b[i]), carry)
result += str(summ)
result += str(carry)
return result[::-1]
As you see we need to reverse the result string, as we built it up "the wrong way".
Putting it all together as full working code:
# boolean binary string adder
def rjust_lenght(s1, s2, fill='0'):
l1, l2 = len(s1), len(s2)
if l1 > l2:
s2 = s2.rjust(l1, fill)
elif l2 > l1:
s1 = s1.rjust(l2, fill)
return (s1, s2)
def get_input():
bits_a = input('input your first binary string ')
bits_b = input('input your second binary string ')
return rjust_lenght(bits_a, bits_b)
def xor(bit_a, bit_b):
A1 = bit_a and (not bit_b)
A2 = (not bit_a) and bit_b
return int(A1 or A2)
def half_adder(bit_a, bit_b):
return (xor(bit_a, bit_b), bit_a and bit_b)
def full_adder(bit_a, bit_b, carry=0):
sum1, carry1 = half_adder(bit_a, bit_b)
sum2, carry2 = half_adder(sum1, carry)
return (sum2, carry1 or carry2)
def binary_string_adder(bits_a, bits_b):
carry = 0
result = ''
for i in range(len(bits_a)-1 , -1, -1):
summ, carry = full_adder(int(bits_a[i]), int(bits_b[i]), carry)
result += str(summ)
result += str(carry)
return result[::-1]
def main():
bits_a, bits_b = get_input()
print('1st string of bits is : {}, ({})'.format(bits_a, int(bits_a, 2)))
print('2nd string of bits is : {}, ({})'.format(bits_b, int(bits_b, 2)))
result = binary_string_adder(bits_a, bits_b)
print('summarized is : {}, ({})'.format(result, int(result, 2)))
if __name__ == '__main__':
main()
two internet sources used for the pictures:
https://www.electronics-tutorials.ws/combination/comb_7.html
https://www.allaboutcircuits.com/textbook/digital/chpt-7/the-exclusive-or-function-xor/
For fun, you can do this in three lines, of which two is actually getting the input:
bits_a = input('input your first binary string ')
bits_b = input('input your second binary string ')
print('{0:b}'.format(int(bits_a, 2) + int(bits_b, 2)))
And in your own code, you are throwing away a carry if on second/subsequent iteration one of the bits are 0, then you set x = 0 which contains the carry of the previous itteration.
this is how i managed to complete this, hope you find this useful.
#Binary multiplication program.
def binaryAddition(bin0, bin1):
c = 0
answer = ''
if len(bin0) > len(bin1):
bin1 = (len(bin0) - len(bin1))*"0" + bin1
elif len(bin1) > len(bin0):
bin0 = (len(bin1) - len(bin0))*"0" + bin0
#Goes through the binary strings and tells the computer what the anser should be.
for i in range(len(bin0)-1,-1,-1):
j = bin0[i]
k = bin1[i]
j, k = int(j), int(k)
if k + j + c == 0:
c = 0
answer = '0' + answer
elif k + j + c == 1:
c = 0
answer = '1' + answer
elif k + j + c == 2:
c = 1
answer = '0' + answer
elif k + j + c == 3:
c = 1
answer = '1' + answer
else:
print("There is something wrong. Make sure all the numbers are a '1' or a '0'. Try again.") #One of the numbers is not a 1 or a 0.
main()
return answer
def binaryMultiplication(bin0,bin1):
answer = '0'*8
if len(bin0) > len(bin1):
bin1 = (len(bin0) - len(bin1))*"0" + bin1
elif len(bin1) > len(bin0):
bin0 = (len(bin1) - len(bin0))*"0" + bin0
for i in range(len(bin0)-1,-1,-1):
if bin1[i] == '0':
num = '0'*len(answer)
elif bin1[i] == '1':
num = bin0 + '0'*((len(bin0)-1)-i)
answer = binaryAddition(num, answer)
print(answer)
def main():
try:
bin0, bin1 = input("Input both binary inputs separated by a space.\n").split(" ")
except:
print("Something went wrong. Perhaps there was not a space between you numbers.")
main()
binaryMultiplication(bin0,bin1)
choice = input("Do you want to go again?y/n\n").upper()
if choice == 'Y':
main()
else: input()
main()
The following adds integers i1 and i2 using bitwise logical operators (i1 and i2 are overwritten). It computes the bitwise sum by i1 xor i2 and the carry bit by (i1 & i2)<<1. It iterates until the shift register is empty. In general this will be a lot faster than bit-by-bit
while i2: # check shift register != 0
i1, i2 = i1^i2, (i1&i2) << 1 # update registers

Print reverse of a number

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.

convert following iterative code to recursive Python

6174 is known as Kaprekar's constant[1][2][3] after the Indian mathematician D. R. Kaprekar. This number is notable for the following property:
Take any four-digit number, using at least two different digits. (Leading zeros are allowed.)
Arrange the digits in descending and then in ascending order to get two four-digit numbers, adding leading zeros if necessary.
Subtract the smaller number from the bigger number.
Go back to step 2.
Dattaraya Ramchandra Kaprekar
number="0011"
print(" helo world, lets do this: " , number)
i = 0
while number != "6174":
sortedS = sorted(number)
String[] sortedString = array[4] av strangen number
reversed = sorted(number, reverse=True)
sortedIntMin = int(sortedS[0]+sortedS[1]+sortedS[2]+sortedS[3])
reversedIntMax = int(reversed[0]+reversed[1]+reversed[2]+reversed[3])
i += 1
number = str(reversedIntMax - sortedIntMin)
reversedIntMax - sortedIntMin
print("det behovdes " , i , "iterationer for processen")
This is my unsuccessful attempt
def Kaprekar(number, i):
if number == 6174:
return
elif number != 6174:
sortedString = sorted(number)
reversedString = sorted(number, reverse=True)
sortedIntMin = int(sortedString[0]+sortedString[1]+sortedString[2]+sortedString[3])
reversedIntMax = int(reversedString[0]+reversedString[1]+reversedString[2]+reversedString[3])
num = reversedIntMax - sortedIntMin
print("processen kors", num )
return 1 + Kaprekar(str(num), i)
print(" helo world, lets do this: ")
print("det behovdes " , Kaprekar("1547", 0) , "iterationer for processen")
there are three things that are wrong: -
You don't need i. remove it from function definition.
The variable you are passing is a string and you are comparing it with an integer, convert it to a string while comparing.
You need to return 1 when number='6174', while you are returning None.
Also, it can be done a bit clearer if list is joined after sorted and it can be directly converted to integer, (thanks endzior for the edit)
try this : -
def Kaprekar(number):
if number == '6174':
return 1
elif number != '6174':
sortedString = ''.join(sorted(number))
reversedString = ''.join(sorted(number, reverse=True))
sortedIntMin = int(sortedString)
reversedIntMax = int(reversedString)
num = reversedIntMax - sortedIntMin
print("processen kors", num )
return 1 + Kaprekar(str(num))
print(" helo world, lets do this: ")
print("det behovdes " , Kaprekar("1547") , "iterationer for processen")
number is a string, so in the first 2 if statements :
if number == '6174':
return 1
else:
And as in another answer i variable is not needed here.

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