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)
Related
I have been trying to print an upside down right triangle in Python 3.7. This is the code I wrote:
n=4
for i in range (0, n):
for j in range(0,n):
print("*", end="")
n-=1
print()
According to what I understood about loops, the nested for loop should iterate n times while the outer for loop iterates once. Following that logic, the column loop should print four asterisks, then one less each time the loop turns because the value of n reduces by one.
But the output I get is this:
****
I don't understand what I'm doing wrong.
Edit: I know and understand the alternative ways of solving this problem. It's just that I don't get why this particular piece of code is not working.
You will be better off using the * operator to build your string.
n = 4
for i in range(n):
print('*' * (n-i))
Output:
****
***
**
*
I'm having trouble with Project Euler #6. The question is as follows:
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
I'm trying to write my code in such a way that what is being asked in Euler(all numbers up to and including 100) can be substituted for any number you like (all numbers up to and including x). I decided that in order to do this, you would need 3 functions. Code is:
#the sumSquare function squares every number from 0 to number called
#in the function and adds each term to a list. the function returns the sum
#of all numbers in this list
def sumSquare(num):
list1 = []
for i in range(num+1):
x = i^2
list1.append(x)
return sum(list1)
#the squareSum function adds every whole number from 0 up to and including
#the number called in the function to list2. It returns the sum squared of #every number in the list
def squareSum(num):
list2 = []
for i in range(1,num+1):
list2.append(i)
return (sum(list2) * sum(list2))
def ans(num):
return squareSum(num) - sumSquare(num)
print ans(100)
My output is 2549748 but I'm reading online that the correct solution is 25164150. Does anyone see where I am going wrong. I am just learning to code so I may be missing something that would be easy to spot by someone more experienced. But as far as I can tell, the lists are being filled with what would be the appropriate numbers before they are summed.
This
i^2
Is not a square in Python. Use i*i or i**2 for a square.
Your code is anylanguage code. But with sintax error.
Really power in Python is **
So.
Python-style code looks like that one:
print(sum(range(1, 101))**2 - sum([i**2 for i in range(1, 101)]))
Thats why they love the Python (R)
Thanks to everyone for the input. After thinking a bit more I realized just how overly convoluted this code was. I realized that if all three functions are taking the same variable to solve the problem, it can be simplified into one function that takes care of each step on its own. Came up with this solution which is obviously much more efficient:
import time
def ans(num):
numSq = []
for i in range(1, num+1):
numSq.append(i**2)
return ((sum(range(1, num+1))**2)-sum(numSq))
start_time = time.time()
print ans(100)
print "This program took {} seconds to execute.".\
format(time.time() - start_time)
Running the program you get:
25164150
This program took 0.00800013542175 seconds to execute.
Again, thanks for the input on my first post!
def diffSum():
sumSquares = 0
squareSum = 0
sumT = 0
for i in range(1,101):
sumSquares = sumSquares + (i * i)
for i in range(1,101):
sumT = sumT + i
squareSum = sumT * sumT
return squareSum - sumSquares
#sumsquares gets all the summation of the square numbers of the first 100 numbers
#sumT stores the summation of the first 100 numbers
#squareSum squares the summation of the first 100 numbers
#returns the difference between sumSquares and squareSum
Yesterday, I was trying to solve a problem with python, and I encountered something really odd:
# create matrix
for i in range(N):
tmp.append(0)
for i in range(N):
marker.append(tmp)
# create sum of 2 first cards
for i in range(N) :
for j in range(N):
if i != j and marker[i][j] == 0:
comCard.append(deck[i]+deck[j])
taken[deck[i]+deck[j]] = [i,j]
marker[i][j] = 1
marker[j][i] = 1
The idea is that I want to calculate all the possible sums of each pair of cards in the deck (these cards need to be different), so I think that with a marker, I can avoid calculating the same 2 cards again. for example: deck[1]+deck[2] and deck[2]+deck[1]. But these lines didn't work as they were supposed to do:
marker[i][j] = 1
marker[j][i] = 1
I can recommend another way using standard python modules:
# suppose this is a deck - list of cards (I don't know how to mark them :)
>>> deck = ['Ax', 'Dy', '8p', '6a']
>>> from itertools import combinations
# here's a list of all possible combinations of 2 different cards
>>> list(combinations(deck, 2)))
[('Ax', 'Dy'), ('Ax', '8p'), ('Ax', '6a'), ('Dy', '8p'), ('Dy', '6a'), ('8p', '6a')]
You may work with this list: check some combinations and so on.
I recommend to pay attention to library itertools - it's really awesome for such type computations!
You're using the same instance of tmp, only shallow-copied. That's why it doesn't work. You need a new copy of each line to add in your matrix.
This can be done with:
marker.append(list(tmp))
Also, you may benefit from using True and False instead of 0 and 1 someday. So the initialisation of your matrix could rahter look like this:
tmp = list()
marker = list()
for i in range(N):
tmp.append(False)
for j in range(N):
marker.append(list(tmp))
This way, when you try marker[i][j] = True, only the index (i, j) will be affected.
That being said, Eugene Lisitsky's answer gives you a far more adapted tool for this kind of matter (permutation listing).
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);
I'm trying to solve problem 12 of Euler project. What is the value of the first triangle number to have over five hundred divisors? ( the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28). This is my code, but it is not fast enough..
Do you have any optimization tips?
n=0
a=0
list=[]
maxcount=0
while True:
n+=1
a+=n
count=0
for x in range(1,int(a+1)):
if a%x==0:
count+=1
if count>maxcount:
maxcount=count
print a, "has", maxcount, "dividors"
Thank you!
Start with reducing the search space, no need to look at numbers that are not triangle numbers. Also try looking at divisors in range(1, sqrt(n)) instead of range(1, n)
Grab the code from this question which implements very fast prime factorization:
Fast prime factorization module
Then use the answer to this question to convert your prime factors into a list of all divisors (the length is what you want):
What is the best way to get all the divisors of a number?
For example, you can add the following function (adapted from the second link) to the bottom of the module from the first link:
def alldivisors(n):
factors = list(factorization(n).items())
nfactors = len(factors)
f = [0] * nfactors
while True:
yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
i = 0
while True:
if i >= nfactors:
return
f[i] += 1
if f[i] <= factors[i][1]:
break
f[i] = 0
i += 1
Then in your code to count divisors you would use len(list(alldivisors(a))) which will calculate the number of divisors significantly more quickly than the brute force method you are currently using.
Apart from number theory: try caching, and doing things the other way around. For example: When you already know that 300 has 18 divisors (and what they are), what does that mean for a number which is dividable by 300? Can you cache such information? (sure you can.)
Pure python speedup hacks won't help you, you need a better algorithm.