Python - Receiving an TypeError - python-3.x

So the code below:
Takes a given square, and if it is an X does nothing. If the square has an O in it, it changes the O to an X and autofills the square above, below, to the left, and to the right.
#openFile(filename): This function opens and prints the users txt file for paint
#input: none
#output: The file that needs to be painted
def openFile(filename):
file = open(filename, 'r')
for line in file:
print(line)
file.close()
#convertFile(filename): This function is used to convert the .txt file into a 2D arrary
#input: none
#output: none
def convertFile(filename):
empty = []
filename = open(filename, 'r')
for line in filename:
line = line.rstrip("\n")
empty.append(list(line))
return empty
#getCoordinates(x,y): This function is used to get the coordinates the user wants to pain from
#input: user coordinates.
#output: none
def getCoordinates(x, y):
coordinates = []
userInt = 0
user = []
try:
user = input("Please enter a square to fill , or q to exit: ")
user.split()
coordinates.append(int(user[0]))
coordinates.append(int(user[2]))
except ValueError:
print("Enter a valid input!")
user = input("Please enter a square to fill, or q to exit: ")
user.split()
coordinates.append(int(user[0]))
coordinates.append(int(user[2]))
return coordinates
def printGrid(grid):
for innerList in grid:
for item in innerList:
print(item, end = "")
print()
#autoFill(board, row, col): This is the heart of the program and the recursive program
# use to fill the board with x's
#input: none
#output: none
def autoFill(grid, rows, cols):
if grid[cols][rows] == "X":
return 0
else:
grid[cols][rows] = "X"
if rows > 0:
autoFill(grid, rows - 1, cols)
if rows < len(grid[cols]) - 1:
autoFill(grid, rows + 1, cols)
if cols > 0:
autoFill(grid, rows, cols - 1)
if cols < len(grid) - 1:
autoFill(grid, rows, cols + 1)
def main():
coordinates = []
empty = []
while True:
filename = input("Please enter a filename: ")
openFile(filename)
empty = convertFile(filename)
coordinates = getCoordinates(len(empty), len(empty[0]))
empty = autoFill(empty(coordinates[0], coordinates[1]))
for item in empty:
s = ""
s.join(item)
for x in item:
s += str(x)
print(s)
if user == "q":
return 0
main()
output should look like:
Please enter a filename: input.txt
OOOOOOXOOOO
OOOOOXOOOOO
OOOOXOOOOOO
XXOOXOOOOOO
XXXXOOOOOOO
OOOOOOOOOOO
Please enter a square to fill, or q to exit: 1, 1
XXXXXXXOOOO
XXXXXXOOOOO
XXXXXOOOOOO
XXXXXOOOOOO
XXXXOOOOOOO
OOOOOOOOOOO
But when i type in the coordinate points i get:
empty = autoFill(empty(coordinates[0], coordinates[1]))
TypeError: 'list' object is not callable
Any guidance in fixing this issue will be much appreciated

The particular error you're asking about is happening because you're trying to call empty (which is a list, as returned by convertFile) as if it were a function.

Related

Create a empty list. Populate the list with couple of numbers until the input is -1

Example for above question:
Explanation:
User is giving some random input(negative and positive). i am storing all in a list and I want only positive number should be present. remove all the negative number
What i have tried:
input_1st = []
var = int(input())
for j in range (0, var):
ele = int(input())
input_1st.append(ele)
for i in input_1st:
if (i>0):
lst.append(i)
print(lst)
the error I have got:
thankyou
Just read all input and check the value.
result = []
while True:
try:
value = int(input())
if value > 0:
result.append(value)
except EOFError:
break
print(result)

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.

Running out of index in binary search

###Binary Search###
def search(list1,n):
l=0
u=len(list1)
print(u)
while l<=u:
mid = (l+u)//2
if list1[mid]==n:
global index1
index = mid
return True
else:
if list1[mid]<n:
l = list1[mid]
else:
u = list1[mid]
list1 = [4,7,8,12,45,99.102,702,10987,56666]
n = 12
list1.sort()
if search(list1, n):
print("Found at ",index)
else:
print("Not Found")
The error I am getting is:
line 26, in <module> if search(list1, n): line 11, in search if list1[mid]==n: IndexError: list index out of range
I am assuming your the u in your code is supposed to be the high pointer. In that case it should be initialized to len(list1) - 1 and in the end the left and right pointers should be set to l = list1[mid+1] and u = list1[mid-1]. For binary search its always easier to implement the recursive method. Find out more info here

Appending results from a list to a string

