String concatenation in while loop not working - python

I'm trying to create a Python program that converts a decimal to binary.
Currently I have
working = int(input("Please select a non-negative decimal number to convert to binary. "))
x = ()
while working !=0:
remainder = working % 2
working = working // 2
if remainder == 0:
x = remainder + 0
print (working, x)
else:
x = remainder + 1
print (working, x)
print ("I believe your binary number is " ,x)
The while works on it's own if I print after that, but the if/else doesn't. I am trying to create a string that is added to with each successive division. Currently, if my starting int is 76, my output is
38 0
38 0
19 0
19 0
9 2
4 2
2 0
2 0
1 0
1 0
0 2
I am trying to get my output to instead be
38 0
19 00
9 100
4 1100
2 01100
1 001100
0 1001100
This is my first attempt at string concatenation and I've tried a few variations of the above code to similar results.

There are a few issues with the code you’ve provided:
x starts with a value of (), and in any case, rather than concatenating strings to it, you’re adding numbers within the loop.
You’re trying to append the numbers rather than prepend, so the result would be reversed if it worked.
Your second print is not inside the conditional, so the output is duplicated.
What you need to do is initialize x with an empty string and then prepend strings to it:
working = int(input("Please enter a non-negative decimal number to convert to binary: "))
x = ""
while working != 0:
remainder = working % 2
working = working // 2
if remainder == 0:
x = "0" + x
else:
x = "1" + x
print (working, x)
print ("I believe your binary number is", x)
Output:
λ python convert-to-binary.py
Please enter a non-negative decimal number to convert to binary: 76
38 0
19 00
9 100
4 1100
2 01100
1 001100
0 1001100
I believe your binary number is 1001100

The problem is that you are not working with strings. You are first creating an empty tuple for x, and then overwriting that with an integer value later.
To do what you are attempting, you need to treat x as a string, and append the string literals '0' and '1' to it.
Try this instead:
working = int(input("Please select a non-negative decimal number to convert to binary. "))
x = ''
while working !=0:
remainder = working % 2
working = working // 2
if remainder == 0:
x += '0'
print (working, x)
else:
x += '1'
print (working, x)
print ("I believe your binary number is " , x[::-1])
Note how x is initially declared as an empty string '' instead of the empty tuple (). This makes it so that when you use the += operator later to append 0 or 1 to it, that it is treated as string concatenation instead of addition.

It should be
working = int(input("Please select a non-negative decimal number to convert to binary. "))
x = ""
while working !=0:
remainder = working % 2
working = working // 2
if remainder == 0:
x = x + str(remainder)
print (working, x)
else:
x = x + str(remainder)
print (working, x)
print ("I believe your binary number is " ,x[::-1])

Change your code to below:
if remainder == 0:
x = str(remainder) + '0'
print (working, x)
else:
x = str(remainder) + '1'
print (working, x)
in your code, python interprets as an int you have to cast it to string.
another way is using built-in function bin(working), directly converts from number to binary value.

Related

Function is not returning any values

I am coding to find whether or not a number is a disarium number or not. A disarium number is a number in which it's digits can be raised to the power of their respective positions and added to give the number.
Example1: 75 is not a disarium number, because 7^1 + 5^2 = 32 and not 75
Example2: 135 is a disarium number, since: 1^1 + 3^2 + 5^3 = 1 + 9 + 125 = 135
In my code, even though 75 is not a disarium number, nothing is returned. It's like my function isn't even going through my if and else statements
def is_disarium(number):
number = str(number)
selection_array = [int(num) for num in number]
disarium_check = 0
for i in range(len(selection_array)):
disarium_check += int(selection_array[i])**(i+1)
if disarium_check == number:
return True
else:
return False
is_disarium(75)
My code (image)
This code is currently returning False for every number because in the if statement you are comparing an integer with a string. And you can use the print command to find the return value.
Use this modified code to check whether it is working as expected.
def is_disarium(number):
number = str(number)
selection_array = [int(num) for num in number]
disarium_check = 0
for i in range(len(selection_array)):
disarium_check += int(selection_array[i])**(i+1)
if disarium_check == int(number):
return True
else:
return False
output = is_disarium(135)
print(output)

Remove trailing zeros from binary result in python

