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:
****
***
**
*
Related
a = [1,2,3,4,5]
for i in range(len(a)):
a.pop(0)
print ('%d/%d' % (i, len(a)))
Above is simple code changes list size during iterating itself.
$ python test.py
0/4
1/3
2/2
3/1
4/0
And the result was like above.
From 2/2, i exceed the total iteration size!
Question
Could anyone tell me why the code still executes after exceeding the size?
hmm... for easier explanation, what happened here is
when you run for i in range(len(a)):
it will automatically run for i in range(5):
so it will not call the len function again and again for each loop
This is another example:
length=5
for i in range(length):
length=2
print(length)
the result is
2
2
2
2
2
Correct me if I am wrong, but I think most of for iteration (any language) is fixed since beginning, if you want to loop something that is not fixed, better use while
length=5
i=0
while i < length:
length=2
print(length)
i+=1
The result
2
2
So I am trying to create two functions (the use of additional functions is allowed). One that creates an entire right triangle by calling a recursive function, and then the recursive function itself is suppose to be able to grab the last X amount of lines of the complete right triangle and display them. The only thing is, the first function (triangle()) cannot be changed.
Here are the two functions (at least this is what I have so far for the recursive function):
def triangle(n):
return recursive_triangle(n, n)
def recursive_triangle(k, n):
if k > 0:
print(k*'*')
recursive_triangle(k-1, n)
So for example, when working properly:
triangle(6)
would give
******
*****
****
***
**
*
and
recursive_triangle(3,6)
would give me the last 3 lines of a right triangle of base and height 6 (above triangle) like so:
***
**
*
I'm not sure how to use the relationship between n and k in a recursive method to implement the proper spacing required.
If I understand you correctly, triangle(6) should show a 6-lines tall triangle. This, I presume, also means that triangle(3) should show a 3-lines tall triangle, just as you presented in your example so there is no need to change anything (in the setup), you just need to write the recursive_triangle() function properly to subtract k from n before sending it to another function to do the actual printing.
However, what I think you want is to still consider the 'whole' triangle, but just not print the higher lines, i.e. instead of:
***
**
*
you want:
***
**
*
Notice the extra indentation as if the 'triangle' was printed but was missing the first 3 lines. In that case, you can use str.rjust() to do the justification for you, e.g.:
def recursive_triangle(k, n):
if k > 0:
print(("*" * k).rjust(n))
recursive_triangle(k-1, n)
Now if you call recursive_triangle(3, 6) you'll get exactly what you're after (and it will also properly print deferred calls from triangle()).
UPDATE: If you want to return a string instead of printing, store the results in a list and then concatenate with new lines, i.e.:
def recursive_triangle_builder(k, n):
result = []
if k > 0:
result.append(("*" * k).rjust(n))
result += recursive_triangle_builder(k-1, n)
return result
def recursive_triangle(k, n):
return "\n".join(recursive_triangle_builder(k, n))
print(recursive_triangle(3, 6)) # or store the result instead of printing
I think this is what you want.
print( (n-k) * ' ' + k * "*")
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)
Consider the following code:
for i in range(size-1):
for j in range(i+1,size):
print((i,j))
I need to go through this for-loop in a random fashion. I attempt to write a generator to do such a thing
def Neighborhood(size):
for i in shuffle(range(size-1)):
for j in shuffle(range(i+1), size):
yield i, j
for i,j in Neighborhood(size):
print((i,j))
However, shuffle cannot be applied to whatever object range is. I do not know how to remedy the situation, and any help is much appreciated. I would prefer a solution avoid converting range to a list, since I need speed. For example, size could be on the order of 30,000 and i will do perform this for loop around 30,000 times.
I also plan to escape the for loop early, so I want to avoid solutions that incorporate shuffle(list(range(size)))
You can use random.sample.
The advantage of using random.sample over random.shuffle, is , it can work on iterators, so in :
Python 3.X you don't need to convert range() to list
In Python 2,X, you can use xrange
Same Code can work in Python 2.X and 3.X
Sample code :
n=10
l1=range(n)
for i in sample(l1,len(l1)):
l2=range(i,n)
for j in sample(l2,len(l2)):
print(i,j)
Edit :
As to why I put in this edit, go through the comments.
def Neighborhood(size):
range1 = range(size-1)
for i in sample(range1, len(range1)):
range2 = range(i+1)
for j in sample(range2, len(range2)):
yield i, j
A simple way to go really random, not row-by-row:
def Neighborhood(size):
yielded = set()
while True:
i = random.randrange(size)
j = random.randrange(size)
if i < j and (i, j) not in yielded:
yield i, j
yielded.add((i, j))
Demo:
for i, j in Neighborhood(30000):
print(i, j)
Prints something like:
2045 5990
224 5588
1577 16076
11498 15640
15219 28006
8066 10142
7856 8248
17830 26616
...
Note: I assume you're indeed going to "escape the for loop early". Then this won't have problems with slowing down due to pairs being produced repeatedly.
I don't think you can randomly traverse an Iterator. You can predefine the shuffled lists, though
random iteration in Python
L1 = list(range(size-1))
random.shuffle(L1)
for i in L1:
L2 = list(range(i+1, size))
random.shuffle(L2)
for j in L2:
print((i,j))
Of course, not optimal for large lists
I am not sure how to implement Floyd's algorithm in the following program. It must print a 5x5 array that represents this graph on page 466 and include a counter which is used to print the total number of comparisons when the algorithm is executed - each execution of the "if" structure counts as one comparison.
Does anyone know how to even start this program? I am not sure how to begin.
The following is purely a transcription of the pseudocode you linked. I changed almost nothing.
for k in range(n):
for i in range(n):
for j in range(n):
if A[i][k]+A[k][j]<A[i][j]:
A[i][j]=A[i][k]+A[k][j]
Translated from the page you linked to,
k=0
while (k <= n-1):
i=0
while (i<=n-1):
j=0
while(j<=n-1):
if(A[i,k] + A[k,j] < A[i,j]):
A[i,j] = A[i,k] + A[k,j]
j += 1
i += 1
k += 1
NB This is the exact translation to Python.
Better, more Pythonic code is also possible - see, e.g. 5xum's answer
which uses the range function instead of manually incrementing the loop counters.
Also A here would be a 2d matrix (e.g. a numpy ndarray).
See more information about numpy here