How can I print an output in reverse in Python? - python

A question is asking me to convert an int into binary, but it also must be in reverse (why!??!?!). After a bunch of tinkering, I was able to get it to print the number in binary. But I can't for the life of me figure out how to make it output in reverse.
The instructions say:
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary.
For an integer x, the algorithm is:
As long as x is greater than 0
Output x modulo 2 (remainder is either 0 or 1)
Assign x with x divided by 2
My code is:
x = int(input())
while x > 0:
x = x//2
print( x % 2, end = ' ')
Testing with input of 6, I get 1 1 0 but it wants me to output 011.
I even tried putting the answer into a list but when I try to reverse the list, I get an error. List method I tried:
x = int(input())
while x > 0:
x = x//2
J = [x % 2]
L = reversed(J)
print(L)
output using list method:
<list_reverseiterator object at 0x7f2cd69484f0>
<list_reverseiterator object at 0x7f2cd6948ee0>
<list_reverseiterator object at 0x7f2cd69484f0>
I feel like there's no way this needs some sort of slicing since that method hasn't even been covered yet in the material I'm learning.

You didn't follow the provided algorithm steps in the given order. Swap the statements in the while loop so they align with what was described.
And a small detail: there was no instruction to separate the output with spaces, so you should provide end = '':
x = int(input())
while x > 0:
print( x % 2, end = '')
x = x//2

You're reading in the least significant bit first, which results in the output being reversed. You don't need to make an explicit call to reversed().
This produces the desired output:
x = int(input())
result = []
while x > 0:
result.append(x % 2)
x = x // 2
# str() transforms each integer to a string.
# We then concatenate them all together
# to get the desired output using ''.join().
print(''.join(str(item) for item in result))

>>> x = 100
>>> res = []
>>> while x > 0:
... x = x//2
... J = x%2
... res.append(J)
...
>>> res
[0, 1, 0, 0, 1, 1, 0]
>>> "".join(str(i) for i in res[::-1])
'0110010'

step1 = input("what number? ")#gets your input
step2 = int(step1) #makes sure it's an int not float
step3 = bin(step2) #converts it to binairy (you method doesn't work for e.g. 7)
step4 = step3.replace("0b", "") #removes 0b from the binairy number
step5 = step4[::-1] #reveses the string
print (step5)
should work
or
print(bin(int(input("what number? "))).replace("0b", "")[::-1])
if you want in more compressed

you can use special function of python to convert integer to binary input and the print reverse of binary input by [:1:-1] in J list, so:
integer_input = int(input()) # input integert number
binary_of_integer_input = bin(integer_input) # convert integer to binary
print(binary_of_integer_input[2:]) # Print binary of integer input
print(binary_of_integer_input[:1:-1]) # Print reverse binary of integer input
Example:
integer number = 8
binary of input = 1000
reverse of binary = 0001
integer_input = int(input()) # input integert number
binary_of_integer_input = bin(integer_input) # convert integer to binary
x = binary_of_integer_input[2:]
J = binary_of_integer_input[:1:-1]
print(x) # Print binary of integer input
print(J) # Print reverse binary of integer input

