What am I Doing wrong. Google kickstart 2020 [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
this the question.
Ron read a book about boring numbers. According to the book, a positive number is called boring if all of the digits at even positions in the number are even and all of the digits at odd positions are odd. The digits are enumerated from left to right starting from 1. For example, the number 1478 is boring as the odd positions include the digits {1, 7} which are odd and even positions include the digits {4, 8} which are even.
Given two numbers L and R, Ron wants to count how many numbers in the range [L, R] (L and R inclusive) are boring. Ron is unable to solve the problem, hence he needs your help.
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line with two numbers L and R.
Output
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the count of boring numbers.
Sample
3
5 15 Case #1: 6
120 125 Case #2: 3
779 783 Case #3: 2
And this is the result which I have written.
t = int(input())
for case in range(1, t+1):
total_number = 0
numbers = []
l, r = map(int, input().split())
for number in range(l, r+1):
answer = False
for x in range(len(str(number))):
position = x+1
pos_num = int(str(number)[x])
if ((position%2 == 0) and (pos_num%2 == 0)) or ((position%2 ==1) and (position%2 == 1)):
answer = True
else:
answer = False
if answer == True:
numbers.append(number)
total_number += 1
print(f"Case #{case}: {total_number}")
I am running this and getting the wrong results. Where am I doing wrong?

Sorry guys, I got the answer. This is the answer but if anyone can suggest a more efficient answer then, you are most welcome!
t = int(input())
for case in range(1, t + 1):
total_number = 0
numbers = []
l, r = map(int, input().split())
for number in range(l, r + 1):
answer = []
lst_number = list(str(number))
for x in range(len(lst_number)):
position = x + 1
pos_num = int(lst_number[x])
if ((position % 2 == 0) and (pos_num % 2 == 0)) or ((position % 2 == 1) and (pos_num % 2 == 1)):
answer.append(1)
else:
answer.append(0)
if 0 not in answer:
numbers.append(number)
total_number += 1
print(f"Case #{case}: {total_number}")

Related

Turn pseudocode into functioning code to find greatest common divisor [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have the pseudocode here that says: Initialize d to the smaller of m and n.
While d does not evenly divide m or d does not evenly divide n do
Decrease the value of d by 1
Report d as the greatest common divisor of n and m
and I can't figure out what's preventing my code from working. I'll post my code below, if you could take a look for me and tell me what's preventing my code from working properly I'd appreciate it.
m = int(input("Enter a positive integer: "))
n = int(input("Enter another positive integer: "))
d = min(m,n)
while True:
if d % m != 0 or d % n != 0:
d -= 1
elif d % m == 0 and d % n == 0:
print(d)
break
To find if a value evenly divides another, you need to have the smaller (divisor) on the right side of the modulus operator. So change your code to:
if (m %d != 0) or (n % d != 0):
This evaluates if d evenly divides mor n, instead of if m or n evenly divide d.
The condition in your if is basically the opposite of your elif condition, and to evenly divide m means m should be the left side of the modulo operator (same thing for n). I made an edit here to show what I mean:
m = int(input("Enter a positive integer: "))
n = int(input("Enter another positive integer: "))
d = min(m,n)
while m % d != 0 or n % d != 0:
d -= 1
print(d)

How to solve this problem without using recursion? (Number of ways a line can be arranged with restriction)

Good day! I am currently writing a code that solves the way in which a line with n number of people with varying heights can be arranged so that m number of people can see "with no obstruction". A person is "with no obstruction" when all the people in front of that person is shorter than the person itself.
I answered this by using recursion:
def notObstruct(n, m):
if n == 0 and m == 0: return 0
if m == 0 and n >= 1: return 0
if m == n: return 1
if m > n: return 0
return notObstruct(n-1, m-1) + (n-1) * notObstruct(n-1, m)
I used stirling number of the first kind to solve this problem. However, I need to solve this using permutation and combination as a restriction from the problem itself.
notObstruct(5, 3) = 35
notObstruct(7, 2) = 1764
notObstruct(10, 3) = 1172700

How to find the sum of all the divisors of a number, without including it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Finding the sum of all the divisors of a number, without including that particular number that is being divided.
For example if we want to find the divisors of number 6 they would be 1,2,3. Number 6 should be included as it is a divisor, but for this scenario we are not considering it.
Note:- number 3 and 4 are not included since, when you divide number 6 by number 3, there would be a remainder.
A divisor is a number that divides into another without a remainder.
def sum_divisors(n):
sum = 0
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0)) # 0
print(sum_divisors(3)) # Should sum of 1 # 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18 # 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51 # 114
I think I got it:
def sum_divisors(n):
return sum([i for i in range(1, n)
if n % i == 0])
print(sum_divisors(0))
print(sum_divisors(3)) # Should sum of 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
Output
0
1
55
114
You could use a combined filter() and lambda() function
num = 36
div_sum = sum(list(filter(lambda div : num % div == 0 , range(1, num))))
# divisors : [1, 2, 3, 4, 6, 9, 12, 18]
# divisors sum : 55
print('divisors sum : ', div_sum)
We need to find the divisors of the number first, and then sum them. Finding out if a number is a divisor of another number is pretty simple:
if x % y == 0:
is_divisor = True
Modulo - % - returns the remainder of a division. 9 % 2 = 1. 10 % 3 = 1. However, we'll need to know which numbers to check. We could just loop through every number up to our input:
for i in range(n):
if n % i == 0:
is_divisor = True
...but that's too much. For example, we know that the highest possible divisor of n that isn't n itself, is 1/2n if n is even, and lower if it's not. Instead, let's focus on getting each pair, and then check if we should continue. We also need to store all of these numbers, so lets create some lists:
lower_divisors = []
upper_divisors = []
We'll want to know what our current highest lower divisor and lowest highest divisor are, and also know where to start. We can populate the lower divisor list with 1 and the highest with n. We can worry about removing n later.
lower_divisors = [1]
upper_divisors = [n]
continu = True
while continu:
# Let's get the last item in each list
highest_low = lower_divisors[-1]
lowest_high = upper_divisors[-1]
for i in range(highest_low + 1, lowest_high):
if n % i == 0:
lower_divisors.append(i)
upper_divisors.append(n // i)
break
continu = False
# If we've left the loop, we have all of our divisors.
lower_sum = sum(lower_divisors)
higher_sum = sum(upper_divisors) - n #Gotta take it back out!
sm = lower_sum + higher_sum
return sm
That should be a fast way to achieve your goal, without making your computer work harder - but... it's a lot more steps to write. I wrote it in far more steps to make it clear what I was doing and to be readable, but it could definitely be trimmed up a lot.
Upon running the code, the simple method of looping through each number from 1 to n starts to really add up when n is over 8 digits. 9 digit numbers were taking around 12-16 seconds on my machine. The longer approach above returns 32-digit values for n in under 1/10th of a second.

Counting primes [duplicate]

This question already exists:
Checking if a number is prime in Python [duplicate]
Closed 6 years ago.
I am new to programming and I found a problem on the internet to show the 1000th prime number. But the problem is that my code but I have some problems with it.
count=0
prime=[]
n=2
while count != 1000:
if n == 2 or n == 3 or n == 5 or n == 7 or n == 11:
prime.append(n)
n=n+1
count=count+1
elif n%2 == 0 or n%3 == 0 or n%5 == 0 or n%7 == 0 or n%11 == 0:
n=n+1
else:
prime.append(n)
n=n+1
count=count+1
print(prime[999])
The problem comes when I have a number like 403. According to the code I wrote it is prime but actually it is not because it can be divided by 13 and 31.
I came up a solution but I don't know how to do it and if there is a better solution. If you help me, please try preserve my code, please don't give me entirely new code.
My solutions is:
elif n%prime[:]==0
n=n+1
So basically what I'm trying to do is trying to divide the number 403, for example, to any of the other prime numbers that I've recorded earlier. But for some reason this code gives me an error. I want to tell the program "devide n to EVERY number in the list". Thanks for the help :)
You can use "any".
In [15]: prime = [2, 3, 5, 7, 11]
In [16]: n = 15
In [17]: any(n%p == 0 for p in prime)
Out[17]: True
In [18]: n = 17
In [19]: any(n%p == 0 for p in prime)
Out[19]: False
In [20]: n = 19
In [21]: any(n%p == 0 for p in prime)
Out[21]: False
Basically, it will tell you if given number is divisible by "any" of the number in the list.
there are several algorithm to count prime numbers, what you need first is first how to decide whether a function isPrime(n) will return true or false and if you need that this funciton isPrime(n) should be under o(n). There are several approach to do this, here are the possibilities:
def isPrime(n):
i = 2;
while i*i < n:
if n % i == 0:
return false
i = i + 1
return true;
this one will give you prime or not with complexity o(n^1/2), should be sufficient for you, after this the next thing you need to do is:
counter = 0
number = 2
while counter < 1000:
if isPrime(number):
counter = counter + 1;
number = number + 1
print number;
i havent tried this code yet but the concept should be there

