I'm trying to create a function that take two parameters: D = digit (0-9) and n = positive number.
If the D is parity number, the function should give me 0 but ,if the D is odd number, the function should count numbers of odd number I have in n.
There is a problem with this code but I don't know what:
def testD(D,n):
if D % 2 == 0:
return 0
count = 0
while n > 0:
if(n%10) %2==1:
count +=1
n=n/10
return count
I changed 2 things :
while n > 1: instead of while n > 0: otherwise your loop never stops
n=n//10 instead of n=n/10, where // is the euclidian division, which is what you need here
You should try this :
def testD(D,n):
if D % 2 == 0:
return 0
count = 0
while n > 1:
if(n%10) %2==1:
count +=1
n=n//10
return count
print(testD(7, 555))
# output : 3 (because 7 is odd, and there is 3 odd digits in 555)
Related
The task:
Using python, create a function that uses a loop to determine how many
times a number can be squared until it reaches at least a twenty eight
digit number.
Ex: It takes three times to reach a three digit number, starting with
2: 2^2 = 4, 4^2 = 16, 16^2 = 256
Below is what I've tried:
def squaring():
maximum = int(len(28))
for i in range(3, maximum):
print(i**2)
I've also tried:
def squaring():
i = 3
while len(str(i)) < 28:
i = i ** 2
print(i)
Your first example doesn't work, as len is not defined for integers.
Your second example is actually quite right: You can add a counter to check how many times you've multiplied the original number:
def squaring():
counter = 0
i = 3
while len(str(i)) < 28:
i = i ** 2
counter += 1
print(i)
return counter
print(f'The number of squares: {squaring()}')
It's not really necessary to convert anything to a string. It can be done like this:
def count_squares(n):
count = 0
while n < 10**27+1:
n *= n
count += 1
return count
print(count_squares(3))
Output:
6
A Update to the function you created, just passing a parameter to pass number of your choice and adding a iterator 'i' in order to get x-times the number is squared
def squaring(input_number):
number = input_number
i = 0
while len(str(number)) <= 28:
number = number ** 2
i += 1
print(number)
return str(i)+'x'
You can transform the number into a string and you evaluate the len len(str(i**2)) and put a condition
You can Use While True until your Conditions occur!
_iter = 0
i = 2
while True:
i = i**2
_iter += 1
if len(str(i)) >=28:
break
print(_iter)
We have an input integer let's say 13. We can find consistent subarray of fibonacci numbers that sums to 10 - [2,3,5]. I need to find next number that is not a sum of consistent subarray. In this case this number will be 14. I have this code, but the catch is, it can be optimized to not iterate through all of the N's from starting Left Pointer = 1 and Right Pointer = 1 but somehow "import" from previous N and i have no clue how to do it so maybe someone smarter might help.
def fib(n):
if n == 1: return 1
if n == 2: return 1
return fib(n-1) + fib(n-2)
def fibosubarr(n):
L_pointer = 1
R_pointer = 2
sumfibs = 1
while sumfibs != n:
if sumfibs > n and L_pointer < R_pointer:
sumfibs -= fib(L_pointer)
L_pointer += 1
elif sumfibs < n and L_poiner < R_pointer:
sumfibs += fib(R_pointer)
R_pointer += 1
else: return False
return True
n = int(input())
while fibosubarr(n):
n += 1
print(n)
Here's a technique called "memoizing". The fib function here keeps track of the current list and only extends it as necessary. Once it has generated a number, it doesn't need to do it again.
_fib = [1,1]
def fib(n):
while len(_fib) <= n:
_fib.append( _fib[-2]+_fib[-1] )
return _fib[n]
With your scheme, 200000 caused a noticeable delay. With this scheme, even 2 billion runs instantaneously.
To get the next subarray sum, you only need one call of the function -- provided you keep track of the least sum value that was exceeding n.
I would also use a generator for the Fibonacci numbers:
def genfib():
a = 1
b = 1
while True:
yield b
a, b = b, a + b
def fibosubarr(n):
left = genfib()
right = genfib()
sumfibs = next(right)
closest = float("inf")
while sumfibs:
if sumfibs > n:
closest = min(sumfibs, closest)
sumfibs -= next(left)
elif sumfibs < n:
sumfibs += next(right)
else:
return n
return closest
Now you can do as you did -- produce the next valid sum that is at least the input value:
n = int(input())
print(fibosubarr(n))
You could also loop to go from one such sum to the next:
n = 0
for _ in range(10): # first 10 such sums
n = fibosubarr(n+1)
print(n)
There is inreger a which represents the amount of stairs. Each number in list b represents the amount of stairs you can jump from current stair. You need to find out if it is possible to get from first to last stair.
Example of input:
case a)
8
1 3 0 0 2 0 1 1
case b)
3
0 1 1
Example of output:
case a)
True
case b)
False
I managed to create a code which works, but exceeds the time limit. All numbers are positive and have int type. Could you give me an idea how to improve my algorithm (if you can name it so).
My code:
a = int(input())
b = list(map(int, input().split()))
flag = True
count = 0
for i in range(a):
if b[i] > 0:
if count != 0:
position = i - count - 1
if b[position] <= count:
flag = False
break
count = 0
elif b[i] == 0:
if i == 0:
flag = False
break
else:
count += 1
print(flag)
Thank you.
I am trying to make a program that finds primes numbers for a public-key cryptography system. I know that a prime number is a positive integer that has no positive divisors other than 1 and itself. I want to use an approach that that takes all integers from 2 to sqrt(n), to tell if it divides n or not.
I have to take a "brute force" approach that takes in an integer input seed and returns the lowest prime number; prime number >= seed.
Some examples of what I want is :
>>> prime_func(100)
101
>>> prime_func(1000)
1009
>>>prime_func(7)
7
>>>prime_func(3)
5
What I have so far is:
def prime_func(number):
START = 2
END = (number**0.5) + 1
for i in range(START, END):
if number % i == 0:
return('Composite')
else:
return number
For the return ('Composite') part, I want it to instead return the closest prime number after that.
Try the following code:
def prime_func(number):
number = int(number)
START = 2
END = int((number**0.5)) + 1
if number == 2:
return 1
if number == 1:
return 0
while True:
flag = True
for i in range(START, END):
if number % i == 0:
flag = False
break
if flag:
return number
else:
number += 1
if __name__ == '__main__':
num = int(input())
print(prime_func(num))
Input: 100
Output: 101
Input: 1000
Output: 1009
This can be achieved using a Sieve of Eratosthenes.
Code:
def primes_sieve(limit):
a = [True] * limit # Initialize the primality list
a[0] = a[1] = False
for (i, isprime) in enumerate(a):
if isprime:
yield i
for n in range(i*i, limit, i): # Mark factors non-prime
a[n] = False
for value in primes_sieve(32):
print(value)
Output:
2
3
5
7
11
13
17
19
23
29
31
See This Post.
My program should print the sum from even numbers from 2 to 10, but when I pass even_while() in the shell I don't see any result. Which is the problem?
def even_while():
number = 2
s = 0
while number < 10:
if number % 2 == 0:
old_number = number
number = number + 1
s = s + old_number
print(s)
Thanks!
"Infinite loop". number starts as 2. That's even, so add 1 to it. That leaves number as 3. Now the while loop goes around "forever". number % 2 == 0 is never true (number is 3!), and number never changes again.
You don't increment number unless number % 2 == 0, so the while loop doesn't make any progress.
Additionally, you might enjoy the range builtin:
def even_while():
s = 0
for number in range(2, 10):
if number % 2 == 0:
old_number = number
s = s + old_number
print(s)
def even_while():
number = 0
s = 0
while number < 11:
number = number + 1
if number % 2 == 0:
old_number = number
s = s + old_number
print(s)
I think this is ok.