I'm having an issue with this piece of code I wrote. I'm trying to convert an integer input and print an output with its equivalent in binary base. For example for 5 it should drop an output of '101' however it just prints '10' like if it doesn't take into account the last digit. Please any comments would be greatly appreciated
T = raw_input()
for i in range(0, int(T)):
n = raw_input()
dec_num = int(n)
cnv_bin = ''
while dec_num//2 > 0:
if dec_num%2 == 0:
cnv_bin += '0'
else:
cnv_bin += '1'
dec_num = dec_num//2
print cnv_bin[::-1]
while dec_num//2 > 0:
should be:
while dec_num > 0:
The first time through the loop, 5//2==2, so it continues.
The second time through the loop, 2//2==1, so it continues.
The third time, 1//2==0 and the loop quits without handling the last bit.
Also, you can just do the following to display a number in binary:
print format(dec_num,'b')
Format string version:
print '{0} decimal is {0:b} binary.'.format(5)
Why not use the build-in function bin()?
eg:
bin(5)
output
0b101
If you don't want the prefix(0b), you can exclude it.
bin(5)[2:]
hope to be helpful!
import math
def roundup(n):
return math.ceil(n)
D = eval(input("Enter The Decimal Value: "))
n = roundup(math.log2(D+1))-1
bi = 0
di = D
qi = 0
i = n
print("Binary Value:",end = " ")
while(i>=0):
qi = math.trunc(di/2**i)
bi = qi
print(bi,end = "")
di = di - bi*(2**i)
i = i-1
Related
I need to replace temperature values in list depends on negative/positive and get rid of float at the same time. I.e. value '-0.81' should be '-1' (round) or '0.88' should be '1'.
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
for i in range (len(myList)):
if myList[i][0] == '-' and int(myList[i][-2]) > 5:
do sth...
At the end I need new list with new values. Thank you for any tips.
Your code is already almost there. It's not necessary to reference the elements by index.
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
for i in myList:
if i[0] == '-' and int(i[-2]) > 5:
do sth...
If all you want to do is rounding then you can use a list comprehension.
roundlist = [round(float(i)) for i in myList]
You could parse the string into number, check for rounding (whether the decimal is higher or lower than 0.5), and convert it back to string
import math
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
result = [0] * len(myList)
for i in range (len(myList)):
num = float(myList[i])
if num - math.floor(num) < 0.5:
result[i] = str(math.floor(num)) # round down
else:
result[i] = str(math.ceil(num)) # round up
print(result)
I want to make this program do the summation of something with their input. My code thus far
def summation():
start = int(raw_input("Start value of n?: "))
end = int(raw_input("End value of n?: "))
eqn = lambda n: raw_input("Equation?: ")
sum = 0
for i in range(start , end + 1):
sum += eqn(i)
return sum
print summation() # start will be 1, end will be 5 , equation will be n + 1. Should print 20
I get the error that I can't add an integer and a string together so is there any way to make the raw_input for equation not a string. Like instead of it being 'n + 1', I want it to be n + 1.
You could use input instead of raw_input, but this isn't really a good idea, since every time eqn is called it will call a input and prompt you for the equation.
A better method is to store the equation beforehand (using raw_input), and then use eval in the lambda function. Something like:
def summation():
start = int(raw_input("Start value of n?: "))
end = int(raw_input("End value of n?: "))
fx = raw_input("Equation: ")
eqn = lambda n: eval(fx)
sum = 0
for i in range(start , end + 1):
sum += eqn(i)
return sum
print summation()
Don't you need to surround your raw_input in your eqn variable with an int()?
I use python 3, but that should fix your problems.
Could you please help me with writing a function, which receives a character char (ie., a string of length one ), and an integer rotation. My function should return a new string of length one, the resulting of rotating char by rotation number of places to the right. My output for this code should be like this:
print(alphabet_position(a, 13)) = Output = n
print(alphabet_position(A, 14)) = Output = (capital) O
print(alphabet_position(6, 13)) = Output = 6
My function looks like this
def alphabet_position(letter, number):
for char in letter:
return ord(char)+ number
print(alphabet_position("g", 2))
print(alphabet_position("Z", 2))
The output is 105
The output is 92
You forgot to do the checks you have mentioned and also, you need to use the chr(returnedValue) to convert the returned integer to a character. Check out the below code for the function:
def alphabet_position(letter, number):
if len(letter) != 1:
return -1 #Invalid input
elif letter.isalpha() == False:
return letter #If its not an alphabet
else:
ans = ord(letter) + number
# the below if-statement makes sure the value does not overflow.
if ans > ord('z') and letter.islower():
ans = ans - ord('z') + ord('a')
elif ans > ord('Z') and letter.isupper():
ans = ans - ord('Z') + ord('A')
return chr(ans)
It works fin in my pc and in an online compiler+debugger. However, when I submit it in codechef, it gives me a runtime error(nzec). When do you get a runtime error and how to you resolve it. What is the problem in this code? I keep getting runtime error very frequently. How do I avoid it? Any kind of help will be deeply appreciated!
t = int(raw_input())
for i in range(t):
a = map(int, raw_input())
if a.index(min(a)) != 0:
if min(a) == 0:
print a.index(min(a))
else:
print str(str(a.index(min(a))) * (min(a)+1))
elif a.index(min(a)) == 0:
k = min(a)
a[0] = 99
l = min(a)
if l == k:
print str(str(a.index(min(a))) * min(a))
elif l > k:
print '1'+ ('0' * (k+1))
You have to split the raw_input()
raw_input() receives the input as just a string. Use raw_input().split() to convert the string to a list. Else you will have indexing problems, since the spaces given in the input are taken for mapping. So you get the nzec (non-zero exit code) error
a=map(int,raw_input().split())
will do
Many times it is due to some white places left.
Try this:
raw_input().strip().split(" ")
if the data is separated by " ".
I made a password generator - I'm only 16 so it's probably not the best- and it outputs 8 0 and ones like 01100101 and then enderneath that it outputs the password. Well when there is a "10" in the password like FG4v10Y6 it will add another character so instead of it being FG4v10Y6 it would be FG4v10Y6M so it has nine or more characters depending on how many "10" are in it.
I'm not sure why it's doing this please help. THanx!
import pygame
import random
pygame.init()
#letters
reg = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
CAP = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
final_pass = []
num_let_list = []
new_list = []
i = 0
file = open("password_test","w")
def num_list_gen(num_list):
for i in range(8):
num_let_list.append(random.randint(0,1))
i += 1
for each in num_let_list:
each = str(each)
new_list.append(each)
print ''.join(new_list)
def CAP_reg_num(final_pass,num_let_list,CAP,reg):
for each in num_let_list:
if each == 0:
cap_reg = random.randint(0,1)
if cap_reg == 0:
let1 = random.randint(0,25)
final_pass.append(reg[let1])
if cap_reg == 1:
let1 = random.randint(0,25)
final_pass.append(CAP[let1])
if each == 1:
num1 = random.randint(0,10)
num1 = str(num1)
final_pass.append(num1)
def main(CAP,reg,num_let_list,final_pass):
num_list_gen(num_let_list)
CAP_reg_num(final_pass,num_let_list,CAP,reg)
print ''.join(final_pass)
file.write(''.join(final_pass))
file.close
main(CAP,reg,num_let_list,final_pass)
why did the code come out all weird on the post in some places and how do you fix it?
Your password generator is flipping a coin to choose between adding a letter or a number. When it chooses to add a number, you choose the number to add with:
num1 = random.randint(0,10)
However, this doesn't return a single digit number. It returns one of 11 possible values: the numbers between 0 and 10 inclusive. So one time in 11, it will add the number 10 to the string, which is, of course, two digits.
You want:
num1 = random.randint(0,9)
instead to add a single digit.