Okay so we just got introduced to loops, and I've been scratching my head for days trying to figure it out. I'm trying to print pascal's triangle.
I found some code online that is simple and something that I can really understand!
rows = int(input("Enter the number of rows : "))
for i in range(0, rows):
coff = 1
for j in range(1, rows-i):
print(" ", end="")
for k in range(0, i+1):
print(" ", coff, end="")
coff = int(coff * (i - k) / (k + 1))
print()
However, how did they get this formula? coff = int(coff * (i - k) / (k + 1)),
I've been searching online on how they derived that, but I still can't find any answers.
I understand how the loop works but I'm scratching my head as to how they got the formula to get the terms. Help is appreciated!
For each position in Pascal's Triangle, the value is i Choose k, where i is the row (starting with 0 on the first row) and k is the position in the row (also starting with 0). i and k here (almost) matches with the variables in your code.
Now, Wikipedia sports this identity:
The trick for transforming this into your code, is that coff = int(coff * (i - k) / (k + 1)) runs after coff is printed, so we need to add 1 to k.
If you want the code closer to the formula, you could do the following:
coff = 1
for k in range(1, i+2):
print(" ", coff, end="")
coff = int(coff * (i + 1 - k) / k)
Related
I am new on Python and I am following a book that purposes the following excercise:
Write a program to generate the following pattern in Python:
*
**
***
****
The suggested code is:
n = input('Enter the number of rows: ')
m = int(n)
*k = 1
for i in range(m):
for j in range(i, i + 2):
print('*', end = " ")
print()
and enter n=5.This lead me to ask to questions. The first one is the *k=1, I am asumming the '' is a typo on the book since my program does not run with it. However i am not seeing that k is being used within the loop. My second question is that I do not understand why my outcome is different than the one I get (once removed the ''). This is what I get when n=5:
**
**
**
**
**
This works for your problem. In python, you can multiply strings. It will be useful for the problem. *k is a typo.
n = input(' num rows: ')
n = int(n)
for i in range(1, n + 1):
print ('*' * i)
You can try this solution. I am pretty sure the *k = 1 is a typo.
n = int(input('Enter the number of rows: '))
k = 1
for i in range(n):
print(k * '* ', end = "\n")
k += 1
Another approach if you don't want to use multiplication approach:
n = input('Enter the number of rows: ')
m = int(n)
for i in range(m):
for j in range(1, i + 2):
print('*', end = " ")
print()
def printStarsInTriangeForm(count):
for i in (range(1, count + 1)):
print("*" * i)
This is one way. :)
yea *k = 1 cant be right, you can delete it.
Your mistake or the mistake in the book is the line:
for j in range(i, i + 2):
if you type i * 2 it works:
for j in range(i, i * 2):
and if you want no spaces between the starts you need to change the print in the loop to:
print("*",end="")
i just removed the space in the "end".
and a better way you can do this is
m = int(input('Enter the number of rows: '))
for i in range(m + 1):
print(i * "*")
I find a new way to traverse the quartet neighbors by using complex number in this solution.
https://leetcode.com/problems/word-search-ii/discuss/59804/27-lines-uses-complex-numbers
(you can just read my example.)
I think it is elegant and concise, but I can not fully understand about it.
Here I have extracted the key code, and simplify the exmaple.
board is a 2d array, and we want to start from every node, and traverse the 4 direction neigbor recursively by dfs:
this is a common way:
def dfs(i, j, word):
# create 4 direction by hand
for I, J in (i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1):
# need to check boundary
if 0 <= I < len(board) and 0 <= J < len(board[0]):
dfs(I, J, word + c)
for i, j in board:
dfs(i, j, '')
here is using complex number as index:
board = {i + 1j * j: c
for i, row in enumerate(board)
for j, c in enumerate(row)}
def dfs(z, word):
c = board.get(z)
# here is visit 4 direction neighbors, which I don't understand
if c:
for k in range(4):
search(node[c], z + 1j ** k, word + c)
for z in board:
dfs(z, '')
I think there is two advantages by using complex number:
don't need to create 4 direction by hand
don't need to check boundary
But I can't understand here for k in range(4): dfs(z + 1j ** k, word + c)
can somebody explain this algorithm? really appreciate it.
If what I think is correct this solution uses the following property of the imaginary number j:
which if added to a complex number as a representation of a grid are the nodes: right, up, left, down
According to me this code below should print the sum of first n integers but it is giving me name error on line 5. How do I fix this ?
def printsum(n):
n = int(raw_input())
for i in range(1,n+1):
j = i + 1
doublesum = i + j - n
total = doublesum / 2
print total
The variables i and j are local to the function printsum. Simply return the values from the function and use said values to do your calculation.
Try with this code copy and past. Because issue may be indentation
def printsum(n):
n = int(raw_input())
for i in range(1,n+1):
j = i + 1
doublesum = i + j - n
total = doublesum / 2
print total
return;
Your logic is make me confused too.
Let's say I have two numbers: 6 and 11 and I am trying to find how many numbers between this range are divisible by 2 (3, in this case).
I have this simple code right now:
def get_count(a, b, m):
count = 0
for i in range(a, b + 1):
if i % m == 0:
count += 1
return count
Its order of growth is linear, O(N), I believe.
I was wondering if there is a faster algorithm with a constant O(1) performance, or a mathematical formula.
I don't expect a direct answer. The name of such an algorithm would be awesome.
Thank you.
((b - b%m) - a)//m+1 seems to work for me. I doubt it has a name. Another formula that seems to work is (b//m) - ((a-1)//m).
Sample python3 program:
def get_count(a, b, m):
return (((b - (b % m)) - a) // m) + 1
for i in range(5, 8):
for j in range(10, 13):
print(get_count(i, j, 2), end=" ")
print()
You are counting even numbers. Let's write o for odd, E for even.
If the sequence has an even count of numbers, it is either oEoE...oE or EoEo...Eo, i.e. one half of numbers is always even. If there is odd count of numbers, you can check the first number (or last one) separately and the rest is the known case discussed first.
def count_even(start, end):
# assert start <= end
len = end - start
len2, r = divmod(len, 2)
if r and start % 2 == 0:
len2 += 1
return len2
To find the count of all numbers between 0 and n that are divisible by two. you can use the bitwise operation called right shift;
c = a >> 1;
10 >> 1 is equivalent to floor(10/2)
You can subtract the two resultant numbers and get numbers between any range.
This will work in O(1). Hope this helps.
This is my first assignment dealing with Dynamic Programming and I'm finding it quite difficult.
Problem:
Given a knapsack of capacity W and n gold bars of weights [wt[0],..., wt[n - 1], find maximum number of gold bars that can fit into knapsack without repetition.
input:
line 1:(capacity knapsack(W)) (num gold bars(n))
line 2: weights of n gold bars (wt)
output: max weight (of gold bars) that can fit in knapsack of capacity W
My code:
import sys
def optimal_weight(W, wt):
"""Find max weight that can fit in knapsack size W."""
# Create n nested arrays of 0 * (W + 1)
max_vals = [[0] * (W + 1) for x in range(len(wt))]
# Set max_vals[0] to wt[0] if wt[0] <= j
max_vals[0] = [wt[0] if wt[0] <= j else 0 for j in range(W + 1)]
for i in range(1, len(wt)):
for j in range(1, W + 1):
value = max_vals[i - 1][j] # previous i # same j
if wt[i] <= j:
val = (max_vals[i - 1][j - wt[i]]) + wt[i]
if value < val:
value = val
max_vals[i][j] = value
else:
max_vals[i][j] = value
return max_vals[-1][-1]
if __name__ == '__main__':
input = sys.stdin.read()
W, n, *wt = list(map(int, input.split()))
print(optimal_weight(W, wt))
Any ideas where I'm going wrong? When I observe my ending max_vals, I am seeing that max_vals, as i increases, is only replacing increasingly smaller values (i - 1) in each nested list. In other words, as I continue iterating, fewer 0's are being replaced with the value of max_vals[i - 1][j]. Somewhat embarrassingly, I've been working on this for almost a week and can't figure it out. This video, aside from the class lecture video, has been my main point of reference. Dynamic programming is proving to be a pretty big challenge.
Trivially easy fix. Can't believe I missed it. Was just messing up with the else statements. Needed an extra.
if value < val:
value = val
max_vals[i][j] = value
else:
max_vals[i][j] = value # set to [i - 1][j]
else:
max_vals[i][j] = value # set to [i - 1][j]