I couldn't find an answer by searching and I've been working on this for two days and am stumped. I think I am just confused on the math. I am trying to write a function that finds the first n triangular numbers.
def formula(n):
i = 1
while i <= n:
print i, '\t', n * (n + 1)/ 2
i += 1
print
So for example if I type in formula(5) it would look like this:
1 1
2 3
3 6
4 10
5 15
I got how to make a table going from 1 through whatever number I choose n.. but I can't figure out how to make the second part equal the formula I typed in which would be n*(n+1)/2. What is the logic going through this? Everytime I type in formula(5) for example the loop goes from 1-5 but returns the same exact answer in the right hand column all the way down which would be 15. I can't make it to where it would start at 1, 3, 6 etc on the right hand side.
The comment that observed that you are computing n * (n + 1) / 2 instead of i * (i + 1) / 2 is correct. You can also get rid of having to do a multiplication and division at each step by observing that the i-th triangle number is simply the sum of the integers from 1 to i, so at each step you just have to add i to the previous triangle number. Code below:
def formula(n):
ith_sum = 0
for i in xrange(1, n+1):
ith_sum += i
print i, '\t', ith_sum
I had completely forgotten about triangular numbers, thank you for the question! I am glad you now know the correct solution. I was curious if it could be done a different way:
def triangular(number):
return number + triangular(number-1) if number else 0
print triangular(5)
If you fancy a challenge, you could try and work this out. A print statement here and there would help you spot what is happening.
This is a simple solution that worked for me
def print_triangular_numbers(n):
for i in range(n+1):
print(i, int(i * (i + 1)/ 2))
print_triangular_numbers(5)
This is not the answer to this question. So delete it as soon as you read it.
It is the answer for printing
#
##
###
####
#####
######
on the console.
Follwing is the code for it :
var strng="";
for (var i=1; i<7; i++)
{
for (var j=1; j<=i; j++)
{
strng=strng+"#";
}
strng=strng+"\n";
}
console.log(strng);
Related
I'm very new to python and coding, been given some exercises to try and complete and there's one that I just can't get, it's not essential to have it solved but not knowing is annoying me so much. I have to create a loop of the first 10 cube numbers I've been able to do this with square numbers and I tried to use the same process but it's not working
Cubes=[]
for i in range((11)):
Cubes.append(i**3)
But all I'm getting is -
runfile('C:/Users/Hannah/Cubes.py', wdir='C:/Users/Hannah')
What am I doing wrong
If you want numbers to show on your screen you should use something like this:
Cubes=[]
for i in range((11)):
Cubes.append(i**3)
print(Cubes)
or
Cubes=[]
for i in range((11)):
Cubes.append(i**3)
print(i**3)
Try to note the difference. Good luck!
First, you forgot to print it. Second good job.
def Cubes
Cubes=[]
for i in range(10):
Cubes.append(i**3)
print Cubes
This is what you want. Hope it helps
maximum = input("Enter Max: ")
r = range(1, maximum)
Cube = maximum * maximum * maximum
for j in r:
if j * j * j <= Cube:
print (j * j * j)
I am not so proficient in python. I had this code in a practice coding. Since it is a golf code problem, i thought of trying python as i have some knowledge about it.
This is my program
Hack sequence of IndiaHacks-2014 if given as below
Hi = 2014*Hi-1 + 69*Hi-2 for (i>2)
Hi = 1 for (i<=2)
Given n, you need to find nth term of Hack sequence
I have used the following code
T = input()
for i in range(T):
N = int(input())
if N <= 2:
print 1
else :
a = [1,1]
j=2
while j < N :
a.append((2014 * a[j-1]) + (69 * a[j-2]))
j++
print a[N-1]
But i get the following error
SyntaxError:
invalid syntax
11, 7, \t\t\tj++\n
Can anyone please tell me what is wrong with this code and why am I getting this error?
Use j += 1 instead of j++. There is no ++ operator in python.
OR in this case simply don't use manually incremented loop variable:
T = input()
# I'm not sure about this part of your code:
# (indentation and the expected value of T)
for i in range(T):
N = int(input())
# To solve this problem you don't have to populate an array,
# you always need only the last two items:
prev2, prev1 = 1, 1
# We could omit this "if" check because the range(N-2) expression
# generates nothing when the input parameter is zero or less,
# that is: when N <= 2.
if N > 2:
# Note: in case of python3 use range(), in case of python2 use xrange()
for _ in range(N-2):
new = (2014 * prev1) + (69 * prev2)
prev2, prev1 = prev1, new
print prev1
To solve this problem you don't need an array but even if you needed an array you could run the j loop variable from 2 to N-1 with for j in range(2, N):. Note that in python you could simply use array[-1] and array[-2] to address the last two items of the array instead of calculating the absolute index (like array[N-1]). Python arrays can be indexed with a negative number relative to the end of the array.
There is no j++ in python. Use j += 1.
The source of the question.
It's an interview question, so I think it should have a solution, but I'm not sure what it is and can't find any.
The problem is this:
Given an array of numbers, check if it is possible, with additions and subtractions placed anywhere, to make the sum zero.
eg:
A={2,1,8,5}
+2-1+8+5 != 0
-2-1+8+5 != 0
+2-1-8+5 != 0
-2-1+8-5 == 0
thus done.
I already have the code for the exponential solution:
def isFeasible(A, p, _sum):
if p == len(A):
if _sum==0: return True
else: return False;
return (isFeasible(A, p+1, _sum+A[p]) or isFeasible(A, p+1, _sum-A[p]))
def driver(arr):
print isFeasible(arr,0,0)
Let's call your numbers A[i] for i = 1..N. You need to solve the following equation:
sum(X[i] * A[i]) = 0, for X[i] = -1 or 1
Obviously, this is equivalent to (just change -1 to 0 in X[]):
sum(X[i] * 2*A[i]) = sum(A[i]), for X[i] = 0 or 1
The second problem is exactly the partition problem for numbers (A[i]), which is NP-hard if numbers are arbitrary. Also, the partition problem is the simplest case of the well-known knapsack problem. Just read both wikipedia articles and you'll learn a lot of ways to solve the problem.
EDIT: Yet another equivalent problem is:
sum(X[i] * A[i]) = sum((1 - X[i]) * A[i]) for X[i] = 0 or 1
It is the same as the second equation, but now it is clearly visible that this is a partition problem: X[i] = 1 means put element to the left, X[i] = 0 means put element to the right. After all the elements are put, sums must be equal.
Also note that there is a pseudopolynomial solution here, it can be also turned into a fully polynomial approximation scheme. Also note that the knapsack problem can be solved by meet-in-the-middle approach, which reduces time complexity of exponential solution from O(2^N) to O(sqrt(2)^N).
Conclusion: read the wikipedia articles on these problems, you'll find all the info there.
You can improve your exponential solution by using memoization: if you already know the answer for _sum, return that. Otherwise, compute it and store it.
However, I want to present a more interesting solution. This is the official solution to a similar problem from a local online judge. In that problem, we had to find the actual assignment of +/- to each number, and it guaranteed that there exists a solution.
The solution was to keep two sets: a set of numbers that are added and a set of numbers that are subtracted. Then, we would randomly do the following while a solution was not found:
if the current sum is smaller than the target:
move a random element from the - set to the + set
else:
move a random element from the + set to the - set
While doing these moves, you can update the current sum in O(1).
This worked for 50 000 numbers in under one second on the online judge. For your problem, you could see if it finds a solution under the given time constrains, and assume there isn't one if it doesn't.
I don't know if this works in general or only on specifically-crafted inputs. Maybe someone else can comment on that, but I was always surprised how well it worked on that problem and that it was the official solution.
Let me know if I am missing something.
You can easily reduce this to a Subset Sum problem , that is given an array a and value k find out if there is a subset whose sum is k.
Let me explain why this problem is same as Subset sum problem.
Say sum of all elements in your array is X. What you want to do is : assign - sign to subset of elements whose sum x/2 and the remaining elements assign + so that your total sum will be zero.
So In your question what you want to find out is if there is a subset whose sum exactly X/2, if there is a subarray like that then assign- all those elements and automatically the sum of total array will be zero.
Now your solution is:
array - a
sum of all elements -x
return isSubsetSum(a,x/2)
And you can write a simple dynamic programming solution to find out this:
bool isSubsetSum(int set[], int n, int sum)
{
bool subset[sum+1][n+1];
for (int i = 0; i <= n; i++)
subset[0][i] = true;
for (int i = 1; i <= sum; i++)
subset[i][0] = false;
// Fill the subset table in botton up manner
for (int i = 1; i <= sum; i++)
{
for (int j = 1; j <= n; j++)
{
subset[i][j] = subset[i][j-1];
if (i >= set[j-1])
subset[i][j] = subset[i][j] || subset[i - set[j-1]][j-1];
}
}
return subset[sum][n];
}
Sorry, I am not good at python. Just translate this to python yourself.
So I was attacking a Euler Problem that seemed pretty simple on a small scale, but as soon as I bump it up to the number that I'm supposed to do, the code takes forever to run. This is the question:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
I did it in Python. I could wait a few hours for the code to run, but I'd rather find a more efficient way to go about this. Here's my code in Python:
x = 1;
total = 0;
while x <= 2000000:
y = 1;
z = 0;
while x >= y:
if x % y == 0:
z += 1;
y += 1;
if z == 2:
total += x
x += 1;
print total;
Like mentioned in the comments, implementing the Sieve of Eratosthenes would be a far better choice. It takes up O(n) extra space, which is an array of length ~2 million, in this case. It also runs in O(n), which is astronomically faster than your implementation, which runs in O(n²).
I originally wrote this in JavaScript, so bear with my python:
max = 2000000 # we only need to check the first 2 million numbers
numbers = []
sum = 0
for i in range(2, max): # 0 and 1 are not primes
numbers.append(i) # fill our blank list
for p in range(2, max):
if numbers[p - 2] != -1: # if p (our array stays at 2, not 0) is not -1
# it is prime, so add it to our sum
sum += numbers[p - 2]
# now, we need to mark every multiple of p as composite, starting at 2p
c = 2 * p
while c < max:
# we'll mark composite numbers as -1
numbers[c - 2] = -1
# increment the count to 3p, 4p, 5p, ... np
c += p
print(sum)
The only confusing part here might be why I used numbers[p - 2]. That's because I skipped 0 and 1, meaning 2 is at index 0. In other words, everything's shifted to the side by 2 indices.
Clearly the long pole in this tent is computing the list of primes in the first place. For an artificial situation like this you could get someone else's list (say, this one), prase it and add up the numbers in seconds.
But that's unsporting, in my view. In which case, try the sieve of atkin as noted in this SO answer.
I just tried a little online programming quiz that asked me to solve this problem as quickly as possible. I got the right answer but I know it isn't pretty. I'm trying to become a better programmer and write cleaner, more efficient code so please give me some tips. I've included the description below. PS I think this algorithm fails for the case N=3
# Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
N= int(sys.stdin.readline())
stringdata = sys.stdin.readline()
array = stringdata.split(' ')
diff1=[0]*(N-1)
diff2 = [0]*(N-2)
index = 0
diff = 0
for i in range(0,len(array)-1):
first_diff[i] = int(array[i+1])-int(array[i])
for i in range(0,len(diff1)-1):
second_diff[i] = first_diff[i+1]-first_diff[i]
if second_diff[i] == 0:
diff = first_diff[i]
else:
index = i
print(int(array[index])+diff)
Task: Find the missing term in an Arithmetic Progression.
An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: Exactly one term from the original series is missing from the set of numbers which have been given to you. The rest of the given series is the same as the original AP. Find the missing term.
Input Format
The first line contains an Integer N, which is the number of terms which will be provided as input.
This is followed by N consecutive Integers, with a space between each pair of integers. All of these are on one line, and they are in AP (other than the point where an integer is missing).
Output Format
One Number which is the missing integer from the series.
Sample Input
5
1 3 5 9 11
Sample Output
7
I think this code can be somewhat simplified. First, the input. Not much different, except I use raw_input (or input in Python 3), and I immediately map the numbers to int.
n = int(raw_input("Number of Numbers: "))
s = raw_input("List of Numbers, space-separated: ")
nums = map(int, s.split())
assert n == len(nums) and n > 2
Now for the interesting part: Note that (assuming the list is well-formed) there can just be two differences between numbers: Either the correct difference, or two times that difference. I use a list comprehension to create a list of tuples (difference, at index). Now I can simply use the builtin max function to find the one with two times the correct difference and the respective index (d2, index) and calculate the missing number.
diffs = [(nums[i+1] - nums[i], i) for i in range(n-1)]
(d2, index) = max(diffs)
print nums[index] + d2 / 2
But the question was about coding style, not about the algorithm, so here are my thoughts:
add some blank lines and comments between logical blocks of your program (e.g. # read input)
map the array to int once, instead of casting the numbers each time you need them
you can use a list comprehension to create diff1 (aka first_diff), as in my example
you don't need diff2 at all; just write if diff1[i+1] - diff1[i] == 0:
be concise: range(0,len(array)-1) is the same as range(N-1)
Works for
1) Any value of N (given 5 in example)
2) Any Difference between terms (given 2 in example)
3) Difference can be + as well as - (example: 11 5 2 -1 -4)
int diff[]= new int[length-1];
for(int i = 0; i<length-1;i++){
diff[i] = n1[i+1]-n1[i];
//System.out.println(diff[i]);
if(i!=0){
if(diff[i]<diff[i-1]){
if(diff[i]<0)
System.out.println(n1[i]+diff[i-1]);
else
System.out.println(n1[i-1]+diff[i]);
break;
}
if(diff[i]>diff[i-1]){
if(diff[i]<0)
System.out.println(n1[i-1]+diff[i]);
else
System.out.println(n1[i]+diff[i-1]);
break;
}
}
}
n1 is where you store the number array from String.
Length is how many numbers you are providing.
This is optimized so that if you miss number in between first two numbers then it only loops 3 times no matter how many numbers you have given
Its very simple , review the code below and if you removed the blank lines it will be exactly 8 lines
I hope this answer is clear for you
import re
N = int(raw_input()) #Number of Terms
I = raw_input() #The Series of Numbers received as a String
I = re.findall(r'\d+',I) #Extract items from the string
I = [int(s) for s in I] #I is a list with Series of Integers
for x in range(N-1):
if (I[x]+2 != I[x+1]):
print I[x]+2
int a[]={1,3,5,7,11};
int i=0,n=5,fd,sd;
printf("output:\n");
do
{
fd=0;sd=0;
fd=a[i+1]-a[i];
sd=a[i+2]-a[i+1];
if(fd<sd)
{
printf("missing term is %d",fd+a[i+1]);
}
else if(fd>sd){
printf("missing term is %d",a[i]+sd);}
else{
i++;}
}while((fd==sd)&&i<n-2);
N = input()
max_num = range(N)
s = raw_input()
AP = map(int,s.split())
comm_dif = AP[1]-AP[0]
length = len(AP)
for i in range(N):
if i != length-1:
if AP[i+1]-AP[i] != comm_dif:
print AP[i]+comm_dif
INPUT:
5
1 21 31 51 61
OUTPUT:
41
Here is my code, work for both positive difference and negative difference...
def find_arith(aplist):
idiff=[]
flag=0
for j in range(0, len(aplist)-1):
diff1 = aplist[j+1] - aplist[j]
if diff1 < 0:
flag=1
idiff.append(abs(diff1))
if flag==1:
final_diff=-1*min(idiff)
else:
final_diff=min(idiff)
print(idiff)
print("final diff:", final_diff)
for i in range(aplist[0],aplist[len(aplist)-1]+1,final_diff):
if i not in aplist:
print(i)
if __name__ == "__main__":
print("First Result")
find_arith([13,21,25,33,37,45])
print("Second Result")
find_arith([-10,-6,-4,-2])
print("3rd Result")
find_arith([-5, -1, 3, 11])
print("4th Result")
find_arith([1, 5, 13, 17, 21])
print("5th Result")
find_arith([-2, -8, -11, -14, -17, -20, -23, -29])
2 For Loops for a simple problems such as this !! that solution above is Quadratic in its behavior !!
Here is one solution which is O(N) for the worst case behavior where the item # index 1 is missing and for any item missing after index 1 the solution is better than linear.
The Arithmetic Progression(input Array) to this method, Substitute the SYSOUT with returns appropriately.
solution:
public static int findMissingNumberInAP(int[] ipArr)
{
// ipArr will always be more than 3 elements in size.
int maxDiff = ipArr[1] - ipArr[0];
int i=0;
while(i<ipArr.length-1)
{
if((ipArr[i+1] - ipArr[i]) > maxDiff)
break;
i++;
}
// This means the 2nd element or i=1 was missing so add ip[0] to
// any random difference you are good to go.
if(i == ipArr.length - 1)
System.out.println(ipArr[0] + (ipArr[ipArr.length-1]-ipArr[ipArr.length-2]));
else System.out.println(ipArr[i] + maxDiff);
// Else just add the maxDiff you got from first step to the position
// of i you broke the loop at.
return -1;
}