for loop in pyton exercise - python

I'm looking for help to solve the below problem: Having 2 variables beat and measures I need to create a loop that prints, on the same line, all the beats times the number of measures. Nevertheless, every time it starts a new measure, the first beat should be equal to the number of the current measure.
Example: beats_per_measure = 4, measures = 4 should give
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4
and not
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
beat = beats_per_measure + 1
measure = measures + 1
for i in range(1,measure):
for j in range(1, beat):
print(j, end = " ")
This is the code I've tried to print beats x measure, but I'm not sure how to change that first beat to reflect the current measure.

This code gave:123123123, maybe you lost "space" somewhere.
for i in range(1,4):
for j in range(1, 4):
print(j, end = "")

for i in range (1, measure+1):
for j in range(1, beat+1):
if j==1:
print(i, end="")
else:
print(j, end="")

Don't overthink a problem like this; adding an extra print provides the expected output, no if required:
measures = 4
beats = 4
for measure in range(1, measures+1):
print(measure, end="")
# Start beat from 2
for beat in range(2, beats+1):
print(beat, end="")

Related

Python inverted number pyramid exercise

This is an example of a correct pyramid.
I have this exercise as homework but I cant figure it out.
The code i've tried so far is this one and I can't make it inverted:
n = 5
for i in range(n, 0, -1):
for j in range(n, i-1, -1):
print(j, end=" ")
print(" ")
n = int(input("What's the number: "))
for i in range(n, 0, -1):
for j in range(i, 0, -1):
print(j, end="")
print()
Works for me.
The trick is to start the second loop "j" with the decrementing "i" downwards.
Imagine you are doing not a pyramid, but printing
5 4 3 2 1 n times.
Something like
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
...
You would start i and j at the same index, n, and just repeat the task.
Here, you start j at i, so each time i gets decremented, j starts from the decremented i, thus making a pyramid effect.
Hope you understand :)

Python: How to make numeric triangle with recursion