I am taking This class!!!! Here's a code with materials learned so far that works! For actual Binary. Except reversing a string may not have been mentioned [::-1].
The lab wants answers per strictly that algorithm. So reversed binary and expects it to end with new line.
num = int(input())
while num > 0:
y =(num % 2)
print(y, end='')
num = (num//2)
print()
The Note: The above algorithm outputs the 0's and 1's in reverse order. If interpreted "as Convert to binary using this algorithm but reverse it"
num = int(input("Enter a number"))
string = ""
while num > 0:
y =str(num % 2)
string+=y
num = (num//2)
reverse=string[::-1]
print(reverse)

Related

What I am doing wrong? Output values below an amount

Here is the question I am working on:
Write a program that first gets a list of integers from input. The last value of the input represents a threshold. Output all integers less than or equal to that threshold value. Do not include the threshold value in the output.
For simplicity, follow each number output by a comma, including the last one.
Ex: If the input is:
50 60 140 200 75 100
the output should be:
50,60,75,
My code is:
n = int(input())
lst = []
for i in range(n):
lst.append(int(input()))
threshold = int(input())
for i in range(n):
if list[i] <= threshold:
print(last[i],end=',')
I keep getting an error, and I can't seem to know why:
ValueError: invalid literal for int() with base 10: '50 60 140 200 75 100'
This is a clean way to do this:
# import numbers separated with a space
n = input()
n = n.split(' ')
n = [int(x) for x in n] # <-- converts strings to integers
# threshold is the last number
threshold = n[-1]
# get the result
result = [x for x in n if x < threshold]
print(result)
the result:
[50, 60, 75]
The following expects one number. Not a list of them.
n = int(input())
Seems like you want to get a list of numbers through one/few prompts. Try something like the following:
n = list(map(int,input("\nEnter the numbers : ").strip().split()))[:]
So your code would look like:
n = list(map(int,input("\nEnter the numbers : ").strip().split()))[:]
lst = []
for i in range(n):
lst.append(int(input()))
threshold = int(input())
for i in range(n):
if list[i] <= threshold:
print(last[i],end=',')
Source: https://www.geeksforgeeks.org/python-get-a-list-as-input-from-user/

How to take an int, split it to digits, do some arithmetics and then append it to new int

Task:
Given an integer as input, Add code to take the individual digits and increase by 1.
For example, if the digit is 5, then it becomes 6. Please note that if the digit is 9 it becomes 0.
More examples
input: 2342 output: 3453
input: 9999 output: 0
input: 835193 output: 946204
I wrote this function but I know for sure this isn't way to write this code and I'm looking for some tips to write it in a more concise, efficient way. Please advise.
def new_num (num):
newnum = []
for i in range (0,len(str(num))):
upper = num%10
print(upper)
num = int(num/10)
print(num)
if upper == 9:
upper = 0
newnum.append(upper)
else:
upper+=1
newnum.append(upper)
strings = [str(newnum) for newnum in newnum]
a_string = "".join(strings)
an_integer = str(a_string)
new_int = int(an_integer[::-1])
return(new_int)
You could do this:-
n = '2349'
nn = ''
for i in n:
nn += '0' if i == '9' else str(int(i) + 1)
print(nn)
one of many possible improvements... replace the if/else with:
upper = (upper+1)%10
newnum.append(upper)
x= input('no = ')
x= '' + x
ans=[]
for i in x :
if int(i) == 9 :
ans.append(str(0))
else:
ans.append(str(int(i)+1))
ans=''.join(ans)
if int(ans) == 0:
ans = 0
print(ans.strip('0'))
This is the most basic code I can write, it can also be shortened to few lines
testInputs = [2342, 9999, 835193, 9]
def new_num (num):
return int("".join([str((int(d) + 1) % 10) for d in str(num)]))
result = [new_num(test) for test in testInputs]
print(result)
# [3453, 0, 946204, 0]
convert the num to string
convert the digit by using (int(d) + 1) % 10
join back the digits
parse the string as int
def newnum(x):
lis = list(str(x))
new_list = [int(i)+1 if int(i)<9 else 0 for i in lis]
new_list = map(str,new_list)
return int(''.join(new_list))
Take the number and convert to list of strings
Iterate through the list. Convert each element to int and add 1. The condition of digit 9 is included to produce 0 instead of 10
Map it back to strings and use join.
Return the output as int.

TypeError: Can't convert 'int' object to str implicitly in Fib

I have work with a Fibonacci-like sequence in Python. Then I have to sum all the digits of the resultant numbers, and then take the sum these.
This is my code:
def fibSum(n):
for x in str(n):
x, n = x, x+int(n)
print(x)
print("The sum is: " + n)
def fib(n):
total = 0
a, b = 1, 1
for i in range(0, n):
a, b = b, a+b
# print (a)
if a % 2 == 0:
total += a
print("sum = " + str(total))
return fibSum(total)
fib(10)
Line 5 presents a problem, and if I use str instead of int, it says:
x,n = x,x+ int(n)
TypeError: Can't convert 'int' object to str implicitly
We worked through your problem together on collabedit and this is the result. The confusion was that the actual problem was:
Calculate fib to the 2015th even sequence
Add only even numbers
With the final sum, sum each individual number
Here is the code:
"""
A generator that yields fib numbers
"""
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
# Instantiate the generator
f = fibonacci()
# Some vars to hold stuff
counter = 0
the_sum = 0
# Use our generator and loop
for x in f:
# Bonus points for printing
print x
# If it is an even number
if x % 2 == 0:
# Add it up
the_sum += x
# Increment counter so we don't go too far
counter += 1
# Are we there yet?
if (counter == 2015): break
# You don't want the final fib you want the sum of each
# number in the final fib
the_answer = 0
# Split the fib number into individual numbers
for n in list(str(the_sum)):
the_answer += int(n) # Add each number together
# Tada
print the_answer
A string in Python is also an array. Find the length of your numeric strings and Iterate over them adding as you go.
I would recommend not using a secondary function on your first pass. If it's a requirement get it to work then refactor.
This may be helpful
foo = '12345'
n = len(foo)
total = 0
for i in range(n):
total += int(foo[i])
print total
When you print an int, you have to convert it to a string first. Try changing the print statement to:
print("The sum is: " + str(n))
If you're trying to print something you want a str, and if you want to add something you want an int, and that + works differently for those types:
a = 1 + 2 # a=3
b = "1" + "2" # b="12"
When you do this:
x,n = x,x+ int(n)
If the second x is a string you will try to add int(n) (which is an integer) to a string, and that doesn't work. Fixing it would yield this:
>>> for x in str("12"):
... x, n = x, int(x)+int(n) # Forcing both values into numbers
... print(x)
...
1
2
>>>
N.B. I don't know if the above is your intended result. The function seems to be trying to iterate over a string, so it will break that string into an array of characters. Then, for each of those you're doing some weird tuple math with casting. This is pretty confused. To wit:
>>> for x in str(12):
... print(x)
...
1
2
>>> for x in 12:
... print(x)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
I think you either don't want to use a for loop there, or you need your input to be iterable. You may be looking for:
>>> from functools import reduce
>>> result = reduce(lambda x, y: int(x) + int(y), str(12), 0)
>>> result
3
Which would make your function:
def fibSum(n):
s = reduce(lambda x, y: int(x) + int(y), str(n), 0)
print("The sum is: " + n)
reduce (when using an addition function) is a way of accumulating a value as you iterate through it. This is equivalent to:
x = 0
for n in int_list:
x = x + n
return x

Add numbers without carrying

Lets say I have two numbers,
Number 1:
1646
Number 2:
2089
You see adding them left to right without the carry on adds up to 3625 how would I do this in python? I'm not sure but I need it to add 9+6 which is 15 but not to carry on the 1 when it adds 8+4 is there any way to add like this in python? And the end result i'm looking for is
3625
Since it doesn't carry on remaining numbers
This will work with varying N of integers of varying lengths:
from itertools import izip_longest
nums = [1646,
2089,
345]
revs = [str(n)[-1::-1] for n in nums] # nums as reversed strings
izl = izip_longest(*revs, fillvalue = '0') # zip the digits together
xsum = lambda ds: str(sum(map(int, ds)))[-1] # digits -> last digit of their sum
rres = ''.join(xsum(ds) for ds in izl) # result, but as reversed string
res = int(rres[-1::-1]) # result: 3960
Similar idea, but using map rather than izip_longest. I like this one better.
revs = [str(n)[-1::-1] for n in nums] # nums as reversed strings
dsum = lambda *ds: sum(int(d or 0) for d in ds) # str-digits -> their sum
sums = map(dsum, *revs)[-1::-1] # digit sums, in order
ones = [str(s % 10) for s in sums] # last digits of the sums
res = int(''.join(ones)) # result: 3960
Because I like to take poetic license with open-ended requests for 'more efficient':
In [49]: a,b = 1646,2089
In [50]: ''.join(str(sum(map(int,x)))[-1] for x in zip(str(a),str(b)))
Out[50]: '3625'
This will work even if the numbers of digits is not the same in both the numbers.
num1, num2, i, temp = 1646, 2089, 10, 0
total = num1 + num2
while num1 or num2:
if (num1 % 10) + (num2 % 10) > 9: temp += i
num1, num2, i = num1 // 10, num2 // 10, i * 10
print total - temp
Output
3625
The following code demonstrates what you want, but please just consider this as a hint. The var names and lack of exception handling will jeopardize your real code.
import operator
n1 = 1646
n2 = 2089
l1 = [int(x) for x in str(n1)]
l2 = [int(x) for x in str(n2)]
res1 = map(operator.add, l1, l2)
res2 = [str(x)[-1] for x in res1]
num = "".join(res2)
print int(num)
This is kind of ugly because I do not know how to index a digit in an integer, only a string, but it works.
If the two strings are always the same size:
A = str(1646)
B = str(2089)
result = ""
for i in range(0,len(A)):
result += str((int(A[i]) + int(B[i]))%10)
result = int(result)
If the two strings are not always the same size, find which one is bigger (length wise). Say the length of the biggest is X and the others length is Y where X > Y. Append the first X-Y indexes of the bigger string onto result, then repeat the above with the remaining digits.
The numbers might be different length, so convert both to strings, reverse order (makes indexing easier), reverse using extended slice ([::-1], Reverse a string in Python), reverse back,
result=""
A=str(1646)[::-1]
B=str(2089)[::-1]
for ndx in range(0,max(len(A),len(B)):
result += str(int(A[ndx])+int(B[ndx]))
resut = int(result[::-1])
You can get carry pretty easily, and handle unequal length strings (explicitly),
#!/bin/env python
a=1646
b=20893
A=str(a)[::-1]
B=str(b)[::-1]
lenA = len(A)
lenB = len(B)
length = max(lenA,lenB)
print "length: "+str(length)
#string add,no carry
total=""
for ndx in range(0,length):
digit = 0
if(ndx<lenA):
digit += int(A[ndx])
if(ndx<lenB):
digit += int(B[ndx])
digit = digit%10
#print "digit: "+str(digit)+", carry: "+str(carry)
total += str(digit)
print "a: " +str(a)+"+b: " +str(b)
result = total[::-1]
resut = int(result)
print "result: " +str(result)
#string add,with carry
total=""
carry=0
for ndx in range(0,length):
digit = carry
if(ndx<lenA):
digit += int(A[ndx])
if(ndx<lenB):
digit += int(B[ndx])
carry = digit/10
digit = digit%10
#print "digit: "+str(digit)+", carry: "+str(carry)
total += str(digit)
if(carry>0):
total += str(carry)
#print "digit: "+str(digit)+", carry: "+str(carry)
print "a: " +str(a)+"+b: " +str(b)
result = total[::-1]
resut = int(result)
print "result: " +str(result)
First convert the numbers into strings so we can iterate over the digits:
>>> n1 = str(1646)
>>> n2 = str(2089)
We can then add the corresponding digits then do %10 to get the last digit. All numbers which result from adding two integers 0-9 will be <= 18, therefore %10 will always return the last digit.
>>> [(int(a)+int(b))%10 for a,b in zip(n1,n2)]
[3, 6, 2, 5]
We then convert each int into a string, join the digits and convert back to a int:
>>> int(''.join(map(str,((int(a)+int(b))%10 for a,b in zip(n1,n2)))))
3625
Or alternatively (converting the digits as you go):
>>> int(''.join(str((int(a)+int(b))%10) for a,b in zip(n1,n2)))
3625
Use izip_longest(...,fillvalue="0") to add numbers of different lengths.

Divide number into digits and save them in list (array) using python

I want to divide number into digits and save them in list (or array) in python. So firstly I should create list like
dig = [0 for i in range(10)]
and then
i = 0
while num > 9:
dig[i] = num % 10
i += 1
num /= 10
dig[i] = num
But I don't really like just creating list for 10 spaces, is it possible to get length of number without repeating loop
i = 0
num2 = num
while num2 > 9:
num2 /= 10
i += 1
i += 1
and then repeat first part of code? Or just make as I made in first place? I don't know exact length of number but it won't be very long
So any advices? Maybe you know better way to divide numbers into digits, or maybe something else.
Since you're just adding the digits from smallest to greatest in order, just use an empty list:
dig = []
i = 0
while num > 9:
dig.append(num % 10)
i += 1
num /= 10
dig.append(num)
Alternatively, just do
dig = list(int(d) for d in str(num))
Which will turn i.e. 123 into '123' then turn each digit back into a number and put them into a list, resulting in [1, 2, 3].
If you want it in the same order as your version, use
dig = reversed(int(d) for d in str(num))
If you really just want to get the length of a number, it's easiest to do len(str(num)) which turns it into a string then gets the length.
Assuming num is a positive integer, the number of digits is equal to int(math.log10(num) + 1).
But better than that is to just use the append method of list -- then you won't have to know the length beforehand.
Even easier (though the list will be in reverse order):
dig = [int(x) for x in str(num)]
or
dig = map(int, str(num))
Although map is often said to be unpythonic, this task is definitely for it:
>>> d = 123456
>>> map(int, str(d))
[1, 2, 3, 4, 5, 6]

Categories