Python: Why does while loop exclude the first value? - python

I am trying to make a decimal to binary converter, however, I noticed that some values are being ignored and the last value is not being entered into the list I created.
#Here we create a new empty list.
binary = []
n = int(input("Enter number: "))
while n > 1:
n = n//2
m = n%2
binary.append(m)
binary.reverse()
print( " ".join( repr(e) for e in binary ))

This is your code after correction :
binary = []
n = int(input("Enter number: "))
while n > 0:
m = n%2
n = n//2
binary.append(m)
if len(binary)==0:
binary.append(0)
binary.reverse()
print( " ".join( repr(e) for e in binary ))
Your question is duplicate to this stackoverflow question check the link too.
good luck :)

As PM 2Ring suggested a tuple assignment may be the way to go. Makes your code shorter too :-) ... also changed n > 1 to n >= 1
binary = []
n = int(input("Enter number: "))
while n >= 1:
n, m = n // 2, n % 2
binary.append(m)
binary.reverse()
print( " ".join( repr(e) for e in binary ))

n = int(input("Enter number: "))
print("{0:0b}".format(n)) # one-line alternate solution
if n == 0: # original code with bugs fixed
binary = [0]
else:
binary = []
while n > 0:
m = n%2
n = n//2
binary.append(m)
binary.reverse()
print("".join( repr(e) for e in binary ))

Your algorithm is close, but you need to save the remainder before you perform the division. And you also need to change the while condition, and to do special handling if the input value of n is zero.
I've fixed your code & put it in a loop to make it easier to test.
for n in range(16):
old_n = n
#Here we create a new empty list.
binary = []
while n:
m = n % 2
n = n // 2
binary.append(m)
# If the binary list is empty, the original n must have been zero
if not binary:
binary.append(0)
binary.reverse()
print(old_n, " ".join(repr(e) for e in binary))
output
0 0
1 1
2 1 0
3 1 1
4 1 0 0
5 1 0 1
6 1 1 0
7 1 1 1
8 1 0 0 0
9 1 0 0 1
10 1 0 1 0
11 1 0 1 1
12 1 1 0 0
13 1 1 0 1
14 1 1 1 0
15 1 1 1 1
As Blckknght mentions in the comments, there's a standard function that can give you the quotient and remainder in one step
n, m = divmod(n, 2)
It can be convenient, but it doesn't really provide much benefit apart from making the code a little more readable. Another option is to use a tuple assignment to perform the operations in parallel:
n, m = n // 2, n % 2
It's a good practice, especially when you're new to coding, to work through your algorithm on paper to get a feel for what it's doing. And if your code doesn't give the expected output it's a good idea to add a few print calls in strategic places to check that the values of your variables are what you expect them to be. Or learn to use a proper debugger. ;)

Related

While loop problem.The result isn't what I expected

