Multiplication tables will not work in my code - python-3.x

What is wrong with my function? I have to write a function that prints out the multiplication table for the specified number. For example: in multiTable(num) if num = 6, then the function should print:"see attached photo".. This is python by the way. Thank you in advance for the help.
Here is my code:
def multiTable(num):
empty=""
print('\t',end='')
for row in range(1,num):
for column in range(1,num):
empty = empty + (str(row*column) +'\t') + '\n'
print(empty)

Reset variable before each loop
First of all you need to reset value of empty variable before each inner loop
Your value should be initialized with empty string: empty = ''
range loops EXCLUISVE
To loop in given range use num + 1 as the ending point
Fixed code
def multiTable(num):
# Display top line
for i in range(1, num + 1):
print('\t' + str(i), end='')
print()
# Show mutiplication table
for row in range(1, num + 1):
# Start by multiplier on the left
empty = str(row) + '\t'
for column in range(1, num + 1):
empty = empty + str(row * column) + '\t'
print(empty)

Related

Speeding up my code for pset6 DNA in cs50x

I am currently doing CS50 DNA pset and I wrote all of my code but it is slower for large files which results in check50 considering it wrong. I have attached my code and the error check50 shows below.
import sys
import csv
def main():
argc = len(sys.argv)
if (argc != 3):
print("Usage: python dna.py [database] [sequence]")
exit()
# Sets variable name for each argv argument
arg_database = sys.argv[1]
arg_sequence = sys.argv[2]
# Converts sequence csv file to string, and returns as thus
sequence = get_sequence(arg_sequence)
seq_len = len(sequence)
# Returns STR patterns as list
STR_array = return_STRs(arg_database)
STR_array_len = len(STR_array)
# Counts highest instance of consecutively reoccurring STRs
STR_values = STR_count(sequence, seq_len, STR_array, STR_array_len)
DNA_match(STR_values, arg_database, STR_array_len)
# Reads argv2 (sequence), and returns text within as a string
def get_sequence(arg_sequence):
with open(arg_sequence, 'r') as csv_sequence:
sequence = csv_sequence.read()
return sequence
# Reads STR headers from arg1 (database) and returns as list
def return_STRs(arg_database):
with open(arg_database, 'r') as csv_database:
database = csv.reader(csv_database)
STR_array = []
for row in database:
for column in row:
STR_array.append(column)
break
# Removes first column header (name)
del STR_array[0]
return STR_array
def STR_count(sequence, seq_len, STR_array, STR_array_len):
# Creates a list to store max recurrence values for each STR
STR_count_values = [0] * STR_array_len
# Temp value to store current count of STR recurrence
temp_value = 0
# Iterates over each STR in STR_array
for i in range(STR_array_len):
STR_len = len(STR_array[i])
# Iterates over each sequence element
for j in range(seq_len):
# Ensures it's still physically possible for STR to be present in sequence
while (seq_len - j >= STR_len):
# Gets sequence substring of length STR_len, starting from jth element
sub = sequence[j:(j + (STR_len))]
# Compares current substring to current STR
if (sub == STR_array[i]):
temp_value += 1
j += STR_len
else:
# Ensures current STR_count_value is highest
if (temp_value > STR_count_values[i]):
STR_count_values[i] = temp_value
# Resets temp_value to break count, and pushes j forward by 1
temp_value = 0
j += 1
i += 1
return STR_count_values
# Searches database file for DNA matches
def DNA_match(STR_values, arg_database, STR_array_len):
with open(arg_database, 'r') as csv_database:
database = csv.reader(csv_database)
name_array = [] * (STR_array_len + 1)
next(database)
# Iterates over one row of database at a time
for row in database:
name_array.clear()
# Copies entire row into name_array list
for column in row:
name_array.append(column)
# Converts name_array number strings to actual ints
for i in range(STR_array_len):
name_array[i + 1] = int(name_array[i + 1])
# Checks if a row's STR values match the sequence's values, prints the row name if match is found
match = 0
for i in range(0, STR_array_len, + 1):
if (name_array[i + 1] == STR_values[i]):
match += 1
if (match == STR_array_len):
print(name_array[0])
exit()
print("No match")
exit()
main()
Check50 error link:
https://submit.cs50.io/check50/fd890301a0dc9414cd29c2b4dcb27bd47e6d0a48
If you wait for long, then you get the answer but since my program is running slow check50 is considering it wrong
Well, I solved it just by adding a break statement.

I wonder how is second 'return' works - return len(A) + 1

This is a coding lesson from Github.
I wonder how the second return, return len(A) + 1 works.
list A is made form 1 to N+1 with 1 number missing
N is number 0 - 100000
ever number in list A is different
The solution is find the missing number.
def solution(A):
index_dict = {index+1: value for index, value in enumerate(A)}
value_dict = {value: index+1 for index, value in enumerate(A)}
for k in index_dict:
if k not in value_dict:
return k
return len(A) + 1
I figured out until return k. wondering how the return len(A) + 1 works
Thank you in advance for any answers.
The last line, return len(A) + 1 is the value that will be returned if all of the values of index_dict can be found from value_dict. Thus it will fall back to returning the value of N + 1, because it had to be the one that was missing from the list.
The solution can actually be even simplified and made more efficient by using sets instead of dicts:
def solution(A):
index_set = {index + 1 for index, _ in enumerate(A)}
value_set = {value for value in A}
for k in index_set:
if k not in value_set:
return k
return len(A) + 1
Then we also notice that we can remove the set comphrenesion and just call set(A) and that we can replace the index_set with a range object:
def solution(A):
set_A = set(A) # store this, so it doesn't have to be recomputed on every loop
for k in range(1, len(A) + 1):
if k not in set_A:
return k
return len(A) + 1
We can also just increase the range by 1 and remove the last return completely. This solution is actually way more effiecient than the original one and is around 7x faster on my machine:
def solution(A):
set_A = set(A)
for k in range(1, len(A) + 2):
if k not in set_A:
return k
Not gonna get more efficient than that, but just for fun, we can make a set out of the range, and return the single element that's left over from the difference of that and set(A):
def solution(A):
return set(range(1, len(A) + 2)).difference(set(A)).pop()