Python script which looks for four smallest consecutive numbers with four unique prime factors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
For my school assignment I need to write a program which looks for the numbers with four unique prime factors and are consecutive. So far I got this code, but as result it yields wrong values. What do I do wrong?
# number to start with
n = 2
#function
def factor(x):
factors = []
i = 2
while x > 1:
if x % i == 0:
x = x / i
factors.append(i)
else:
i += 1
factors = sorted(set(factors))
return factors
#loop
while len(factor(n)) !=4 and len(factor(n+1)) !=4 and len(factor(n+2)) !=4 and len(factor(n+3)) !=4:
n+=1
print "The first number is {}, the second number is {}, the third number is {}".format(n-3,n-2, n-1)
print "And the fourth number is {}".format(n)
Although you are right that the numbers in range(204, 208) don't have four factors:
>>> for x in range(204, 208):
print x, factor(x)
204 [2, 3, 17]
205 [5, 41]
206 [2, 103]
207 [3, 23]
you have been misled by your code; you check n, n+1, n+2, n+3 but show n-3, n-2, n-1, n. Your code stopped at n == 207, and if we add three to that:
>>> factor(210)
[2, 3, 5, 7]
So your code stops when it finds the first number where len(factor(x)) == 4. Your logic is backwards; with a while loop like that, you want something that only evaluates False when you've found the answer. Evaluating your four predicates:
>>> True and True and True and False
False
Compare to the same predicates combined with or, instead:
>>> True or True or True or False
True
Now when all four numbers have four factors:
>>> False or False or False or False
False
I think you ended up with and because it follows the logic in your head more closely ("I want the first one to be four, and the second one to be four, and..."). On that basis, your code might be clearer as:
while True:
if len(factor(n)) == 4 and len(factor(n+1)) == 4 and len(factor(n+2)) == 4 and len(factor(n+3)) == 4:
break
n += 1
or, more neatly (and obeying the style guide's line length limit!):
while True:
if all(len(factor(x)) == 4 for x in range(n, n+4)):
break
n += 1

Categories

Resources