Reversing 32bit integer - python

I was trying out a question which asked me to reverse a 32bit signed integer, I created this python program
input1=int(input("Enter the number: "))
binary=bin(input1).replace('0b','')
result=binary.zfill(32)
num=list(result)
num=num[::-1]
result=''.join(num)
ans=int(result,2)
print(ans)
This code passed one test case when the value of input1 was 2 but failed in second testcase, when the value of input1 was 1
Expected answer = -2147483648
My answer = 2147483648
What changes should I make in the code to make it pass second testcase ?

You need to look at the sign bit of the binary version of your number. You can do that by looking at the 0-indexed value of either your num variable or result.
input1 = int(input("Enter the number: "))
binary = bin(input1).replace('0b', '')
result = binary.zfill(32)
num = list(result)
num = num[::-1]
result = ''.join(num)
if num[0] == '0':
ans = int(result, 2)
else:
# flip the sign
ans = -int(result, 2)
print(ans)

input1 = int(input("Enter the number: "))
binary = bin(input1 ).replace("0b","").zfill(32)
reverse = binary[::-1]
result = int(reverse,2)
print(result if reverse[0] == "0" else -result)

Related

How to list all solutions in 24 game using Python

Recently I created a 24 game solver with python
Read this website if you do not know what the 24 game is:
https://www.pagat.com/adders/24.html
Here is the code:
from itertools import permutations, product, chain, zip_longest
from fractions import Fraction as F
solutions = []
def ask4():
num1 = input("Enter First Number: ")
num2 = input("Enter Second Number: ")
num3 = input("Enter Third Number: ")
num4 = input("Enter Fourth Number: ")
digits = [num1, num2, num3, num4]
return list(digits)
def solve(digits, solutions):
digit_length = len(digits)
expr_length = 2 * digit_length - 1
digit_perm = sorted(set(permutations(digits)))
op_comb = list(product('+-*/', repeat=digit_length-1))
brackets = ([()] + [(x,y)
for x in range(0, expr_length, 2)
for y in range(x+4, expr_length+2, 2)
if (x,y) != (0,expr_length+1)]
+ [(0, 3+1, 4+2, 7+3)])
for d in digit_perm:
for ops in op_comb:
if '/' in ops:
d2 = [('F(%s)' % i) for i in d]
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insert_point, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(insert_point, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [(term if not term.startswith('F(') else term[2])
for term in exp]
ans = ' '.join(exp).rstrip()
print("Solution found:", ans)
solutions.extend(ans)
return ans
print("No solution found for:", ' '.join(digits))
def main():
digits = ask4()
solve(digits, solutions)
print(len(solutions))
print("Bye")
main()
Right now, my code only shows one solution for the numbers given, even when there are clearly more solutions.
So if someone knows how to do this please help me
Thanks
You're not allowing the code to finish it's task before all of the solutions have been calculated and listed. Better to save the solutions in a list/array instead of returning it straight away.
Your function is returning as soon as it finds a solution. Delete the return statement. After the loop, you can return the list of all solutions if desired. To check if there were none, see if the length of the list is zero (so you know when to say there are no solutions).
I would also suggest making solutions local to solve, instead of global.

How can I use round() while forcing the digits to be as much as I firstly entered

import random
userask = float(input("enter number: "))
userask = userask + ((random.randrange(20)*userask)/random.randint(3, 100))
print("new value is " + str(userask))
Let's say my input is 123.0123
I want the program to force the new value after such operation to have the same number of digits as my initial input, rounding the result.
An example: my input is 102.31, the new value should have two digits and be rounded.
I have read round() docs but could not find something useful for this. how would you do it?
You can try this:
import random
userask = input("enter number: ")
lst = userask.split('.')
digits = 0 if len(lst)==1 else len(lst[1])
userask = float(userask)
userask = userask + ((random.randrange(20)*userask)/random.randint(3, 100))
print("new value is " + '{:.{}f}'.format(digits).format(userask))
You can do the following:
import random
import re
inp = input("enter number: ")
if '.' in inp:
num_digits = len(inp.split('.')[1])
else:
num_digits = 0
val = float(inp)
val = val + ((random.randrange(20)*val)/random.randint(3, 100))
if num_digits:
res = round(val, num_digits)
else:
res = int(val)
print("new value is " + str(res))
This code will work also for int's as well for float's, notice that the second if is not mandatory if you don't mind that your output will be printed as float, meaning that for an int it will have a 0 in the decimal place (13 -> 13.0)
Notice
You should always check the input entered to match the desired behaviour of your program, in this case you should probably check that the value entered has the proper "looks" of a number either float or int.
In this case you could do something like:
checker = re.compile('^[0-9]+.?[0-9]*$')
is_valid = bool(checker.match(inp))
and if is_valid isn't True then the value entered is problematic

Calculating average from raw_input data in a while loop

Fellow python developers. I have a task which I can't seem to crack and my tutor is MIA. I need to write a program which only makes use of while loops, if, elif and else statements to:
Constantly ask the user to enter any random positive integer using int(raw_input())
Once the user enters -1 the program needs to end
the program must then calculate the average of the numbers the user has entered (excluding the -1) and print it out.
this what I have so far:
num = -1
counter = 1
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
counter += anyNumber
answer = counter + anyNumber
print answer
print "Good bye!"
Try the following and ask any question you might have
counter = 0
total = 0
number = int(raw_input("Enter any number: "))
while number != -1:
counter += 1
total += number
number = int(raw_input("Enter another number: "))
if counter == 0:
counter = 1 # Prevent division by zero
print total / counter
You need to add calculating average at the end of your code.
To do that, have a count for how many times the while loop runs, and divide the answer at the end by that value.
Also, your code is adding one to the answer each time because of the line - answer = counter + anyNumber, which will not result in the correct average. And you are missing storing the first input number, because the code continuously takes two inputs. Here is a fixed version:
num = -1
counter = 0
answer = 0
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
counter += 1
answer += anyNumber
anyNumber = int(raw_input("Enter another number: "))
if (counter==0): print answer #in case the first number entered was -1
else:
print answer/counter #print average
print "Good bye!"
There's another issue I think:
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
The value of the variable anyNumber is updated before the loop and at the beginning of the loop, which means that the first value you're going to enter is never going to be taken in consideration in the average.
A different solution, using a bit more functions, but more secure.
import numpy as np
numbers = []
while True:
# try and except to avoid errors when the input is not an integer.
# Replace int by float if you want to take into account float numbers
try:
user_input = int(input("Enter any number: "))
# Condition to get out of the while loop
if user_input == -1:
break
numbers.append(user_input)
print (np.mean(numbers))
except:
print ("Enter a number.")
You don't need to save total because if the number really big you can have an overflow. Working only with avg should be enough:
STOP_NUMBER = -1
new_number = int(raw_input("Enter any number: "))
count = 1
avg = 0
while new_number != STOP_NUMBER:
avg *= (count-1)/count
avg += new_number/count
new_number = int(raw_input("Enter any number: "))
count += 1
I would suggest following.
counter = input_sum = input_value = 0
while input_value != -1:
counter += 1
input_sum += input_value
input_value = int(raw_input("Enter any number: "))
try:
print(input_sum/counter)
except ZeroDivisionError:
print(0)
You can avoid using two raw_input and use everything inside the while loop.
There is another way of doing..
nums = []
while True:
num = int(raw_input("Enter a positive number or to quit enter -1: "))
if num == -1:
if len(nums) > 0:
print "Avg of {} is {}".format(nums,sum(nums)/len(nums))
break
elif num < -1:
continue
else:
nums.append(num)
Here's my own take on what you're trying to do, although the solution provided by #nj2237 is also perfectly fine.
# Initialization
sum = 0
counter = 0
stop = False
# Process loop
while (not stop):
inputValue = int(raw_input("Enter a number: "))
if (inputValue == -1):
stop = True
else:
sum += inputValue
counter += 1 # counter++ doesn't work in python
# Output calculation and display
if (counter != 0):
mean = sum / counter
print("Mean value is " + str(mean))
print("kthxbye")

How do i write a basic program that asks for a number and then prints out the sum from one to the number?

What is wrong with this? I need to get it to sum negative numbers too.
Result = int(input('Enter a number: ')) M = (result) For I in range(m): Result = result + i Print(result)
Probably an indentation error, but your for loop should read,
"for i in range(m):"
not "for I in range(m):"
The print function should be in lowercase letters as well.
Python is case sensitive so make sure all of your variables are matching up.
This code works for you.
n = int(input())
result=0
for i in range(n):
print "Enter number"
num = int(input())
result+=num
print"The sum is", result
This fixes it for negative input values; it still has a problem if input is 0.
upto = int(input("Enter a number: "))
sign = abs(upto) // upto # +1 or -1
upto = abs(upto)
total = sign * sum(range(upto + 1))
print("The result is {}".format(total))

I dont understand this syntax error

I think I'm calculating the conversion from an integer to a binary number wrong. I entered the integer 6 and got back the binary number 0, which is definitely wrong. Can you guys help out? Here's the new code.
def ConvertNtoBinary(n):
binaryStr = ''
if n < 0:
print('Value is a negative integer')
if n == 0:
print('Binary value of 0 is 0')
else:
if n > 0:
binaryStr = str(n % 2) + binaryStr
n = n > 1
return binaryStr
def main():
n = int(input('Enter a positive integer please: '))
binaryNumber = ConvertNtoBinary(n)
print('n converted to a binary number is: ',binaryNumber)
main()
You forgot to call raw_input(). Right now you try to convert your prompt message to an integer which cannot work.
n = int(raw_input('Enter a positive integer please: '))
Of course a try..except around that line would be a good idea:
try:
n = int(raw_input('Enter a positive integer please: '))
except ValueError:
n = 0 # you could also exit instead of using a default value
In n = int('Enter a positive integer please: '), you are trying to make an int out of the string 'Enter a positive...'. I would assume you forgot your raw_input(). You could either do
n = int(raw_input('Enter a positive integer please: '))
or
n = raw_input('Enter a positive integer please: ')
n = int(n)
You can't cast a arbitratry string literal to an int. I think what you mean to do is call a prompt method of some sort that takes input from the user.

Categories

Resources