Change specific elements of a matrix puzzle - Python

I have to solve how to replace the elements below zero elements with zeros and output the sum of the remaining elements in the matrix.
For example, [[0,3,5],[3,4,0],[1,2,3]] should output the sum of 3 + 5 + 4 + 1 + 2, which is 15.
So far:
def matrixElementsSum(matrix):
out = 0
# locate the zeros' positions in array & replace element below
for i,j in enumerate(matrix):
for k,l in enumerate(j):
if l == 0:
break
out += l
return out
The code outputs seemingly random numbers.
Can someone fix what's wrong? Thanks
You can easily drop elements that are below a zero element is by using the zip function.
def matrixElementsSum(matrix):
out = 0
# locate the zeros' positions in array & replace element below
for i,j in enumerate(matrix):
# elements in the first row cannot be below a '0'
if i == 0:
out += sum(j)
else:
k = matrix[i-1]
for x, y in zip(j, k):
if y != 0:
out += x
return out
Now consider naming your variables a little more meaningfully. Something like:
def matrixElementsSum(matrix):
out = 0
# locate the zeros' positions in array & replace element below
for row_number, row in enumerate(matrix):
# elements in the first row cannot be below a '0'
if row_number == 0:
out += sum(row)
else:
row_above = matrix[row_number - 1]
for element, element_above in zip(row, row_above):
if element_above != 0:
out += element
return out
You should look into list comprehensions to make the code even more readable.

Python, using list of lists to update a self made board

I'm trying to put my list "Grid" into the board so whenever the user gives what column and row they want to fire at, it will update the guess onto the board. Any help on this?
def displayGrid(Rows,Columns):
output = ' |'
if (Rows >= 10) or (Columns >= 27):
print("Please pick a Row less than 10 or a number less than 27")
else:
for title in range(97,97+Columns):
output = output + chr(title)
output = output + ' |'
print(output.upper())
for row in range(Rows):
output = str(row+1) + '| '
for col in range(Columns):
output = output + ' | '
print(output)
displayGrid(Rows, Columns)
GuessRow = int(input("What row do you guess? \n"))
GuessColumn = int(input("What column do you guess? \n"))
def userGuess(GuessRow, GuessColumn):
grid = []
for row in range(Rows):
grid.append([])
for col in range(Columns):
grid[row].append('')
grid[GuessRow-1][GuessColumn-1] = 'X'
print(grid)
userGuess(GuessRow, GuessColumn)
Here are couple example functions. create_grid creates an empty grid of zeros. update_grid updates the specified index to an X. I find pprint helpful for nicely formatting nested tables. Also checkout tabulate library when you are working on output.
from pprint import pprint as pp
def create_grid(numRows,numColumns):
grid = []
for row in range(numRows):
row = []
for column in range(numColumns):
row.append(0)
grid.append(row)
return grid
def update_grid(grid, guessRow, guessColumn):
grid[guessColumn][guessRow] = 'X'
numRows = 7
numColumns = 7
grid = create_grid(numRows,numColumns)
pp(grid)
guessRow = 5
guessColumn = 2
update_grid(grid, guessRow, guessColumn)
pp(grid)

Printing on the same line different Permuations of a value

Hey guys so here is my question. I have written code that sums two prime numbers and prints the values less than or equal to 100 and even. How do I write it so that every combination of the number prints on the same line
like so
100 = 3 + 97 = 11 + 89
def isPrime(n):
limit = int(n ** 0.5) +1
for divisor in range (2, limit):
if (n % divisor == 0):
return False
return True
def main():
a = 0
b = 0
for n in range (4, 101):
if (n % 2 == 0):
for a in range (1, n + 1):
if isPrime(a):
for b in range (1, n + 1):
if isPrime(b):
if n == (a + b):
print ( n, "=", a, "+", b)
main()
any ideas?
I don't know too much about strings yet, but I was thinking we could set the string as n == a + b and some how repeat on the same line where n == n print the a + b statement or idk haha
One way to do this is to accumulate a and b pairs in some collection, then print a line containing all the pairs. Here's an example with some comments explaining whats going on and general Python tips:
def main():
for n in range (4, 101, 2): # range() can have third argument -> step
accumulator = []
for a in filter(isPrime, range(1, n + 1)): # filter() is useful if you want to skip some values
for b in filter(isPrime, range (1, n + 1)):
if n == (a + b):
accumulator.append((a,b)) # We accumulate instead of printing
str_accumulator = ["{} + {}".format(i[0], i[1]) for i in accumulator]
joined_accumulator = " = ".join(str_accumulator)
print("{} = {}".format(n, joined_accumulator))
Now, some explanation:
range(4, 101, 2) - as said in comment, it has an optional third argument. Some examples and explanations on how to use range in documentation.
filter() - Very useful generic iterator constructor. You pass a function that returns True/False, a collection, and you receive an iterator that spits out only those elements from the collection that are accepted by the function. See documentation.
str.format - For me, format is the best way to paste values into strings. It has PLENTY options and is very versatile. You should read the whole documentation here.
str.join - When you have a collection of string, and you want to make one string of them, join is what you want. It's much faster than str + str operation, and also you don't have to care if there is one or many elements in the collection. See documentation.

Resources