We have a program that changes decimals to binary.
And the goal is to run the program, input a value, and outputs the value in binary.
The problem with my code is that it has trailing zeros when outputting the binary.
I need to achieve this without using external libraries like "math", so please stick to the built-in functions.
Current output:
Insert a value:
5
The number fits in 1 byte and is in binary:
00000101
Insert a value:
100
The number fits in 1 byte and is in binary:
01100100
Insert a value:
280
The number fits in 16 bits and is in binary:
0000000100011000
Expected output:
Insert a value:
5
The number fits in 1 byte and is in binary:
101
Insert a value:
100
The number fits in 1 byte and is in binary:
1100100
Insert a value:
280
The number fits in 16 bits and is in binary:
100011000
Current code:
def dec2bin(value, number_bits):
result = ''
while number_bits > 0:
bit_value = 2 ** (number_bits - 1)
if value >= bit_value:
result = result + '1'
value = value - bit_value
else:
result = result + '0'
number_bits = number_bits - 1
print(result)
input_ok = False
userinput = 0
while not input_ok:
print('Insert a value:')
userinput = int(input())
if userinput > 65535:
print('invalid, cant handle that big numbers, try again')
else:
input_ok = True
if userinput < 256:
print('The number fits in 1 byte and is in binary:')
dec2bin(userinput, 8)
else:
print('The number fits in 16 bits and is in binary:')
dec2bin(userinput, 16)
It easy with string formatting functions (see Pranav's comment). But perhaps in this case you want the algorithm to take care of it, and see treating it as a string is cheating.
def dec2bin(value, number_bits):
result = ''
starting = True
while number_bits > 0:
bit_value = 2 ** (number_bits - 1)
if value >= bit_value:
result = result + '1'
value = value - bit_value
starting = False
elif not starting:
result = result + '0'
number_bits = number_bits - 1
print(result)
Since you are storing the value as a string you can use
result.lstrip('0')
to remove the leading zeros from your answer.

boolean string not counted in while/if statement in python[3.8]

I'm a beginner programmer and chose python[3.8] as my choice to learn. I don't even know what to ask or how to search this site. My program counts 30 to 40 and prints 'Go' for multiples of 3 and strings of 3 and remainders of 3. It counts Go's. Output should be 10 but it's 3. It's not counting the strings. There is no error msgs.
`enter code here`
s = '3'
x = 40
y = 30
num = 0
while y < x :
y=y+1
if y % 3 == 0 or y % 10 == 3 or s in 'y' :
print('Go',y)
num = num + 1
print(num, 'Go\'s')
I think the problem here is to understand how python works.
When you write s in 'y' it will always return false because y here is a character that composes the string which value is ythe character.
So what you'll need to do is use the function str(param) to convert your integer to a string with the same value.
This is a code that works the way you want to.
s = '3'
x = 40
y = 30
num = 0
while y < x :
if y % 3 == 0 or y % 10 == 3 or s in str(y) :
print('Go',y)
num = num + 1
y=y+1
print(num, 'Go\'s')

How to break a while loop when input is a particular string?

I need to stop adding up user inputs when one of them is the string "F".
So basically If my input is a int then : += result, if the same input variable is a string then I need to stop and add them together.
My code actually works and has the same inputs and outputs the exercise demands but I'm very unhappy with the way I resolve it.
This is my code:
import numbers
cat = int(input())
def norm(cat):
res = 0
for n in range(cat):
x = int(input())
res += x
print(res)
def lon():
res = 0
while 2 > 1:
try :
y = int(input())
if isinstance(y,int):
res +=y
except:
print(res)
break
if cat >= 0 :
norm(cat)
else:
lon()
It's actually breaking the while loop in a stupid way by checking if my variable is an int. (I need to make it stop by simply pressing F)
Is there any cleaner and shorter way to obtain the same outputs?
Example of the actual inputs-outputs I expect :
in: out:16 (1 + 3 + 5 + 7)
4
1
3
5
7
in: out:37 (1 + 3 + 5 + 7 + 21)
-1
1
3
5
7
21
F
You could have written it a bit shorter:
result = 0
while True:
line = input()
try:
result += int(line)
except ValueError:
break
print(result)
Notice:
import numbers isn't needed. (I didn't even know that existed!)
Instead of 2 > 1, you can use True.
You don't need to check isinstance(..., int) since int() enforces that.
This runs until any non-integer string is reached.
If you want to specifically check for "F" only, it's a bit easier:
result = 0
while True:
line = input()
if line == "F":
break
result += int(line)
print(result)
Note that without using try, you'll crash the program if you input a non-integer, non-"F" string.

How can I Keep the following program running until it becomes a single digit number?

