How to implement input into multiplication table? - python

Heyy, i got a bit of help earlier but am stuck once again :(
I am completely new to coding so i apologize for questions on such simple matters.
I am writing a program that puts out a multiplication table for the numbers that the user chooses(Using while instead of for to better understand how while loops work)
This is what i have so far:
print(end='')
max_x = int(input("Number of columns:"))
x = 1
while x <= max_x:
print(end='')
x += 1
max_y = int(input("Number of rows:"))
y = 1
while y <= max_y:
print('')
print(end='')
z = 1
while z <= max_x:
print(y*z, end='\t')
z += 1
y += 1
And this is the output that i get:
Number of columns:5
Number of rows:4
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
My issue is that i can´t for the life of me figure out how to get the table to also include the 1, as in:
1 2 3 4
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16
Appreciate any help as i´ve been trying and googling a bunch and frankly feel quite dumb struggling with such a simple thing

The extra digits are for the axis labels so they need to be drawn separately.
Try this code:
print(end='')
max_x = int(input("Number of columns:"))
x = 1
while x <= max_x:
print(end='')
x += 1
max_y = int(input("Number of rows:"))
y = 1
print(' \t' + '\t'.join([str(i+1) for i in range(max_x)]), end="") # labels X axis
while y <= max_y:
print('')
print(end='')
z = 1
print(y,end='\t') # label Y axis
while z <= max_x:
print(y*z, end='\t')
z += 1
y += 1
Output:
Number of columns:4
Number of rows:4
1 2 3 4
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16

Related

sum of Fibbonaci Sequences?

Trying to add the sum of Fibonacci, using definite loops. It's meant to calculate the summation of Fibonacci number with each number too. Below is the sample for the Fibonacci sequence and its summation, how do i add the sum of the fibonacci eg 1,1,2,3,5,8
Fibonacci Summation
0 0
1 1
1 2
2 4
3 7
5 12
8 20
n = int(input("enter"))
def fibonacciSeries():
a=0
b=1
for i in range (n-2):
x = a+b
a=b
b=x
int(x)
x[i]= x+x[i-1]
#should add the previous sequences
print(x)
fibonacciSeries()
You don't need to keep track of the whole sequence. Plus your Fibonacci implementation doesn't start with 1, 1 but rather 1, 2 so I fixed that.
def fibonacciSeries(n):
a=0
b=1
x=1
series_sum = 0
for i in range (n-2):
series_sum += x
print(f'{x} {series_sum}')
x = a+b
a=b
b=x
n = 10
fibonacciSeries(n)
Output:
1 1
1 2
2 4
3 7
5 12
8 20
13 33
21 54
def fibonacciSeries(n):
sum = 0
a = 0
b = 1
x = 1
sum = 0
for i in range(0,n - 2):
sum += x
print(x,sum)
x = a + b
a = b
b = x
n = int(input("enter : ")) # n = 8
fibonacciSeries(n)
Output:
enter : 8
1 1
1 2
2 4
3 7
5 12
8 20

2D list editing in Python

I am trying to edit a 5 * 5 square matrix in Python.And I initialize every element in this 5 * 5 matrix with the value 0. I initialize the matrix by using lists using this code:
h = []
for i in range(5):
h.append([0,0,0,0,0])
And now I want to change the matrix to something like this.
4 5 0 0 0
0 4 5 0 0
0 0 4 5 0
0 0 0 4 5
5 0 0 0 4
Here is the piece of code -
i = 0
a = 0
while i < 5:
h[i][a] = 4
h[i][a+1] = 5
a += 1
i += 1
where h[i][j] is the 2 D matrix. But the output is always is showing something like this -
4 4 4 4 4
4 4 4 4 4
4 4 4 4 4
4 4 4 4 4
4 4 4 4 4
Can you guys tell me what is wrong with it?
Do the update as follows using the modulo operator %:
for i in range(5):
h[i][i % 5] = 4
h[i][(i+1) % 5] = 5
The % 5 in the first line isn't strictly necessary but underlines the general principle for matrices of various dimensions. Or more generally, for random dimensions:
for i, row in enumerate(h):
n = len(row)
row[i % n] = 4
row[(i+1) % n] = 5
Question answered here: 2D list has weird behavor when trying to modify a single value
This should work:
#m = [[0]*5]*5 # Don't do this.
m = []
for i in range(5):
m.append([0]*5)
i = a = 0
while i < 5:
m[i][a] = 4
if a < 4:
m[i][a+1] = 5
a += 1
i += 1

how can I decrease execution time needed for python code?

#https://www.codechef.com/problems/GRIDGM
from sys import setrecursionlimit
setrecursionlimit(10**6)
def sol(l,lst):
sum=0
for i in range(l[0],l[2]+1):
for j in range(l[1],l[3]+1):
#print(lst[i-1][j-1],end="")
sum += lst[i-1][j-1]
#print('---')
#print("sol below")
return sum
for _ in range(int(input())):
n,m=map(int, input("enter values of n and m").split())
lst=[]
for _ in range(n):
lst.append(list(map(int,input("enter a row").split())))
#print(lst)
#q=int(input())
#dj=[] #it saves x y and a b
for _ in range(int(input("enter no of queries"))):
#v=list(map(int,input().split()))
#print(v)
#print('sol below')
print(sol(list(map(int,input("enter cordinates").split())),lst))
sample input
1
4 4
9 13 5 2
1 11 7 6
3 7 4 1
6 0 7 10
2
2 1 4 2
2 2 4 4
output
28
53
above code took 5.1 sec to execute.
in this question, I have to find sum of elements within given coordinates a,b and x,y
more information about this problem can be found in the link below.
https://www.codechef.com/problems/GRIDGM

How to make a while loop for a multiplication table?

I am trying to create a multiplication chart with a while loop for an assignment but I am having a hard time getting the expected output.
I have tried everything I can think of. I am new to the coding world.
#While loop
print('While Loop')
print()
x = 1
y = 1
z = 1
while x <= 12:
print(x ,end='\t')
x += 1
while y <= 12:
print('\n')
print(y,'\t')
y += 1
while z <= 12:
print(x*z ,end='\t')
z += 1
z = 0
x = 1
I expect the output to be
but I get
.
Short answer: you use x*z when you calculate the product, but you use y as a "row counter" and z as a "column counter" so it should be y*z. Furthermore you should increment the y after the inner while loop.
Since you use y as the "row counter" and z as the "column counter", you should print y * z as the answer of that specific multiplication. Furthermore you increment y too soon: you should increment it after the while loop, and reset z to 1, like:
print('While Loop')
print('x', end='\t') # print a cross
x = 1
while x <= 12:
print(x ,end='\t')
x += 1
y = 1
while y <= 12:
print('')
print(y,end='\t')
z = 1 # reset to 1
while z <= 12:
print(y*z ,end='\t') # use y * z
z += 1
y += 1 # incerement after while loop
print()
Using for loops
There are also some minor formatting issues. For example you should first print('X', end='\t') since otherwise the columns do not match correctly.
That being said, you make things way harder than these should be. You can make use of a for loop instead, like:
print('x', end='\t')
print('\t'.join(str(i) for i in range(1, 13)))
for r in range(1, 13):
print(r, end='\t')
print('\t'.join(str(r*c) for c in range(1, 13)))
or in a function:
def mulgrid(n):
print('x', end='\t')
print('\t'.join(str(i) for i in range(1, n+1)))
for r in range(1, n+1):
print(r, end='\t')
print('\t'.join(str(r*c) for c in range(1, n+1)))
For example:
>>> mulgrid(1)
x 1
1 1
>>> mulgrid(2)
x 1 2
1 1 2
2 2 4
>>> mulgrid(5)
x 1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
>>> mulgrid(7)
x 1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49

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