Heavy python beginner here. I want to create a simple function for a PIN guessing game that receives two 4-digit lists ( [guess], [answer] ) and returns a string with 4 letters stating how close I am to guessing the correct [answer] sequence (eg. Higher, True, Lower, Higher)
However, I get a new list for each string:
def checkNumbers(guess,right):
for n in range(4):
result = []
if guess[n] == right[n]:
result.append("T") #true
elif guess[n] < right[n]:
result.append("H") #higher
elif guess[n] > right[n]:
result.append("L") #lower
else:
result.append("F") #false
print (result)
return
checkNumbers([1,2,3,5],[2,2,1,6])
The result should look like this:
checkNumbers([1,2,3,4], [2, 2, 1 , 6]) #call function with ([guess], [answer])
'HTLH' #returns a string stating how accurate [guess] is to [answer] list
Result looks like this however:
checkNumbers([1,2,3,5],[2,2,1,6])
['H']
['T']
['L']
['H']
Thanks very much in advance for any help I could get.
you can use string instead of list or "".join()
def checkNumbers(guess, right):
result = ""
for n in range(4):
if guess[n] == right[n]:
result += "T" # true
elif guess[n] < right[n]:
result += "H" # higher
elif guess[n] > right[n]:
result += "L" # lower
else:
result += "F" # false
print(result)
but... maybe you want to use zip function
def checkNumbers(guess, right):
result = ""
for g, r in zip(guess, right):
if g == r:
result += "T" # true
elif g < r:
result += "H" # higher
elif g > r:
result += "L" # lower
else:
result += "F" # false
print(result)
Funny bonus here:
def checkNumbers(guess, right):
print("".join("THL"[(g > r) + (g != r)] for g, r in zip(guess, right)))
I don't get why you need else part...
Initiate the list and print the result outside of the loop:
def checkNumbers(guess, right):
result = []
for n in range(4):
# do loopy stuff
print (result)
return # not strictly necessary
If you do it inside, you are creating a new list on every iteration.

Extending current code to include both median and mode

I have this line of code that i used for one assignment, but i can't figure out how to add the median and mode into the code to let it run without error.
def main():
filename = input('File name: ')
num=0
try:
infile = open(filename, 'r')
count = 0
total = 0.0
average = 0.0
maximum = 0
minimum = 0
range1 = 0
for line in infile:
num = int(line)
count = count + 1
total = total + num
if count == 1:
maximum = num
minimum = num
else:
if num > maximum:
maximum = num
if num < minimum:
minimum = num
if count > 0:
average = total / count
range1 = maximum - minimum
I'll jump right in and show you the code. It's a very simple and quite pythonic solution.
Solution
import statistics
def open_file(filename):
try:
return open(filename, 'r')
except OSError as e:
print(e)
return None
def main():
# Read file. Note that we are trusting the user input here without sanitizing.
fd = open_file(input('File name: '))
if fd is None: # Ensure we have a file descriptor
return
data = fd.read() # Read whole file
if data == '':
print("No data in file")
return
lines = data.split('\n') # Split the data into a list of strings
# We need to convert the list of strings to a list of integers
# I don't know a pythonic way of doing this.
for number, item in enumerate(lines):
lines[number] = int(item)
total_lines = len(lines)
total_sum = sum(lines)
maximum = max(lines)
minimum = min(lines)
# Here is the python magic, no need to reinvent the wheel!
mean = statistics.mean(lines) # mean == average
median = statistics.median(lines)
mode = "No mode!"
try:
mode = statistics.mode(lines)
except statistics.StatisticsError as ec:
pass # No mode, due to having the same quantity of 2 or more different values
print("Total lines: " + str(total_lines))
print("Sum: " + str(total_sum))
print("Max: " + str(maximum))
print("Min: " + str(minimum))
print("Mean: " + str(mean))
print("Median: " + str(median))
print("Mode: " + str(mode))
if __name__ == '__main__':
main()
Explanation
Generally, in python, it's safe to assume that if you want to calculate any mundane value using a well known algorithm, there will already be a function written for you to do just that. No need to reinvent the wheel!
These functions aren't usually hard to find online either. For instance, you can find suggestions regarding the statistics library by googling python calculate the median
Although you have the solution, I strongly advise looking through the source code of the statistics library (posted below), and working out how these functions work for yourself. It will help your grow as a developer and mathematician.
statistics.py
mean
def mean(data):
"""Return the sample arithmetic mean of data.
>>> mean([1, 2, 3, 4, 4])
2.8
>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)
>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')
If ``data`` is empty, StatisticsError will be raised.
"""
if iter(data) is data:
data = list(data)
n = len(data)
if n < 1:
raise StatisticsError('mean requires at least one data point')
T, total, count = _sum(data)
assert count == n
return _convert(total/n, T)
median
def median(data):
"""Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:
>>> median([1, 3, 5])
3
>>> median([1, 3, 5, 7])
4.0
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
if n%2 == 1:
return data[n//2]
else:
i = n//2
return (data[i - 1] + data[i])/2
mode
def mode(data):
"""Return the most common data point from discrete or nominal data.
``mode`` assumes discrete data, and returns a single value. This is the
standard treatment of the mode as commonly taught in schools:
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3
This also works with nominal (non-numeric) data:
>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
If there is not exactly one most common value, ``mode`` will raise
StatisticsError.
"""
# Generate a table of sorted (value, frequency) pairs.
table = _counts(data)
if len(table) == 1:
return table[0][0]
elif table:
raise StatisticsError(
'no unique mode; found %d equally common values' % len(table)
)
else:
raise StatisticsError('no mode for empty data')

Resources