I am new to Python and Stackoverflow in general, so sorry if my formatting sucks and I'm not good at English. But I have a problem with this code.
n = int(input("Fibonacci sequence (2-10): "))
a = 0
b = 1
sum = 0
count = 1
f = True
print("Fibonacci sequence up to {}: ".format(n), end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
This is the result of the code
Fibonacci sequence (2-10): 2
Fibonacci sequence up to 2: 0 1
And this is the result that I expect.
Fibonacci sequence (2-10): 1
Invalid Number!
Fibonacci sequence (2-10): 15
Invalid Number!
Fibonacci sequence (2-10): 10
Fibonacci sequence up to 10: 0 1 1 2 3 5 8 13 21 34
Looks like you just need to add an additional validation step to make sure that the input is in the desired range. This should do it.
while True:
n = int(input("Fibonacci sequence (2-10): "))
if n<2 or n>10:
print("Invalid Number!")
else:
a = 0
b = 1
sum = 0
count = 1
f = True
print("Fibonacci sequence up to {}: ".format(n), end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
break
Edit: To #Barmar's point, a loop on the outside would help avoid rerunning the code in case the input isn't within the desired range.

Check if the digits in the number are in increasing sequence in python

I was working on a problem that determines whether the digits in the numbers are in the increasing sequence. Now, the approach I took to solve the problem was, For instance, consider the number 5678.
To check whether 5678 is an increasing sequence, I took the first digit and the next digit and the last digit which is 5,6,8 and substitute in range function range(first,last,(diff of first digit and the next to first digit)) i.e range(5,8+1,abs(5-6)).The result is the list of digits in the ascending order
To this problem, there is a constraint saying
For incrementing sequences, 0 should come after 9, and not before 1, as in 7890. Now my program breaks at the input 7890. I don't know how to encode this logic. Can someone help me, please?.
The code for increasing sequence was
len(set(['5','6','7','8']) - set(map(str,range(5,8+1,abs(5-6))))) == 0
You can simply check if the number, when converted to a string, is a substring of '1234567890':
str(num) in '1234567890'
you could zip the string representation of the number with a shifted self and iterate on consecutive digits together. Use all to check that numbers follow, using a modulo 10 to handle the 0 case.
num = 7890
result = all((int(y)-int(x))%10 == 1 for x,y in zip(str(num),str(num)[1:]))
I would create a cycling generator and slice that:
from itertools import cycle, islice
num = 5678901234
num = tuple(str(num))
print(num == tuple(islice(cycle(map(str, range(10))), int(num[0]), int(num[0]) + len(num))))
This is faster than solutions that check differences between individual digits. Of course, you can sacrifice the length to make it faster:
def digits(num):
while num:
yield num % 10
num //= 10
def check(num):
num = list(digits(num))
num.reverse()
for i, j in zip(islice(cycle(range(10)), num[0], num[0] + len(num)), num):
if i != j:
return False
return True
Since you already have the zip version, here is an alternative solution:
import sys
order = dict(enumerate(range(10)))
order[0] = 10
def increasing(n):
n = abs(n)
o = order[n % 10] + 1
while n:
n, r = divmod(n, 10)
if o - order[r] != 1:
return False
o = order[r]
return True
for n in sys.argv[1:]:
print n, increasing(int(n))
Here's my take that just looks at the digits and exits as soon as there is a discrepancy:
def f(n):
while (n):
last = n % 10
n = n / 10
if n == 0:
return True
prev = n % 10
print last, prev
if prev == 0 or prev != (last - 1) % 10:
return False
print f(1234)
print f(7890)
print f(78901)
print f(1345)
Somehow this question got me thinking of Palindromes and that got me to thinking of this in a different way.
5 6 7 8
8 7 6 5
-------------
13 13 13 13
9 0 1
1 0 9
---------
10 0 10
9 0 1 2
2 1 0 9
-------------
11 1 1 11
And that leads to this solution and tests.
pos_test_data = [5678, 901, 9012, 9012345678901]
neg_test_data = [5876, 910, 9021]
def monotonic_by_one(n):
fwd = str(n)
tgt = ord(fwd[0]) + ord(fwd[-1])
return all([ord(f) + ord(r) in (tgt, tgt - 10) for f, r in zip(fwd, reversed(fwd))])
print("Positive: ", all([monotonic_by_one(n) for n in pos_test_data]))
print("Negative: ", all([not monotonic_by_one(n) for n in neg_test_data]))
Results:
Positive: True
Negative: True
Instead of using to full list comprehension you could use a for loop and bail out at the first failure. I'd want to look at the size of the numbers being checked and time somethings to decide which was faster.
I would try this, a little verbose for readability:
seq = list(input())
seq1 = seq[1:]
seq2 = seq[:-1]
diff = [x-y for x,y in zip([int(x) if int(x)>0 else 10 for x in seq1],[int(x) if int(x)>0 else 10 for x in seq2])]
if any (t != 1 for t in diff) :
print('not <<<<<')
else :
print('<<<<<<')
A simple solution that checks the next number in the sequence and then using current_number + 1 == next_number to detect sequence.
import bisect
def find_next(x, a):
i = bisect.bisect_right(x, a)
if i:
return x[i]
return None
def is_sequence(x):
ans = True
for i in x[:-1]:
next_num = find_next(x, i)
if next_num and i+1 != next_num:
ans = False
break
return ans
print(is_sequence([1,2,3,4])) # True

find total number of divisors of number, for t test cases in python

i make a programe to find the number of divisor for a number with test case to submit it on the online judge so i write the code like that
num_case=int(raw_input())
num=list()
final_o=[]
for x in xrange(num_case):
num.append(int(raw_input()))
for h in num:
result=[int(h)]
for i in xrange(1, h + 1):
if h % i == 0:
result.append(i)
a=final_o.append(len(result)-1)
for ff in final_o:
print ff
in this case i make user input the number of test case for example 3 and then enter the number for example 12 7 and 36 then he get the output like this 6 2 9 that the 12 have 6 divisor number and so on this code work well but i get Memory Error when i submit it so i try to use itertools because range in for loop is small and xrange take a lot of time more than 2 second but i dont get any output code
from itertools import count
num_case=int(raw_input())
num=list()
final_o=[]
for x in xrange(num_case):
num.append(int(raw_input()))
for h in num:
result=[int(h)]
n=int(raw_input())
for i in count(1):
if n % i == 0:
result.append(i)
elif count==n+1:
break
a=final_o.append(len(result)-1)
for ff in final_o:
print ff
any one have a solution to this bug ? Note that the time for the test case 2 second and the range of the numbers is 10^9 and test case 100 How i Do that ?
def devisors_number(n):
result = 0
sqrt_n = int(n**0.5)
for i in xrange(1, sqrt_n + 1):
if n % i == 0:
result += 1
result *= 2
if sqrt_n**2 == n:
result -= 1
return result
n = int(raw_input("Enter a number: "))
d = devisors_number(n)
print "{0} has {1} devisors".format(n, d)

How to stop repetition in my code?

This code executes primes upto a given number. It works correctly as far as the prime generation is concerned but the output is painfully repetitive.
The code is:
numP = 1
x = 3
y = int(input('Enter number of primes to be found: '))
while numP<=y:
for n in range(2, x):
for b in range(2, n):
if n % b == 0:
break
else:
# loop fell through without finding a factor
print (n)
x += 2
numP += 1
The output is like (e.g. for y=4):
2
2
3
2
3
5
2
3
5
7
I want to avoid repetition and obtain output like:
2
3
5
7
How should the code be modified?
If you store the data in a set, you will avoid repetitions
There's no reason to loop n from 2..x. Get rid of that loop, and replace all references to 'n' with 'x'. I.e.:
def find_primes(y):
x = 3
numP = 0
while True:
for b in range(2, x):
if x % b == 0:
break
else:
# loop fell through without finding a factor
print (x)
numP += 1
if numP >= y:
return
x += 2

How to find the sum of all the multiples of 3 or 5 below 1000 in Python?

Not sure if I should've posted this on math.stackexchange instead, but it includes more programming so I posted it here.
The question seems really simple, but I've sat here for at least one hour now not figuring it out. I've tried different solutions, and read math formulas for it etc but it won't gives me the right answer when coding it! I made two different solutions for it, which both gives me the wrong answer. The first solution gives me 265334 while the second one gives me 232169. The answer is 233168, so the second solution is closer.
I should mention this is a question from Project Euler, the first one to be precise.
Here's my code. Any ideas what's wrong?
nums = [3, 5]
max = 999
result = 0
for num in nums:
for i in range(1,max):
if num*i < max:
result += num*i
print result
result = 0
for i in range(0,max):
if i%3 == 0 or i%5 == 0:
result += i
print result
You are overcomplicating things. You just need a list of numbers that are multiples of 3 or 5 which you can get easily with a list comprehension:
>>> [i for i in range(1000) if i % 3 == 0 or i % 5 == 0]
Then use sum to get the total:
>>> sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
<<< 233168
Or even better use a generator expression instead:
>>> sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)
Or even better better (courtesy Exelian):
>>> sum(set(list(range(0, 1000, 3)) + list(range(0, 1000, 5))))
range(k,max) does not include max, so you're really checking up to and including 998 (while 999 is a multiple of 3). Use range(1,1000) instead.
I like this the most:
def divisibles(below, *divisors):
return (n for n in xrange(below) if 0 in (n % d for d in divisors))
print sum(divisibles(1000, 3, 5))
The problem with your first solution is that it double-counts multiples of 15 (because they are multiples of both 3 and 5).
The problem with your second solution is that it doesn't count 999 (a multiple of 3). Just set max = 1000 to fix this.
result = 0
for i in range(0,1000):
if (i % 3 == 0 or i % 5 == 0):
print i
result = result + i
print result
Output:
0
3
5
6
9
.
.
.
993
995
996
999
233168
max = 1000 # notice this here
result = 0
for i in range(0,max):
if i%3 == 0 or i%5 == 0:
result += i
print result
This works, but use 1000 for max, so it includes 999 too.
I know this was 3 months ago but as an experiment because I am new to python I decided to try and combine some of the other people answers and I came up with a method you can pass the max number to and the divisors as a list and it returns the sum:
def sum_of_divisors(below, divisors):
return sum((n for n in xrange(below) if 0 in (n % d for d in divisors)))
max = 1000
nums = [3, 5]
print sum_of_divisors(max, nums)
There are floor(999/3) multiples of 3, floor(999/5) multiples of 5, and floor(999/15) multiples of 15 under 1000.
For 3, these are: 3 + 6 + 9 + 12 +... + 999 = 3 * (1 + 2 + 3 + 4 +...+333)
= 3 * (333 * 334 / 2) because the sum of the integers from 1 to k is k*(k+1)/2.
Use the same logic for the sum of multiples of 5 and 15. This gives a constant time solution. Generalize this for arbitrary inputs.
I know this is from 6 years ago but I just thought id share a solution that found from a math formula that I thought was interesting as it removes the need to loop through all the numbers.
https://math.stackexchange.com/a/9305
def sum_of_two_multiples(nums, maxN):
"takes tuple returns multiples under maxN (max number - 1)"
n1, n2 = nums = nums[:2]
maxN -= 1
def k(maxN, kx):
n = int(maxN / kx)
return int(kx * (0.5 * n * (n+1)))
return sum([k(maxN, n) for n in nums]) - k(maxN, n1*n2)
Outputs the follows
print(sum_of_two_multiples((3,5), 10))
# 23
print(sum_of_two_multiples((3,5), 1000))
# 233168
print(sum_of_two_multiples((3,5), 10**12))
# 233333333333166658682880
I think only the last few lines from your code are important.
The or statement is the key statement in this code.
Also rater than setting the max value to 999, you should set it to 1000 so that it will cover all values.
Here is my code.
ans=0
for i in range(1,1000):
if(i%3==0 or i%5==0):
ans += i
print(ans)
input('press enter key to continue');#this line is only so that the screen stays until you press a key
t = int(input())
for a in range(t):
n = int(input().strip())
sum=0
for i in range(0,n):
if i%3==0 or i%5==0:
sum=sum+i
print(sum)
You can also use functional programming tools (filter):
def f(x):
return x % 3 == 0 or x % 5 == 0
filter(f, range(1,1000))
print(x)
Or use two lists with subtraction of multiples of 15 (which appears in both lists):
sum1 = []
for i in range(0,1000,3):
sum1.append(i)
sum2 = []
for n in range(0,1000,5):
sum2.append(n)
del sum2[::3] #delete every 3-rd element in list
print(sum((sum1)+(sum2)))
I like this solution but I guess it needs some improvements...
here is my solution:
for n in range(100):
if n % 5==0:
if n % 3==0:
print n, "Multiple of both 3 and 5" #if the number is a multiple of 5, is it a multiple of 3? if yes it has has both.
elif n % 5==0:
print n, "Multiple of 5"
elif n % 3==0:
print n, "Multiple of 3"
else:
print n "No multiples"
this is my solution
sum = 0
for i in range (1,1000):
if (i%3)==0 or (i%5)==0:
sum = sum + i
print(sum)
count = 0
for i in range(0,1000):
if i % 3 == 0 or i % 5 ==0:
count = count + i
print(count)
I know it was 7 years ago but I wanna share my solution to this problem.
x= set()
for i in range(1,1001):
if (i % 3) == 0:
x.add(i)
for j in range(1,1001):
if (j % 5) == 0:
x.add(j)
print(sum(x))
I had to do it in range 1 , 100
This is how I did it.
For i in range(1,100):
If i ÷ 3 == 0 and i ÷ 5 == 0:
print(i)
So with 1000 you just change the 100 to 1000
I had to find the multiples of 3 and 5 within 100 so if you need 3 or 5 just change it to or and it will give you more answers too. I'm just starting to learn so correct me if I'm wrong
Here is the code:
count = 1000
m = [3, 5, 3*5]
result = 0
Sum = 0
for j in m:
result = 0
for i in range(count):
if i*j < 1000:
result = result + i*j
elif i == (count - 1):
if j < 15:
Sum = result + Sum
elif j == 15:
Sum = Sum - result
print(Sum)
total = 0
maxrange = input("Enter the maximum range") #Get the maximum range from the keyboard
print("")
max = int(maxrange)
for i in range (0,max):
if i%3 == 0 or i%5 ==0:
total = total +i
print (total)

Categories

Resources