I'm trying to print the first 12 numbers in the Fibonacci. My idea is to increment the two list index numbers.
list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers
listint = list[0] #sets the list variable I want to incremented
list2int = list[1] #set the other list variable to be incremented
while len(list) < 13: #sets my loop to stop when it has 12 numbers in it
x = listint + list2int #calculates number at index 2
list.append(x) #appends new number to list
listint += 1 #here is where it is supposed to be incrementing the index
list2int +=1
print list
My output is:
[0, 1, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
I want:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
Please note I am a beginner, and I'm trying to do this without using an built in functions. (I'm sure there is some sort of fibonacci sequence generator).
Thanks in advance for your help!
The problem is in the two last lines of the while loop. You are adding 1 each time instead of using the last two elements of the list that are the previous fibonacci numbers:
list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers
listint = list[0] #sets the list variable I want to incremented
list2int = list[1] #set the other list variable to be incremented
while len(list) < 13: #sets my loop to stop when it has 12 numbers in it
x = listint + list2int #calculates number at index 2
list.append(x) #appends new number to list
listint = list[-2] #here is where it is supposed to be incrementing the index
list2int = list[-1]
print list
list = [0,1]
while len(list) < 12:
list.append(list[len(list)-1]+list[len(list)-2])
print list
Not very performant, but quick and dirty.
use < 12 because in 11th loop you'll add the 12th entry to the list.
With list[x] you access the x number of entry starting with 0 for the first entry.
edit:
output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
change the first line of the while loop:
list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers
listint = list[0] #sets the list variable I want to incremented
list2int = list[1] #set the other list variable to be incremented
while len(list) < 12: #sets my loop to stop when it has 12 numbers in it
x = list[listint] + list[list2int] #calculates number at index 2
list.append(x) #appends new number to list
listint += 1 #here is where it is supposed to be incrementing the index
list2int +=1
print list
Also to get the 1st 12 numbers you can set your while loop condition to < 12 because Python list indices start from 0.
Related
Given an integer n and array a, I need to find for each i, 1≤ i ≤ n, how many elements on the left are less than or equal to ai
Example:
5
1 2 1 1 2
Output
0 1 1 2 4
I can do it in O(N2) but I want to ask if there is any way to do it faster, since N is very large (N ≤ 106)?
You can use a segment tree, you just need to use a modified version called a range tree.
Range trees allow rectangle queries, so you can make the dimensions be index and value, and ask "What has value more than x, and index between 1 and n?"
Queries can be accomplished in O(log n) assuming certain common optimizations.
Either way O(N^2) is completely fine with N < 10^6.
I like to consider a bigger array to explain, so let's consider following array,
2, 1, 3, 4, 7, 6, 5, 8, 9, 10, 12, 0, 11, 13, 8, 9, 12, 20, 30, 60
The naïve way is to compare an element with all elements at left of it. Naïve approach has complexity of O(n^2) which make it not useful for big array.
If you look this problem closely you will find a pattern in it, and the pattern is Rather than comparing with each left element of an element we can compare first and last value of a range!. Wait a minute what is the range here?
These numbers can be viewed as ranges and there ranges can be created from traversing left to right in array. Ranges are as follows,
[2], [1, 3, 4, 7], [6], [5, 8, 9, 10, 12], [0, 11, 13], [8, 9, 12, 20, 30, 60]
Let’s start traversing array from left to right and see how we can create these ranges and how these ranges shall reduce the effort to find all small or equal elements at left of an element.
Index 0 have no element at its left to compare thus why we start form index 1, at this point we don’t have any range. Now we compare value of index 1 and index 0. Value 1 is not less than or equals to 2, so this is very import comparison, due to this comparison we know the previous range should end here because now numbers are not in acceding order and at this point we get first range [2], which contains only single element and number of elements less than or equals to left of element at index 1 is zero.
As continue with traversing left to right at index 2 we compare it with previous element which is at index 1 now value 1 <= 3 it means a new range is not staring here and we are still in same range which started at index 1. So to find how many elements less than or equals, we have to calculate first how many elements in current range [1, 3), in this case only one element and we have only one know range [2] at this point and it has one element which is less than 3 so total number of less than or equals elements at the left of element at index 2 is = 1 + 1 = 2. This can be done in similar way for rest of elements and I would like to jump directly at index 6 which is number 5,
At index 6, we have all ready discovered three ranges [2], [1, 3, 4, 7], [6] but only two ranges [2] and [1, 3, 4, 7] shall be considered. How I know in advance that range [6] is not useful without comparing will be explained at the end of this explanation. To find number of less than or equals elements at left, we can see first range [2] have only one element and it is less than 5, second range have first element 1 which is less than 5 but last element is 7 and it is greater than 5, so we cannot consider all elements of range rather we have to find upper bound in this range to find how many elements we can consider and upper bound can be found by binary search because range is sorted , so this range contains three elements 1, 3, 4 which are less then or equals to 5. Total number of elements less than or equals to 5 from two ranges is 4 and index 6 is first element of current range and there is no element at left of it in current range so total count = 1 + 3 + 0 = 4.
Last point on this explanation is, we have to store ranges in tree structure with their first value as key and value of the node should be array of pair of first and last index of range. I will use here std::map. This tree structure is required so that we can find all the range having first element less than or equals to our current element in logarithmic time by finding upper bound. That is the reason, I knew in advance when I was comparing element at index 6 that all three ranges known that time are not considerable and only two of them are considerable .
Complexity of solution is,
O(n) to travels from left to right in array, plus
O(n (m + log m)) for finding upper bound in std::map for each element and comparing last value of m ranges, here m is number of ranges know at particular time, plus
O(log q) for finding upper bound in a range if rage last element is greater than number, here q is number of element in particular range (It may or may not requires)
#include <iostream>
#include <map>
#include <vector>
#include <iterator>
#include <algorithm>
unsigned lessThanOrEqualCountFromRage(int num, const std::vector<int>& numList,
const std::map<int,
std::vector<std::pair<int, int>>>& rangeMap){
using const_iter = std::map<int, std::vector<std::pair<int, int>>>::const_iterator;
unsigned count = 0;
const_iter upperBoundIt = rangeMap.upper_bound(num);
for(const_iter it = rangeMap.cbegin(); upperBoundIt != it; ++it){
for(const std::pair<int, int>& range : it->second){
if(numList[range.second] <= num){
count += (range.second - range.first) + 1;
}
else{
auto rangeIt = numList.cbegin() + range.first;
count += std::upper_bound(rangeIt, numList.cbegin() +
range.second, num) - rangeIt;
}
}
}
return count;
}
std::vector<unsigned> lessThanOrEqualCount(const std::vector<int>& numList){
std::vector<unsigned> leftCountList;
leftCountList.reserve(numList.size());
leftCountList.push_back(0);
std::map<int, std::vector<std::pair<int, int>>> rangeMap;
std::vector<int>::const_iterator rangeFirstIt = numList.cbegin();
for(std::vector<int>::const_iterator it = rangeFirstIt + 1, endIt = numList.cend();
endIt != it;){
std::vector<int>::const_iterator preIt = rangeFirstIt;
while(endIt != it && *preIt <= *it){
leftCountList.push_back((it - rangeFirstIt) +
lessThanOrEqualCountFromRage(*it,
numList, rangeMap));
++preIt;
++it;
}
if(endIt != it){
int rangeFirstIndex = rangeFirstIt - numList.cbegin();
int rangeLastIndex = preIt - numList.cbegin();
std::map<int, std::vector<std::pair<int, int>>>::iterator rangeEntryIt =
rangeMap.find(*rangeFirstIt);
if(rangeMap.end() != rangeEntryIt){
rangeEntryIt->second.emplace_back(rangeFirstIndex, rangeLastIndex);
}
else{
rangeMap.emplace(*rangeFirstIt, std::vector<std::pair<int, int>>{
{rangeFirstIndex,rangeLastIndex}});
}
leftCountList.push_back(lessThanOrEqualCountFromRage(*it, numList,
rangeMap));
rangeFirstIt = it;
++it;
}
}
return leftCountList;
}
int main(int , char *[]){
std::vector<int> numList{2, 1, 3, 4, 7, 6, 5, 8, 9, 10, 12,
0, 11, 13, 8, 9, 12, 20, 30, 60};
std::vector<unsigned> countList = lessThanOrEqualCount(numList);
std::copy(countList.cbegin(), countList.cend(),
std::ostream_iterator<unsigned>(std::cout, ", "));
std::cout<< '\n';
}
Output:
0, 0, 2, 3, 4, 4, 4, 7, 8, 9, 10, 0, 11, 13, 9, 11, 15, 17, 18, 19,
Yes, It can be done in better time complexity compared to O(N^2) i.e O(NlogN). We can use the Divide and Conquer Algorithm and Tree concept.
want to see the source code of above mentioned two algorithms???
Visit Here .
I think O(N^2) should be the worst case. In this situation, we will have to traverse the array at least two times.
I have tried in O(N^2):
import java.io.*;
import java.lang.*;
public class GFG {
public static void main (String[] args) {
int a[]={1,2,1,1,2};
int i=0;
int count=0;
int b[]=new int[a.length];
for(i=0;i<a.length;i++)
{
for(int c=0;c<i;c++)
{
if(a[i]>=a[c])
{
count++;
}
}
b[i]=count;
count=0;
}
for(int j=0;j<b.length;j++)
System.out.print(b[j]+" ");
}`
I am given this algorithmic problem, and need to find a way to return the count in a list S and another list L that is between some variable x and some variable y, inclusive, that runs in O(1) time:
I've issued a challenge against Jack. He will submit a list of his favorite years (from 0 to 2020). If Jack really likes a year,
he may list it multiple times. Since Jack comes up with this list on the fly, it is in no
particular order. Specifically, the list is not sorted, nor do years that appear in the list
multiple times appear next to each other in the list.
I will also submit such a list of years.
I then will ask Jack to pick a random year between 0 and 2020. Suppose Jack picks the year x.
At the same time, I will also then pick a random year between 0 and 2020. Suppose I
pick the year y. Without loss of generality, suppose that x ≤ y.
Once x and y are picked, Jack and I get a very short amount of time (perhaps 5
seconds) to decide if we want to re-do the process of selecting x and y.
If no one asks for a re-do, then we count the number of entries in Jack's list that are
between x and y inclusively and the number of entries in my list that are between x and
y inclusively.
More technically, here is the situation. You are given lists S and L of m and n integers,
respectively, in the range [0, k], representing the collections of years selected by Jack and
I. You may preprocess S and L in O(m+n+k) time. You must then give an algorithm
that runs in O(1) time – so that I can decide if I need to ask for a re-do – that solves the
following problem:
Input: Two integers, x as a member of [0,k] and y as a member of [0,k]
Output: the number of entries in S in the range [x, y], and the number of entries in L in [x, y].
For example, suppose S = {3, 1, 9, 2, 2, 3, 4}. Given x = 2 and y = 3, the returned count
would be 4.
I would prefer pseudocode; it helps me understand the problem a bit easier.
Implementing the approach of user3386109 taking care of edge case of x = 0.
user3386109 : Make a histogram, and then compute the accumulated sum for each entry in the histogram. Suppose S={3,1,9,2,2,3,4} and k is 9. The histogram is H={0,1,2,2,1,0,0,0,0,1}. After accumulating, H={0,1,3,5,6,6,6,6,6,7}. Given x=2 and y=3, the count is H[y] - H[x-1] = H[3] - H[1] = 5 - 1 = 4. Of course, x=0 is a corner case that has to be handled.
# INPUT
S = [3, 1, 9, 2, 2, 3, 4]
L = [2, 9, 4, 6, 8, 5, 3]
k = 9
x = 2
y = 3
# Histogram for S
S_hist = [0]*(k+1)
for element in S:
S_hist[element] = S_hist[element] + 1
# Storing prefix sum in S_hist
sum = S_hist[0]
for index in range(1,k+1):
sum = sum + S_hist[index]
S_hist[index] = sum
# Similar approach for L
# Histogram for L
L_hist = [0] * (k+1)
for element in L:
L_hist[element] = L_hist[element] + 1
# Stroing prefix sum in L_hist
sum = L_hist[0]
for index in range(1,k+1):
sum = sum + L_hist[index]
L_hist[index] = sum
# Finding number of elements between x and y (inclusive) in S
print("number of elements between x and y (inclusive) in S:")
if(x == 0):
print(S_hist[y])
else:
print(S_hist[y] - S_hist[x-1])
# Finding number of elements between x and y (inclusive) in S
print("number of elements between x and y (inclusive) in L:")
if(x == 0):
print(L_hist[y])
else:
print(L_hist[y] - L_hist[x-1])
Suppose I have two lists with elements that are natural numbers.
Set A has n elements and Set B starts with a single element.
Now could i code a program that takes a member from Set A, performs an operation
involving all the elements from Set B and then adds the element from set A to set B. Repeating this process until all elements from set A have been added to set B.
Example:
Set A = {3, 4, 5, 6} & Set B = {2}
Check to see if the first element from set A can be divided wholly by any element from set B. After this check has been done the first element from A goes to set B.
Set A = {4, 5, 6} & Set B = {2, 3}
Repeat
Set A = {5, 6} & Set B = { 2, 3, 4 }
Repeat
Set A = {6} & Set B = { 2, 3, 4, 5 }
Repeat
Set A = {} & Set B = { 2, 3, 4, 5, 6 }
END
RESOLVED
def getprime(n):
for p in range(2, n+1):
for i in range(2, p):
if p % i == 0:
break
else:
print(p)
This code solves your example question
Check to see if the first element from set A can be divided wholly by all elements from set B. After this check has been done the first element from A goes to set B.
I hope you can understand how to apply this to other similar questions.
A = [2, 4, 5, 6]
B = [2]
# while the list A is not empty
while len(A) > 0:
# the first number in the list
num = A[0]
# for every element in list B
for j in B:
fully_divisible = True
# the the number is not divisible by a number from list B
if num % j != 0:
fully_divisible = False
if fully_divisible:
# this will only print if ALL the numbers currently in list B are divisible by num
print num, "can be divided wholly by all elements from set B"
else:
# this will print if there is at least one number in list B the is not divisible by num
print num, "cannot be divided wholly by all elements from set B"
# remove the first element from list A, next time we loop the first element of the list (A[0]) will be different
A.remove(num)
# add that number to list B
B.append(num)
Output:
2 can be divided wholly by all elements from set B
4 can be divided wholly by all elements from set B
5 cannot be divided wholly by all elements from set B
6 cannot be divided wholly by all elements from set B
It is known that there exists C(100,10) possibilities of selecting 10 different numbers from 1 to 100. each possibility is a combination like [1, 2,..., 10] or [2,3,...,11], or [11, 22, 33, .., 99, 100], as long as the 10 numbers are different.
How to list all the combinations by programming??
I don't want to write 10 Loops, python or c preferred
Using python and itertools.combinations.
Warning - Printing will take a long time
for i in itertools.combinations(xrange(1,101),10):
print i
My friend, Yujie Liu came up this idea. Using pure iteration.
# select n diff numbers from min - max
def traceArr(arr, min, max, n):
if n > 0:
for i in range(min, max-n+2):
arr1 = arr[:]
arr1.append(i)
traceArr(arr1, i+1, max, n-1)
elif n == 0:
print arr
# Demo, select 5 diff numbers from 1-10
traceArr([], 1, 10, 5);
I'm trying to find, for a list of numbers from 1 to 50, what numbers within that range are the sums of two other specific numbers from another list. The other list is 1, 2, 4, 6, 18, 26.
I'm basically trying to run a "for x in range(1,50):" type program that then lists all the numbers from 1 to 50 and next to them says "TRUE" if they are the sum of any two of the numbers in that list (e.g. 1 + 1, 1 + 4, 1 + 26, 4 + 18, 18 + 26 etc etc).
Any ideas??
Thank you!!
Matt
Iterate over all possible pairs of numbers:
sums = []
for n1 in numbers:
for n2 in numbers:
# Add them together and store the result in `sums`
And then check to see if every number from range(50) is in your list of sums:
for n in range(50):
if n in sums:
# `n` is the sum of two numbers from your list
def solveMeFirst(a,b):
# Hint: Type return a+b below
return a+b
num1 = int(input())
num2 = int(input())
res = solveMeFirst(num1,num2)
print(res)