I want to write a program that can calculate the sum of an integer as well as count its digits . It will keep doing this until it becomes a one digit number.
For example, if I input 453 then its sum will be 12 and digit 3.
Then it will calculate the sum of 12=1+2=3 it will keep doing this until it becomes one digit. I did the first part but i could not able to run it continuously using While . any help will be appreciated.
def main():
Sum = 0
m = 0
n = input("Please enter an interger: ")
numList = list(n)
count = len(numList)
for i in numList:
m = int(i)
Sum = m+Sum
print(Sum)
print(count)
main()
It is not the most efficient way, but it doesn't matter much here; to me, this is a problem to elegantly solve by recursion :)
def sum_digits(n):
n = str(n)
if int(n) < 10:
return n
else:
count = 0
for c in n:
count += int(c)
return sum_digits(count)
print sum_digits(123456789) # --> 9 # a string
A little harder to read:
def sum_digits2(n):
if n < 10:
return n
else:
return sum_digits2(sum(int(c) for c in str(n))) # this one returns an int
There are a couple of tricky things to watch out for. Hopefully this code gets you going in the right direction. You need to have a conditional for while on the number of digits remaining in your sum. The other thing is that you need to covert back and forth between strings and ints. I have fixed the while loop here, but the string <-> int problem remains. Good luck!
def main():
count = 9999
Sum = 0
m = 0
n = input("Please enter an integer: ")
numList = list(n)
while count > 1:
count = len(numList)
for i in numList:
m = int(i)
Sum = m+Sum
print(Sum)
print(count)
# The following needs to be filled in.
numlist = ???
main()
You can do this without repeated string parsing:
import math
x = 105 # or get from int(input(...))
count = 1 + int(math.log10(x))
while x >= 10:
sum = 0
for i in xrange(count):
sum += x % 10
x /= 10
x = sum
At the end, x will be a single-digit number as described, and count is the number of original digits.
I would like to give credit to this stackoverflow question for a succinct way to sum up digits of a number, and the answers above for giving you some insight to the solution.
Here is the code I wrote, with functions and all. Ideally you should be able to reuse functions, and here the function digit_sum(input_number) is being used over and over until the size of the return value (ie: length, if sum_of_digits is read as a string) is 1. Now you can use the while loop to keep checking till the size is what you want, and then abort.
def digit_sum(input_number):
return sum(int(digit) for digit in str(input_number))
input_number = input("Please enter a number: ")
sum_of_digits = digit_sum(input_number)
while(len(str(sum_of_digits)) > 1):
sum_of_digits = digit_sum(input_number)
output = 'Sum of digits of ' + str(input_number) + ' is ' + str(sum_of_digits)
print output
input_number = sum_of_digits
this is using recursive functions
def sumo(n):
sumof = 0
while n > 0:
r = n%10 #last digit
n = n/10 # quotient
sumof += r #add to sum
if sumof/10 == 0: # if no of digits in sum is only 1, then return
return sumof
elif sumof/10 > 0: #else call the function on the sumof
sumo(sumof)
Probably the first temptation would be to write
while x > 9:
x = sum(map(int, str(x)))
that literally means "until there is only one digit replace x by the sum of its digits".
From a performance point of view however one should note that computing the digits of a number is a complex operation because Python (and computers in general) store numbers in binary form and each digit in theory requires a modulo 10 operation to be extracted.
Thus if the input is not a string to begin with you can reduce the number of computations noting that if we're interested in the final sum (and not in the result of intermediate passes) it doesn't really matter the order in which the digits are summed, therefore one could compute the result directly, without converting the number to string first and at each "pass"
while x > 9:
x = x // 10 + x % 10
this costs, from a mathematical point of view, about the same of just converting a number to string.
Moreover instead of working out just one digit however one could also works in bigger chunks, still using maths and not doing the conversion to string, for example with
while x > 99999999:
x = x // 100000000 + x % 100000000
while x > 9999:
x = x // 10000 + x % 10000
while x > 99:
x = x // 100 + x % 100
while x > 9:
x = x // 10 + x % 10
The first loop works 8 digits at a time, the second 4 at a time, the third two and the last works one digit at a time. Also it could make sense to convert the intermediate levels to if instead of while because most often after processing n digits at a time the result will have n or less digits, leaving while loops only for first and last phases.
Note that however the computation at this point is so fast that Python general overhead becomes the most important part and thus not much more can be gained.
You could define a function to find the sum and keep updating the argument to be the most recent sum until you hit one digit.
def splitSum(num):
Sum = 0
for i in str(num):
m = int(i)
Sum = Sum + m
return str(Sum)
n = input("Please enter an integer: ")
count = 0
while count != 1:
Sum = splitSum(n)
count = len(Sum)
print(Sum)
print(count)
n = Sum

Categories