while I was working on the Python practice, I found a question that I cannot solve by myself.
The question is,
Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes.
Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed.
So by that question, I found that this is a question that requires the
recursion since I have to call your function only once.
I tried to work on the codes that I made many times, but I couldn't solve it.
global a
a = 1
def printLine(n):
global a
if (n == 0):
return
for i in range(1, a + 1):
print(i, end=" ")
print()
a += 1
for k in range(1, n+1):
print(k, end=" ")
print()
printLine(n - 1)
n = int(input())
printLine(n)
Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :(
What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call?
Or is there another way can divide the ascending and descending part in the function?
Any ideas, comments, or solutions are appreciated.
Thx
You can use the below function:
def create_triangle(n, k: int = 1, output: list = []):
if n == 1:
output.append(n)
return output
elif k >= n:
output.append(" ".join([str(i) for i in range(1, n + 1)]))
return create_triangle(n - 1, k)
else:
output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
return create_triangle(n, k + 1)
for i in create_triangle(5):
print(i)
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
# function to print all the numbers from 1 to n with spaces
def printLine(k):
# create a range. if k is 4, will create the range: 1, 2, 3, 4
rng = range(1, k + 1)
# convert each number to string
str_rng = map(lambda x: str(x), rng)
# create one long string with spaces
full_line = " ".join(str_rng)
print(full_line)
# capture input
n = int(input())
# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
printLine(i)
# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
printLine(i)
Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.
def triangle_line(n, config={'max':1, 'ascending':True}):
print(*range(1, config['max'] + 1))
if config['ascending']:
config['max'] += 1
else:
config['max'] -= 1
if config['max'] > n:
config['ascending'] = False
config['max'] = n
elif config['max'] == 0:
config['ascending'] = True
config['max'] = 1
Each call you make will return one iteration.
>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1
Or you can run on a loop, two times your input size.
>>> n = 4
>>> for i in range(0,n*2):
... triangle_line(n)
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1

for loop to iterate the values based on index

I have a dataset from which i need to take the index 0 and 1 then process the output then take the index value 2 and 3 then process the output and so on.
The code which i have tried takes the value of index 0 and 1 then 1 and 2 then 2 and 3 and so on.
for i,r in tqdm(gf.iterrows()):
lp = 0
for v in range(0, 10 + 1):
lp += r.length_10
ix.append(i)
basket.append(r.line.interpolate(lp))
The code must take the index value of o and 1 then 2 and 3 then 4 and 5 and so on....0
for v in range(0, 10+1,2):
print(v,v+1)
#prints
#0 1
#2 3
#4 5
#6 7
#8 9
Honestly, I couldn't understand very well your code. But, I think that the problem occurs here:
for v in range(0, 10 + 1):
this means that your iterator will go from 0 to 10 one by one, but try to change this line to:
for v in range(0, 10 + 1,2):
I think this one will do the job

Number half Pyramid Python

I'm trying to print a half pyramid that stars on the left side in python.
So far, this is my code
for i in range(1,12):
for j in range(12 - i):
print(" ", end = " ")
for j in range(1, i):
print(j, end = " " )
print("\n")
and my output is
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
However, my output is meant to be in the opposite order:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How can I make this change?
Just reverse the second loop -- the one that prints that actual numbers:
for j in range(i-1, 0, -1):
The last parameter controls the "step", or how much the variable changes on each loop iteration. Output:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
...
Reverse the range by adding the third argument (-1). Also format your numbers to use 2 places, so 10 is not pushing the last line to the right. Finally, the last print should probably not have \n, since that is already the default ending character of print:
for i in range(1,12):
for j in range(12 - i):
print(" ", end = "")
for j in range(i-1, 0,-1):
print(str(j).rjust(2), end = "" )
print()
You could just reverse the range that you print out as numbers
for i in range(1,12):
for j in range(12 - i):
print(" ", end = " ")
for j in reversed(range(1, i)):
print(j, end = " " )
print("\n")
The problem is in your second for loop, as you are looping from 1 to i, meaning you start off with 1 being printed first, and every following number until (not including) i.
Fortunately, for loops are able to go in reverse. So, instead of:
for j in range(1, i)
You could write:
for j in range((i-1), 0, -1)
Where the first parameter is signifies where the loop starts, the second is where the loop finishes, and the third signifies how large our jumps are going to be, in this case negative. The reason we are starting at i-1 and finishing at 0 is because loops start at exactly the first given number, and loop until just before the second given number, so in your given code the loop stops just before i, and so this one starts just before i as well, although you could remove the -1 if you wish to include 12 in the pyramid.

For loop a square pattern of numbers

In this question I had to create a program that prompts the user for a number and then prompt again for how many rows to create. Something like:
1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 3 3 3 3 3 3
4 4 4 4 4 4 4
This is what I came up with and I have tried many different ways to get the same result but it didn't work.
num=int(input("Enter a number between 1 and 10: "))
rows=int(input("Enter how many rows to of numbers: "))
for i in range(num):
print(i,end=" ")
for x in range(rows):
print (x)
This is the output I came up with:
Enter a number between 1 and 10: 6
Enter how many rows to of numbers: 4
0 1 2 3 4 5 0
1
2
3
You may simply do it like:
num = 5
rows = 4
for i in range(1, num+1):
print('{} '.format(i) * rows)
Output:
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
Explanation: When you multiply a str with some number say n, new string is returned with original string repeated n times. Doing this you will eliminate your nested loop
Simple solution: Just use nested for loops:
num = int(input("Enter a number between 1 and 10: "))
rows = int(input("Enter how many rows to of numbers: "))
for i in range(num):
print ('\n')
for x in range(rows):
print (i + 1)
The code above will go through the range 0 to num, printing first a new line and then printing the current number rows times.
rows = 5
side = int(input("Please Enter any Side of a Square : "))
for i in range(side):
for j in range(side):
if(i == 0 or i == side - 1 or j == 0 or j == side - 1):
print(i, end = ' ')
else:
print(i, end = ' ')
print()

Categories

Resources