Tables of multiples in Python - python

I would like to print a table that print rows*columns in that many rows and columns, with the beginning of each column incrementing by one and that row being multiples of the first number. For example: table(3,4)
1 2 3 4
2 4 6 8
3 6 9 12
Here is my code so far. It's currently going by ones, and I don't know how to make each row be a multiple of the first number. Thank you.
def table(rows, columns):
for i in range(rows):
print(*range(1+i*columns, 1+(i+1)*columns))
for h in range(rows%rows):
print(*range(1+h*columns%rows, 1+(h+1)*columns))

You should iterate over a range of rows and a range of columns, and output their products:
def table(rows, columns):
for i in range(1, rows + 1):
for h in range(1, columns + 1):
print(i * h, end=' ')
print()
so that:
table(3, 4)
would output:
1 2 3 4
2 4 6 8
3 6 9 12

Related

Making a 2D array without brackets

I'm trying to create a 2D array, but it prints out in one row and with brackets.
How do I make it into rows and columns without brackets?
rows = int(input("Please enter the number of rows: "))
board = [[i + (j * cols) for i in range(1, cols + 1)] for j in range(0, rows)]
print(board)
for row in board:
print(" ".join(list(map(str, row))))
We iterate through the board and for each row, make it a list of strings (using map) instead of numbers and join them with a space.
Maybe this is what you are looking for:
for row in board:
print(row)
Is this what you mean?
rows = int(input("Please enter the number of rows: "))
cols=rows#my thing would not run without this line
board = [[i + (j * cols) for i in range(1, cols + 1)] for j in range(0, rows)]
print(board)
arr=[]
for i in range(rows):
for c in range(cols):
print(str(i)+" "+str(board[i][c]))
Output:
0 1
0 2
0 3
0 4
0 5
1 6
1 7
1 8
1 9
1 10
2 11
2 12
2 13
2 14
2 15
3 16
3 17
3 18
3 19
3 20
4 21
4 22
4 23
4 24

Create a pandas Series

I want to create a panda series that contains the first ā€˜nā€™ natural numbers and their respective squares. The first ā€˜nā€™ numbers should appear in the index position by using manual indexing
Can someone please share a code with me
Use numpy.arange with ** for squares:
n = 5
s = pd.Series(np.arange(n) ** 2)
print (s)
0 0
1 1
2 4
3 9
4 16
dtype: int32
If want omit 0:
n = 5
arr = np.arange(1, n + 1)
s = pd.Series(arr ** 2, index=arr)
print (s)
1 1
2 4
3 9
4 16
5 25
dtype: int32

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()

Print a number table in a simple format

I am stuck trying to print out a table in Python which would look like this (first number stands for amount of numbers, second for amount of columns):
>>> print_table(13,4)
0 1 2 3
4 5 6 7
8 9 10 11
12 13
Does anyone know a way to achieve this?
This is slightly more difficult than it sounds initially.
def numbers(n, r):
print('\n'.join(' '.join(map(str, range(r*i, min(r*(i + 1), n + 1)))) for i in range(n//r + 1)))
numbers(13, 4)
#>>> 0 1 2 3
4 5 6 7
8 9 10 11
12 13
def numbers(a,b):
i=0;
c=0;
while i<=a:
print(i,end="") #prevents printing a new line
c+=1
if c>=b:
print("\n") #prints a new line when the number of columns is reached and then reset the current column number
c=0;
I think it should work
def num2(n=10, r=3):
print('\n'.join(' '.join(tuple(map(str, range(n+1)))[i:i+r]) for i in range(0, n+1, r)))
<<<
0 1 2
3 4 5
6 7 8
9 10

Number Pyramid Nested for Loop

I'm wondering if you could help me out. I'm trying to write a nested for loop in Python 3 that displays a number pyramid that looks like;
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
Can anybody help me out? It would be much appreciated!
This is what I have so far:
col = 1
for i in range(-1, 18, col*2):
for j in range(1, 0, 1):
print(" ", end = "")
for j in range(i, 0, -2):
print(j, end = " ")
print()
So, I can only get half of the pyramid to display.
I guess the main problems I'm having is:
How do i get the output to display an increasing and then decreasing value (ie. 1, 2, 4, 2, 1)?
An alternate way using list comprehensions.
Always break the problem down into digestable chunks. Each line is a mirror of itself, so lets just deal with first making out set of numbers we need.
This generates a list of strings that hold all powers of two which is what this is generating
lines = []
for i in range(1,9):
lines.append([str(2**j) for j in range(i)])
But if we just print this list, a) its going to only have half, and b) its going to mush the numbers together. We need to buffer the numbers with spaces. Fortunately, the last row will have the largest digits for any column, so:
Firstly, how long does each line need to end up being (we need this later) and also, what is the longest number in each column. We can use len as we cast the numbers to strings above.
b = len(lines[-1])
buffers = [len(x) for x in lines[-1]]
Now I have everything I need to print the strings (we stopped using numbers above):
So, for each line, find out how long it is, and expand the array it to the length of the longest line by filling the left of the array with empty strings (for this we're still pretending we're only printing the left half of the triangle):
for line in lines:
l = len(line)
line = [" "]*(b-len(line)) + line
With each line now buffered, we'll make a new array that we will print from. By zip()ing together the line and the buffer, we can easily right justify (String.rjust()) numberic strings, expanded out to the length required.
out = []
for x,y in zip(line,buffers):
out.append(x.rjust(y))
Remmeber until now, we've still just been working with the left half of the pyramid. So we take the output array, reverse it (array[::-1]) and then take every element but the first (array[1:]) and join it all together with a string and print it out.
print(" ".join(out+out[::-1][1:]))
Voila! The completed code:
lines = []
for i in range(1,9):
lines.append([str(2**j) for j in range(i)])
b = len(lines[-1])
buffers = [len(x) for x in lines[-1]]
for line in lines:
l = len(line)
line = [" "]*(b-len(line)) + line
out = []
for x,y in zip(line,buffers):
out.append(x.rjust(y))
print(" ".join(out+out[::-1][1:]))
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
height = 8
maxHeight = height - 1
for i in range(height):
k, Max = 1, i * 2 + 1
print(maxHeight * " ", end="")
maxHeight -= 1
for j in range(Max):
print("%5d" % k, end="")
if (j < (Max // 2)):
k *= 2
else:
k //= 2
print()
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
This could be the other 9 line solution.
Generate power of two's numbers as series
Find the offset need to add in each rows
Print the empty space for the each row before printing the palindromic list.
Ie. (offset * (n - i)) times " "(empty space)
Build palindromic series by slice operation ie. temp + temp[::-1][1:]
Print the palindromic series and offset spaces relative to the length of the number you are printing.
Code:
n = 8
numbers = [2**x for x in range(n)] # Generate interseted series.
offset = len(str(numbers[-1:])) -1 # Find the max offset for the tree.
for i in range(1, n+1): # Iterate n times. 1 to n+1 helps eazy slicing.
temp = numbers[:i] # Slice series to get first row numbers.
print(' ' * (offset * (n - i)), end=" ") # Prefix spaces, multiples of offset.
for num in temp + temp[::-1][1:]: # Generate palindromic series for the row.
print(num, end=" " * (offset - len(str(num)))) # Adjust offset for the number.
print('')
output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1

Categories

Resources