I am very new to coding, I found something very confusing in python for me.
In this small piece of code:
if (count % 4) == 0 and (count % 6) == 0:
print ("Cheesecrackers")
count = count + 1
elif (count % 4) == 0:
print("Cheese")
count = count + 1
elif (count % 6) == 0:
print ("Crackers")
count = count +1
else:
print (count)
count = count + 1
The line: if (count % 4) == 0 and (count % 6) == 0:
Why does the addition of "==0" make a difference to how the code runs?
== 0 means the remainder is zero of the two numbers.
As x % y gives the remainder of x / y, you can say y goes into x evenly if there is no remainder (ie the remainder is 0). However, x % y will not always equal zero. For instance 3 % 2 gives 1. Thus the == 0 is checking that the remainder computed by count % 4 and count % 6 is zero (no remainder)
if (count % 4) == 0:
In the if-else statement, these are conditions or cases that are being tested. So in this case, it is testing if count % 4 has a remainder of 0 (happens when count is perfectly divisible by 4).
If you omitted the '==0', the if statement will just test if the outcome exists regardless of whether it is perfectly divisible or not.
Similarly,
if count:
will also always evaluate to True as long as the variable count exists.
Related
This is my code:
def helper_number_of_ones(n:int, counter:int)->int:
if n == 1:
counter += 1
return counter
else:
if n % 10 == 1:
counter += 1
if n // 10 == 1:
counter += 1
return helper_number_of_ones(n-1,counter)
def number_of_ones(n: int) -> int:
count = 0
return helper_number_of_ones(n,count)
My code basically checks for the number of digit one occurrences, throughout all numbers between n and 1, for example n=13 will output 6 for 6 ones occurrences, the only problem it doesn’t work
properly for numbers bigger than 100? Thanks in advance
Your code takes into consideration two possibilities:
The ones digit is 1 (if n % 10 == 1)
The tens digit is 1 (if n // 10 == 1)
This is enough for numbers up to 99, but fails for higher numbers.
I would suggest to break your function into two separate functions: one that counts the number of occurences of 1 in a single number, and another that does that for a range of numbers (using the first one of course).
It is because of how you calculate counter
...
if n % 10 == 1:
counter += 1
if n // 10 == 1:
counter += 1
...
For example, if n = 100, it will fail both ifs. You can make a function that calculates the number of 1 in a number recursively.
def num_of_one(number):
if number == 0:
return 0
else:
return ((number % 10) == 1) + num_of_one(number // 10)
Then make another function to calculate it over the range.
def range_num_of_one(max_num):
if max_num == 1:
return 1
else:
return num_of_one(max_num) + range_num_of_one(max_num - 1)
I found this code in a website for checking prime number
def isPrime(number):
if (number <= 1):
return False
elif (number <= 3):
return True
elif (number % 2 == 0 or number % 3 == 0):
return False
i = 5
while(i * i <= number):
if (number % i == 0 or number % (i + 2) == 0):
return False
i += 6
return True
but I can't understand the logic of if statement under while loop, that is if (number % i == 0 or number % (i + 2) == 0)
why need i+2??? when i is even, i+2 is also even and odd while i is odd. So, why need to check for i+2???
Except for 2 and 3, all prime numbers are of the form 6n±1. This code checks for 2 and 3 explicitly and then checks higher numbers in pairs: 6n-1, 6n+1, starting with 5. So it checks 5, 7 then 11, 13 then 17, 19 and so on. It steps 6 between pairs and steps 2 within each pair. Doing it this way avoids ever having to check multiples of 2 or 3.
i starts from 5, so adding 2 means taking in count only evens numbers.
It makes the check faster.
If you want to find out if a number is prime or not, here is a short sample
# Check if a positive integer number is a prime number. Check only till square root +1.
import math
def isPrime(n):
if ( n > 3 ):
if (n % 2 == 0):
return False
for i in range(3, math.isqrt(n), 2):
if (n % i == 0):
return False
return True
else:
return True
I am supposed to write a program that displays numbers from 100 to 200, ten per line, that are divisible by 5 or 6 but NOT both. This is my code so far. I know it's a basic problem so can you tell me the basic code that I'm missing instead of the "shortcut" steps. Any help is appreciated!
def main():
while (num >= 100) and (num <= 200):
for (num % 5 == 0) or (num % 6 == 0)
print (num)
main()
This is how I would go about it. I would recommend using a for loop over a while loop if you know the range you need. You are less likely to get into an endless loop. The reason for the n variable is since you said you needed 10 numbers per line. The n variable will track how many correct numbers you find so that you know when you have ten results and can use a normal print statement which automatically includes a newline. The second print statement will not add a newline.
n = 0
for i in range(100,201):
if (i%5 == 0 or i%6 == 0) and not (i%5 == 0 and i%6 == 0):
n += 1
if n%10 == 0:
print(i)
else:
print(str(i) + ", ", end="")
You should init every variable using in the code
While (condition) will break when the condition false. Since your condition depends on num, but num is never changed in your code, infinity loop will happen. You need to add num = num + 1 at the end of your loop block.
It's supposed to use if not for for each iterator here. And the condition you used for your problem is wrong to.
Should be like this:
def main():
num = 100
while (num >= 100) and (num <= 200):
if ((num % 5 == 0) or (num % 6 == 0)) and (num % 30 != 0):
print (num)
num = num + 1
main()
If my understanding is correct, 5 % 5 should equal 0. However when i run this code:
endless = 0
while endless == 0:
n = int(input("Provide a number here: "))
count = 0
sum = 0
while count < n:
if 1+count % 3 == 0 | 1+count % 5 == 0:
sum += 1 + count
count += 1
if count >= n:
print(sum)
It always returns 0, which implies that 1+count % 3 or 1+count % 5 never equals 0. What did i miss?
EDIT:
I seem too have missed fundamental maths somehow.
Dont use bitwise OR, and use paranthesis (operator precedence)!
Try:
(1+count) % 3 == 0 or (1+count) % 5 == 0:
^ ^ ^^ ^ ^
The operator priority of % is the same as / and higher than +, that means:
1+count % 3 == 1 + (count % 3)
which can never be 0 since modulo returns a value between 0 and 2.
I've been trying to write a recursive solution to a program to find a number where first N digits are divisible by N.
As an example: 3816547290, 3 is divisible by 1, 38 is divisible by 2, 381 is divisible by 3 and so on...
My recursive solution works fine while going "into" the recursion, but has issues when the stack unwinds (i.e. I don't specifically know how to backtrack or take steps on the way out
ARR = [0]*10
ARR[0] = 1 #dummy entry
def numSeq(pos, num):
if all(ARR):
print num
return True
if (pos>0) and (num%pos) != 0:
return False
for i in xrange(1,10):
if ARR[i] == 1:
continue
new_num = num*10 + i
if new_num%(pos+1) == 0:
ARR[i] = 1
numSeq(pos+1,new_num)
The problem with this code seems to be that it follows the number generation correctly while going into the recursion...so it correctly generates the number 123654 which is divisible by 6 and follows first N digits being divisible by N, but after it fails to find any further digits from 7-8 or 9 that divide 7, i don't get the next set of steps to "reset" the global ARR and begin from index 2, i.e. try 24xxxx,and eventually get to 3816547290
Thanks in Advance for your help!
EDIT: One condition I'd forgotten to mention is that each digit must be used exactly once (i.e. repetition of digits is disallowed)
2nd EDIT:
I was able to finally apply proper backtracking to solve the problem...this code works as is.
ARR = [0]*10
def numDivisibile(num,pos):
if all(ARR):
print num
return True
for i in xrange(0,10):
if ARR[i] == 1:
continue
new_num = num*10+i
#check for valid case
if new_num%(pos+1) == 0:
ARR[i] = 1
if numDivisibile(new_num, pos+1):
return True
#backtrack
ARR[i] = 0
return False
print numDivisibile(0, 0)
To generate all 10 digits integers where the first n digits are divisible by n for each n from 1 to 10 inclusive:
#!/usr/bin/env python3
def generate_ints_nth_digit_divisible_by_n(n=1, number=0):
number *= 10
if n == 10:
yield number # divisible by 10
else:
for digit in range(not number, 10):
candidate = number + digit
if candidate % n == 0: # divisible by n
yield from generate_ints_nth_digit_divisible_by_n(n + 1, candidate)
print("\n".join(map(str, generate_ints_nth_digit_divisible_by_n())))
Output
1020005640
1020061620
1020068010
...
9876062430
9876069630
9876545640
To get numbers where each digit occurs only once i.e., to find the permutations of the digits that satisfy the divisibility condition:
def divisibility_predicate(number):
digits = str(number)
for n in range(1, len(digits) + 1):
if int(digits[:n]) % n != 0:
return n - 1
return n
def generate_digits_permutation(n=1, number=0, digits=frozenset(range(1, 10))):
# precondition: number has n-1 digits
assert len(set(str(number))) == (n - 1) or (number == 0 and n == 1)
# and the divisibility condition holds for n-1
assert divisibility_predicate(number) == (n - 1) or (number == 0 and n == 1)
number *= 10
if n == 10:
assert not digits and divisibility_predicate(number) == 10
yield number # divisible by 10
else:
for digit in digits:
candidate = number + digit
if candidate % n == 0: # divisible by n
yield from generate_digits_permutation(n + 1, candidate, digits - {digit})
from string import digits
print([n for n in generate_ints_nth_digit_divisible_by_n()
if set(str(n)) == set(digits)])
print(list(generate_digits_permutation()))
Output
[3816547290]
[3816547290]
In your function, you never do return numSeq(...), this seems like causing the issue.
If you want to have a iterative solution, you can check the following:
def getN(number):
strNum = str(number)
for i in range(1, len(strNum)+1):
if int(strNum[:i]) % i != 0:
return i-1
return i
print getN(3816)
print getN(3817)
print getN(38165)
Output:
4
3
5
We can modify your recursive function a little to try different possibilities. Rather than have a global record (ARR) of used positions, each thread of the recursion will have its own hash of used digits:
def numSeq(pos, num, hash):
if pos != 1 and num % (pos - 1) != 0: # number does not pass the test
return
elif pos == 11: # number passed all the tests
print num
elif pos == 5:
numSeq(pos + 1,10 * num + 5,hash) # digit is 5 at position 5
elif pos == 10:
numSeq(pos + 1,10 * num,hash) # digit is 0 at position 10
else:
k = 2 if pos % 2 == 0 else 1 # digit is even at even positions
for i in xrange(k,10,2):
if hash & (1 << i): # digit has already been used, skip it
continue
numSeq(pos + 1,10 * num + i,hash | (1 << i))
numSeq(1,0,0) # 3816547290