Write a program that displays 12 digits,
each digit is equal to three times the digit before him.
I tried to code like this
a , b , c = 1 , 1 , 1
print(c)
while c < 12 : # for looping
c = c + 1 # c for counting
b = a+b
y = 3*b
print(c,y)
can any one help me to correct the result
You can use power operator for that:
from itertools import islice
def numbers(x, base=3):
n = 0
while True:
yield x * base ** n
n += 1
for n in islice(numbers(1), 12):
print(n)
Or if you really like your way of doing that, here's a fixed version of your code:
b, c = 1, 0
while c < 12:
print(c, b)
b *= 3
c += 1
You can start with a list where first element is the beginning of the multiples:
-- start with 1 or the number you like
multiples = [1]
for i in range(1, 12):
multiples.append(3 * multiples[i - 1])
print(multiples)
-- Output : [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147]
Related
The following code generate random number of 2d arrays and I want to print how many values in each pair are divisible to 3. For example assume we have an array [[2, 10], [1, 6], [4, 8]].
So the first pair which is [2,10] has 3 ,6 and 9 which are totally 3 and second pair has 3 and 6 which are totally two and last pair[4,8] has just 1 divisible to 3 which is 6. Therefore, The final out put should print sum of total number of divisible values which is 3+2+1=6
a=random.randint(1, 10)
b = np.random.randint(1,10,(a,2))
b = [sorted(i) for i in b]
c = np.array(b)
counter = 0;
for i in range(len(c)):
d=(c[i,0],c[i,1])
if (i % 3 == 0):
counter = counter + 1
print(counter)
One way is to count how many integers in the interval are divisible by 3 by testing each one.
Another way, and this is much more efficient if your intervals are huge, is to use math.
Take the interval [2, 10].
2 / 3 = 0.66; ceil(2 / 3) = 1.
10 / 3 = 3.33; floor(10 / 3) = 3.
Now we need to count how many integers exist between 0.66 and 3.33, or count how many integers exist between 1 and 3. Hey, that sounds an awful lot like subtraction! (and then adding one)
Let's write this as a function
from math import floor, ceil
def numdiv(x, y, div):
return floor(y / div) - ceil(x / div) + 1
So given a list of intervals, we can call it like so:
count = 0
intervals = [[2, 10], [1, 6], [4, 8]]
for interval in intervals:
count += numdiv(interval[0], interval[1], 3)
print(count)
Or using a list comprehension and sum:
count = sum([numdiv(interval[0], interval[1], 3) for interval in intervals])
You can use sum() builtin for the task:
l = [[2, 10], [1, 6], [4, 8]]
print( sum(v % 3 == 0 for a, b in l for v in range(a, b+1)) )
Prints:
6
EDIT: To count number of perfect squares:
def is_square(n):
return (n**.5).is_integer()
print( sum(is_square(v) for a, b in l for v in range(a, b+1)) )
Prints:
5
EDIT 2: To print info about each interval, just combine the two examples above. For example:
def is_square(n):
return (n**.5).is_integer()
for a, b in l:
print('Pair {},{}:'.format(a, b))
print('Number of divisible 3: {}'.format(sum(v % 3 == 0 for v in range(a, b+1))))
print('Number squares: {}'.format(sum(is_square(v) for v in range(a, b+1))))
print()
Prints:
Pair 2,10:
Number of divisible 3: 3
Number squares: 2
Pair 1,6:
Number of divisible 3: 2
Number squares: 2
Pair 4,8:
Number of divisible 3: 1
Number squares: 1
The python code, given in a lab for a class I'm in when executed through pycharm, ouputs 0. However, upon looking at the code, it should be 1. Why is it 0?
X = 4
C = 0
while X > 0:
if X % 2 == 0:
C = C + 1
else:
C = C - 1
X = X - 1
print(C)
The code is fine. Your X will go from 4 to 1 and on X = 0, the program will leave the loop. Printing X-C for each iteration gives the values:
X-C
4-1
3-0
2-1
1-0
If you want it to go till 0, make the condition as:
while X >= 0:
The loop executes 4 times: When X = 4, C = 1; when X = 3, C = 0; when X = 2, C = 1; when X = 1, C = 0.
I am analyzing counting example in python presented by Codility
I don't understand the logic used in the last loop (5 last rows) of this algorithm.
Can anybody help please?
The problem:
You are given an integer m (1 < m < 1000000) and two non-empty,
zero-indexed arrays A and B of n integers, a0, a1, ... ,
an−1 and b0, b1, ... , bn−1 respectively (0 < ai, bi < m).
The goal is to check whether there is a swap operation which can be
performed on these arrays in such a way that the sum of elements in
array A equals the sum of elements in array B after the swap. By
swap operation we mean picking one element from array A and one
element from array B and exchanging them.
The solution:
def counting(A, m):
n = len(A)
count = [0] * (m + 1)
for k in xrange(n):
count[A[k]] += 1
return count
def fast_solution(A, B, m):
n = len(A)
sum_a = sum(A)
sum_b = sum(B)
d = sum_b - sum_a
if d % 2 == 1:
return False
d //= 2
count = counting(A, m)
for i in xrange(n):
if 0 <= B[i] - d and B[i] - d <= m and count[B[i] - d] > 0:
return True
return False
What I would recommend you is read again the explanations given in the exercise. It already explains what how the algorithm works. However, if you still have problems with it, then take a piece of paper, and some very simple example arrays and go through the solution step by step.
For example, let A = [6, 6, 1, 2, 3] and B = [1, 5, 3, 2, 1].
Now let's go through the algorithm.
I assume you understand how this method works:
def counting(A, m):
n = len(A)
count = [0] * (m + 1)
for k in xrange(n):
count[A[k]] += 1
return count
It just returns a list with counts as explained in the exercise. For list A and m = 10 it will return:
[0, 1, 1, 1, 0, 0, 2, 0, 0, 0, 0]
Then we go through the main method fast_solution(A, B, m):
n = 11 (this will be used in the loop)
The sum of A equals 18 and the sum of B equals 12.
The difference d is -6 (sum_b - sum_a), it is even. Note that if difference is odd, then no swap is available and the result is False.
Then d is divided by 2. It becomes -3.
For A we get count [0, 1, 1, 1, 0, 0, 2, 0, 0, 0, 0] (as already mentioned before).
Then we just iterate though the list B using xrange and check the conditions (The loop goes from 0 and up to but not including 11). Let's check it step by step:
i = 0, B[0] - (-3) is 1 + 3 = 4. 4 is greater than or equal to 0 and less than or equal to 10 (remember, we have chosen m to be 10). However, count[4] is 0 and it's not greater than 0 (Note the list count starts from index 0). The condition fails, we go further.
i = 1, B[1] - (-3) is 5 + 3 = 8. 8 is greater than or equal to 0 and less than or equal to 10. However, count[8] is 0 and the condition fails.
i = 2, B[2] - (-3) is 3 + 3 = 6. 6 is greater than 0 and less than 10. Also count[6] is 2 and it is greater than 0. So we found the number. The loop stops, True is returned. It means that there is such a number in B which can be swapped with a number in A, so that sum of A becomes equal to the sum of B. Indeed, if we swap 6 in A with 3 in B, then their sum become equal to 15.
Hope this helps.
I'm not sure I get your idea correctly. Here's my understanding:
def counting(A, m):
n = len(A)
count = [0] * (m + 1)
for k in xrange(n):
count[A[k]] += 1
return count # this essentially build a counter
def fast_solution(A, B, m):
n = len(A)
sum_a = sum(A)
sum_b = sum(B)
d = sum_b - sum_a
if d % 2 == 1:
return False
d //= 2
count = counting(A, m) # get the dict
for i in xrange(n):
if 0 <= B[i] - d and B[i] - d <= m and count[B[i] - d] > 0:
# the first two conditions are to verify that B[i]-d exists as a key (index) in counter.
# then check if there actually exists the value.
# if count > 0, then you can swap the two to get same sum
return True
return False
Or rewriting to get:
def counting(A, m):
count = collections.Counter()
for i in A:
count[i] += 1
return count
def fast_solution(A, B, m):
n = len(A)
sum_a = sum(A)
sum_b = sum(B)
d = sum_b - sum_a
if d % 2 == 1:
return False
d //= 2
count = counting(A, m) # get the dict
for i in B:
if count[i-d]:
return True
return False
But in any case, this piece of code just check the solution existence with only single swap, be sure to check if that's what you wanted.
I need to make a quick algorithm(I already made a slow one) which will find the number of all possible values from two ranges of integer numbers (ranges can intersect or not) which sum will be the given number
I can represent it like an equation: z = x + y
where z is a known number and equals x plus y
z can be any number between 0 and 10^18
x belongs to a range of integer numbers [a..b], where 0 <= a <= b <= 10^18 and
the difference between the consecutive numbers is 1
y belongs to a range of integer numbers [c..d], where 0 <= c <= d <= 10^18 and
the difference between the consecutive numbers is 1
so I need to find the number(not their exact values) of all the possible variations of x and y from two sets of numbers which sum will be z
Example:
z = 5
first set: a = 1, b = 5(it means the set consists of 1,2,3,4,5)
second set: c = 1, b = 5
then the answer is 4, because all possible combinations are:
x = 4, y = 1
x = 3, y = 2
x = 2, y = 3
x = 1, y = 4
because theirs sums are 5's
The compulsory condition for an algrorithm is to work faster than 1 second
The following code works fine but only with numbers lesser than 1000000. It starts to work much slower with big numbers
with open(r"input.txt") as f:
n = int(f.readline()) # the given number
a = int(f.readline()) # the start position of the first set
b = int(f.readline()) # the end position of the first set
c = int(f.readline()) # the start position of the second set
d = int(f.readline()) # the end position of the second set
# print "n:",n,"a:",a,"b:",b,"c:",c,"d:",d
t = b - a + 1 # all posible variants of the first set
k = d - c + 1 # all posible variants of the second set
number_of_vars = 0
if t >= k:
while b >= a:
if (n - b <= d) \
and (n - b>= c):
number_of_vars += 1
b -= 1
else:
b -= 1
if t < k:
while d >= c:
if (n-d <= b) and (n-d >= a):
number_of_vars += 1
d -= 1
else:
d -= 1
print number_of_vars
No algorithm required -- just algebra:
It suffices to count the number of x in [a,b] for which z - x is in [c,d]
You need both a <= x <= b and c <= z - x <= d. The second inequality is equivalent to z - d <= x <= z - c hence you need
max(a, z - d) <= x <= min(b,z - c)
The number of such x is 0 if min(b,z - c) < max(a, z - d) otherwise it is
min(b,z - c) - max(a, z - d) + 1
In either case the number of solutions is
max(0, min(b,z - c) - max(a, z - d) + 1)
In your example a = c = 1 and b = d = z = 5 and
min(b, z - c) - max(a, z - d) + 1 = min(5,4) - max(1,0) + 1 = 4 - 1 + 1 = 4
One thing that you can use to reduce the checks in your algorithm is,
If the range for the 2 sets are overlapping, then you can cancel out some checks. Like in your example,
range for 1st set is 1 to 5
range for 2nd set is 1 to 5
So, if
x = 4, y = 1
is working, then
x = 1, y = 4
will also work. So you have to go only till half the number (i.e till 3 only in this case)
If only a part of the range is overlapping, then you can use the above method for that part, and the remaining part can be checked using normal method.
I have a task to make a program that will sum the first 100 Fibonacci numbers. I checked my output in Python, and my output in QBasic 64 and they aren't same. I checked with different inputs also.
Input: 10
Output: 89
-----------
Input: 100
Output: 573147844013817084101
Is it correct ?
Here is my code:
n = int(input())
print()
p = 0
d = 1
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
for i in range(n - 2):
p = d
d = z
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
print('Sum:', z)
EDIT: Code edited again, check it now. I just found on Wikipedia.. It depends from what number you start the loop. So if I use (0, 1, 1, 2, 3, 5, 8, 13, 21, and 34) as first 10 Fibonacci numbers, the sum is going to be 88, not 89.
The sums of the first ten and 100 fibonacchi number would be 88 and 573147844013817084100, respectively:
>>> cache = {}
>>> def fib(n):
if n == 0: return 0
if n == 1: return 1
if not n in cache:
cache[n] = fib(n - 1) + fib(n - 2)
return cache[n]
>>> sum([fib(i) for i in range(10)])
88
>>> sum([fib(i) for i in range(100)])
573147844013817084100
In your loop you are already starting the iteration at the 3rd position, since you set. So set your range to (n -2).
0: 1
1 : 1
2 : 1
3 : 2
4 : 3
5 : 5
To get the sum of the Fibonacci numbers, using zero as the first in the series, you need to do this:
def run_it(n):
N2 = 0
N1 = 0
N = 0
z = N
for i in range(n):
print(N,z)
N2 = N1
N1 = N
if N is 0: N = 1
else: N = N1 + N2
z = z + N
run_it(int(input('Number: ')))
To calculate the sum using one as the start of the series, change the initial value of N from zero to one.