Create the following pyramid in python - python

Iv`e been asked to create the following pyramid in python with only using 2 for loops.
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
Is there a shorter way only using 2 for loops as apposed to my program?
for x in range(1, 10):
for y in range(0, 1):
print ('1')
print("2 4")
for u in range(1, 2):
for v in range(0,1):
print("3 6 9")
print("4 8 12 16")
for t in range(1, 2):
for s in range(0, 1):
print("5 10 15 20 25")
print("6 12 18 24 30 36")
for r in range(1, 2):
for q in range(0, 1):
print("7 14 21 28 35 42 49")
print("8 16 24 32 40 48 56 64")
for p in range(0,1):
print("9 18 27 36 45 54 63 72 81")

I'm gonna do this more of a code review...
Your first line for x in range(1,10): shows that you want to create a loop to iterate through a sequence of code 9 times (10 - 1).
With programming, counting starts from 0, instead of saying range(1,10), you can say range(0,9) or even range(9).
This helps make it more readable (I read 9 faster than computing 10 - 1)
Inside this main loop, you've added a lot of for loops... for y in range(1,2):. What this means is that it will iterate through the code indented once, as 2 - 1 is 1. Therefore this for loop is irrelevant and you can just simply use print('1').
If we simplify your code taking into account whats said above, we get:
for x in range(9):
print("1")
print("2 4")
print("3 6 9")
print("4 8 12 16")
print("5 10 15 20 25")
print("6 12 18 24 30 36")
print("7 14 21 28 35 42 49")
print("8 16 24 32 40 48 56 64")
print("9 18 27 36 45 54 63 72 81")
Isn't that already much nicer and more readable. If you type this into python, it will produce the same result as the code you gave, thats because computationally it is the same, however in your method you have unnecessary steps as mentioned above.
Taking this a step further..
Your code prints out this 'pyramid' 9 times. I think you want to print out this pyramid once, so therefore we will have to remove the initial for loop. What you want to for loop is what is printed. Because there is a pattern behind it, a relationship, you can create a for loop to do this for you. This also helps create a more general-case usability. (So instead of doing this until 9, 18, 27, you can do it until n*1, n*2, n*3 [also a checky hint of what you should for loop]).
Hope this was helpful, comment if theres anything you dont understand!
EDIT:
I was just doing some random coding and I found a quite neat way of creating the same result (though it is quite confusing), just wanted to share...
for k in [[(j+1)*i for j in range(i)] for i in range(1,11)]:
print k

for i in range(1,10):
for j in range (1,i+1):
print(i*j)
This will print every number on a new line though. If you want to keep everything on the same line, and you don't want to print a list or something, then you might add to a string instead:
for i in range(1,10):
x = ''
for j in range(1,i+1)
x=x+str(i*j)+' '
print(x.strip())

Four lines, really:
for x in range(1, 10):
for y in range(x, x ** 2 + 1, x):
print (y, end = ' ')
print('\n')
This makes use of the start, stop and step parameters and will yield:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
To get rid of the extra newlines, just change the print('\n') statement to print().

Related

Removing last line and initial whitespaces from an 8 by 8 list of integers in python

#Print the user board
s = ''
for i in range(n):
for j in range(n):
z = i * n + j
s += ' '
if z < 10:
s += ' '
s += str(z)
s += '\n'
print(dedent(s))
queens = list(map(int, input("Queens: ").split()))
I keep getting an error from my testcase environment of a last blank line before proceeding to the queens input below. What can I approach to fix
I have tried cleandoc from textwrap and while it works, it disrupts every required spacing and new distinctive lines for z from the "s" string which is a perfect 8 by 8 from 0 to 63.
Creating the right way instead of removing things after is easier:
from itertools import count
import toolz
n = 8
start_value = 0
counter = count(start_value)
rows = [" ".join(f"{num:2}" for num in toolz.take(n, counter)) for _ in range(n)]
print("\n".join(rows))
The itertools.count creates an iterable counter that gives the next value every time you want. Here the take function will get 8 items each time.
If you do not want the initial space, you'd better use join, which only adds the separator between consecutive items:
s = '\n'.join(' '.join('{:2d}'.format(i * n + j)
for j in range(n))
for i in range(n))
print(s)
gives as expected:
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63

How to skip a for loop by X amount and continue for Y amount, then repeat

Being struggle with this for a while but how am I able to skip for loops in python by X and continue for Y then repeat.
For example:
# This loop should loop until 99, but after it reaches a number that is a multiple of 10 e.g. 10,20,30 etc it should continue for 5 iterations, then skip to next multiple of 10.
# E.g 0,1,2,3,4,5,10,11,12,13,14,15,20,21,22,23,24,25,30...etc
for page_num in range(100):
# Use page_num however
Modify the loop to use a step of 10, and add a sub-loop to have iterations that break off after the 5th element.
for j in range(0,100,10):
for page_num in range(j, j+6):
# use page_num
Use continue to skip the rest of the loop if the digit in units place is greater than 5.
skip_after = 5
for page_num in range(100):
if page_num % 10 > skip_after: continue
# ... Do the rest of your loop
print(page_num)
page_num % 10 uses the modulo % operator to give the remainder from dividing page_num by 10 (which is the digit in the units place).
Output (joined into a single line for readability):
0 1 2 3 4 5 10 11 12 13 14 15 20 21 22 23 24 25 30
Using itertools.filterfalse
from itertools import filterfalse
for x in (filterfalse(lambda x: (x % 10) > 5, range(0, 100))):
print(x, end=' ')
Output:
0 1 2 3 4 5 10 11 12 13 14 15 20 21 22 23 24 25 30 31 32 33 34 35 40 41 42 43 44 45 50 51 52 53 54 55 60 61 62 63 64 65 70 71 72 73 74 75 80 81 82 83 84 85 90 91 92 93 94 95
I would recommend list comprehension. Im not positive if this is the complete answer but I would do it as:
def find_divisors_2(page_num):
"""
You can insert an algorithmic phrase after if and it will produce the answer.
"""
find_divisors_2 = [x for x in range(100) if (Insert your algorithm)]
return find_divisors_2
You can directly modify the value of page_num inside the for loop with a certain condition:
for page_num in range(100):
if str(page_num)[-1]=="6":
page_num += 4
print(page_num)

How to print 6 rows of 7 numbers with user input

I must write a program that accepts a number, n, where -6 < n < 2. The program must print out the numbers n to n+41 as 6 rows of 7 numbers. The first row must contain the values n to n+6, the second, the values n+7 to n+7+6, and so on.
That is, numbers are printed using a field width of 2, and are right-justified. Fields are separated by a single space. There are no spaces after the final field.
Output:
Enter the start number: -2
-2 -1 0 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39
The numbers need to be directly lined under each other.
I have absolutely no idea how to do this
This is my code so far:
start = int(input('Enter the start number: '))
for n in range(n,n+41):
If you could help me I will really appreciate it.
I assume you are not allowed to use a library to tabulate the numbers for you and are expected to do the logic yourself.
You need to print 6 rows of numbers. Start by determining the first number of each row. That is given by range(n,n+42,7) (note, not n+41). For starting value -2, those are the numbers -2, 5, 12, 19, 26, 33. Every other number in the row is just the next 6 integers. If the first number in the row is leftmost then the entire row is given by range(leftmost, leftmost + 7). So the first row those are the numbers -2, -1, 0, 1, 2, 3, 4.
To print 6 rows of 7 numbers you need a loop with 6 iterations, one for each value of leftmost. Inside that loop you print the other numbers. The only complication is all of the numbers in the list must be followed by a space, except the last. So that has to get special treatment.
You need to specify format {0:2d} to ensure that "numbers are printed using a field width of 2".
n = -2
for leftmost in range(n,n+42,7):
for value in range(leftmost,leftmost + 6):
print("{0:2d}".format(value), end=" ")
print("{0:2d}".format(leftmost+6))
-2 -1 0 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39
check the tabulate library here, you can use it to format the output - the tablefmt="plain" parameter produces a very similar table.
If you store the numbers in a list you can use list slicing to get the rows of 7 numbers each and put those in an another list to satisfy the format that tabulate is expecting
from tabulate import tabulate
n = 2
while not -6 < n < 2:
n = int(input('Please submit a number greater than -6 and smaller than 2:\n'))
number_list, output_list = [], []
for i in range(42):
number_list.append(n + i)
for i in range(6):
output_list.append(number_list[i*7:i*7+7])
print()
print(
tabulate(
output_list,
tablefmt='plain'
)
)
Please submit a number greater than -6 and smaller than 2:
-3
-3 -2 -1 0 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
32 33 34 35 36 37 38

A function that prints out tables from 1 to 10 using iteration

def tablesOneToTen(): # a function that will print out multiplication tables from 1-10
x = 1
y = 1
while x <= 10 and y <= 12:
f = x * y
print(f)
y = y + 1
x = x + 1
tablesOneToTen()
I am trying to make a function that will give me values from the multiplication table from 1-10.
Should I add if and elif statements in addition to nested while loops to make this code work?
For these sort of iteration tasks you're better off using the for loop since you already know the boundaries you're working with, also Python makes creating for loops especially easy.
With while loops you have to check that you are in range using conditionals while also explicitly incrementing your counters making mistakes all the more likely.
Since you know you need multiplication tables for values of x and y ranging from 1-10 you can, to get you familiar with loops, create two for loops:
def tablesOneToTen(): # a function that will print out multiplication tables from 1-10
# This will iterate with values for x in the range [1-10]
for x in range(1, 11):
# Print the value of x for reference
print("Table for {} * (1 - 10)".format(x))
# iterate for values of y in a range [1-10]
for y in range(1, 11):
# Print the result of the multiplication
print(x * y, end=" ")
# Print a new Line.
print()
Running this will give you the tables you need:
Table for 1 * (1 - 10)
1 2 3 4 5 6 7 8 9 10
Table for 2 * (1 - 10)
2 4 6 8 10 12 14 16 18 20
Table for 3 * (1 - 10)
3 6 9 12 15 18 21 24 27 30
With a while loop, the logic is similar but of course just more verbose than it need to since you must initialize, evaluate the condition and increment.
As a testament to its uglyness, the while loop would look something like this:
def tablesOneToTen():
# initialize x counter
x = 1
# first condition
while x <= 10:
# print reference message
print("Table for {} * [1-10]".format(x))
# initialize y counter
y = 1
# second condition
while y <=10:
# print values
print(x*y, end=" ")
# increment y
y += 1
# print a new line
print(" ")
# increment x
x += 1
Using Python 3
for i in range(1, 10+1):
for j in range(i, (i*10)+1):
if (j % i == 0):
print(j, end="\t")
print()
or:
for i in range(1, 10+1):
for j in range(i, (i*10)+1, i):
print(j, end="\t")
print()
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Hope it would help you to get 1 to 10 table.
a = [1,2,3,4,5,6,7,8,9,10]
for i in a:
print(*("{:3}" .format (i*col) for col in a))
print()

There is a 4 in my prime number list generated in Python

Here is my code.
#Prime numbers between 0-100
for i in range(2,100):
flg=0
for j in range(2,int(i/2)):
if i%j==0:
flg=1
break
if flg!=1:
print(i)
And the output is
2
3
4 <-
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
I have no idea why there is this 4.
Pardon me if i made some noobish mistake, as i can't seem to figure it out.
The reason is that range is not inclusive, i.e.
>>> range(2,2)
[]
So when you access 4, you don't check for divisors. Change for example to range(2,int(i/2)+1)
To speed up your calculation, you can use math.sqrt instead of /2 operation, for example as:
import math
and then
for j in range(2, int(math.sqrt(i)+1)):

Categories

Resources