I am new to Python
I am trying to solve this problem. https://www.hackerrank.com/challenges/palindrome-index/problem
my code is here.
def palindrome(s):
string = ''
if s == s[::-1]:
print(-1) # return -1
else:
for i in range(len(s)):
string = s[:i]+s[i+1:]
if string == string[::-1]:
print(i) # return i
break
else:
if(i+1 == len(s)):
print(-1) # return -1
when I submitted the above code, I got some test cases passed and 3 test cases are "time limit exceeded".
Then I have gone through this video https://www.youtube.com/watch?v=gd4hCrbYAMg and tried the code given in the video as below.
def palindromeIndex(s):
if s == s[::-1]:
print(-1) # return -1
n = len(s)
for i in range(n//2):
if s[i] != s[n-1-i]:
if s[i:n-1-i] == s[i:n-1-i][::-1]:
print(n-1-i) # return n-1-i
elif s[i+1:n-i] == s[i+1:n-i][::-1]:
print(i) # return i
print(-1) # return -1
from the video, code above is successfully passed all test cases.
when I try to run above code in my terminal with plain text file with .py extension, it is giving 3 lines or 2 lines or 1line as a result for youtube linked script.
My Question is about the script from video link(which is palindromeIndex(s)), Can anyone explain why is this happening please?
example:
# palindrom.py
#!/bin/python3
#####################################################################
def palindromeIndex(s):
if s == s[::-1]:
print(-1)
n = len(s)
for i in range(n//2):
if s[i] != s[n-1-i]:
if s[i:n-1-i] == s[i:n-1-i][::-1]:
print(n-1-i)
elif s[i+1:n-i] == s[i+1:n-i][::-1]:
print(i)
print(-1)
#####################################################################
#####################################################################
def palindrome(s):
string = ''
if s == s[::-1]:
print(-1)
else:
for i in range(len(s)):
string = s[:i]+s[i+1:]
if string == string[::-1]:
print(i)
break
else:
if(i+1 == len(s)):
print(-1)
#####################################################################
s = input()
print('########### result of the script from video link ##############')
palindromeIndex(s)
print('################ result of the script by me ###################')
palindrome(s)
print('###########################################')
$ python palindrome.py
yellow
########### result of the script from video link ##############
-1
################ result of the script by me ###################
-1
###########################################
$ python palindrome.py
red
########### result of the script from video link ##############
-1
################ result of the script by me ###################
-1
###########################################
$ python palindrome.py
azad
########### result of the script from video link ##############
3
2 # } Not Expecting
-1 # } Not Expecting
################ result of the script by me ###################
3
###########################################
$ python palindrome.py
pratap
########### result of the script from video link ##############
1
3 # } Not Expecting
-1 # } Not Expecting
################ result of the script by me ###################
1
###########################################
$
I have a txt file which has values x , y listed as
20
80
70.....
I wrote code to read the x and y but i am not sure what i am doing wrong .
def readTruth():
with open("Truth.txt") as f:
for line in f:
x_truth, y_truth = line.split("\n")
return x_truth,y_truth
def main():
x,y = readTruth()
print(x)
if __name__ == "__main__":
main()
I only see one value getting printed in x.
You are reading one line at a time. So you cannot access the values in the 2nd line while reading the first line. Splitting the line by the newline character "\n" will do nothing in this instance.
If you only have 2 lines in your text file, you could do something like this:
# Note here that I am lazy and used a string here instead of text file
a_string = "1\n2"
def readTruth():
x_truth, y_truth = a_string.split("\n")
return x_truth,y_truth
x,y = readTruth()
print(x) # 1
print(y) # 2
But I suspect you have more than just 2 values. You could refactor your text file to hold the 2 values on the same line, separated by a space or comma. If you do so, your solution will work. You would just need to split by the comma or space, whichever delimiter you choose to use.
If you must have each number on a separate line, then your solution won't work. You would need to add the results to a list of X values and a list of Y values:
# truth.txt:
# 1
# 2
# 3
# 4
#
f = open("truth.txt", "r")
def readTruth():
counter = 1
X_vals = []
Y_vals = []
for line in f.readlines():
# If it is an even numbered line, add to Y_vals
if counter % 2 == 0:
Y_vals.append(line.strip("\n"))
# Otherwise it is an odd numbered line, so add to X_vals
else:
X_vals.append(line.strip("\n"))
counter+=1
return X_vals, Y_vals
x,y = readTruth()
print(x) # ['1', '3']
print(y) # ['2', '4']
Based on comments from the question poster, I assume they have a blank line between each number in their text file. This means each number is on an odd numbered line. The quick solution, added onto my previous example, is to skip blank lines:
# truth.txt:
# 1
#
# 2
#
# 3
#
# 4
#
f = open("truth.txt", "r")
def readTruth():
counter = 1
X_vals = []
Y_vals = []
for line in f.readlines():
# Skip blank lines
if line.strip("\n") != "":
# If it is an even numbered line, add to Y_vals
if counter % 2 == 0:
Y_vals.append(line.strip("\n"))
# Otherwise it is an odd numbered line, so add to X_vals
else:
X_vals.append(line.strip("\n"))
counter+=1
return X_vals, Y_vals
x,y = readTruth()
print(x) # ['1', '3']
print(y) # ['2', '4']
We obtain the values โโof X and Y:
def readTruth():
with open("Truth.txt") as f:
for line in f:
x_truth, y_truth = line.split("\n")
return x_truth,y_truth
def main():
x,y = readTruth()
print("Var_X = "+ str(x[0]))
print("Var_Y = "+ str(x[1]))
You can put the variables in a list for each X and Y
I am beginner who just copy a game sample from a book. The game working fine, and i able to understand all part of the exclude the read, write part.
The book didn't explain how it work and i been stuck at this part.
p/s: the game work totally fine. Just unable to write and read from highscore list.
def update_high_scores():
global score, scores
filename = r"/Users/User/Desktop/python/python-games/baloon fight/High-Score1.txt"
scores = []
with open(filename, "r") as file:
line = file.readline()
high_scores = line.split()
for high_score in high_scores:
if(score > int(high_score)):
scores.append(str(score) + " ")
score = int(high_score)
else:
scores.append(str(high_score) + " ")
with open(filename, "w") as file:
for high_score in scores:
file.write(high_score)
def display_high_scores():
screen.draw.text("HIGH SCORES", (350, 150), color="black")
y = 175
position = 1
for high_score in scores:
screen.draw.text(str(position) + ". " + high_score, (350, y), color="black")
y += 25
position += 1
I worked with your code, but updating it made the code more complicated. I thought it may be easier to provide a short function to update the score file.
The main steps:
Open the existing score file (scores are on single line separated by space)
Split the line and convert the scores to integers
If the current score is already included, just exit the function
Add the current score the score list
Sort the list and update the score file
Here is the code:
def update_high_scores():
global score, scores
filename = r"c:/tmp/High-Score1.txt" # file must exist
with open(filename, "r") as file:
line = file.readline() # scores are one line
high_scores = [int(s) for s in line.split()] # read scores as integers
if score in high_scores: # if current score already in high scores
return # no update needed
high_scores.append(score) # add current score
high_scores.sort() # sort scores (low - high)
with open(filename, "w") as file: # updates score file
for high_score in high_scores[::-1]: # write scores in reverse (high - low)
file.write(str(high_score) + " ")
I'm trying to write a program in Python 3.
This is how it works:
The input is a word.
And the program has to look if the word contains a dutch numeric word.
A word cannot contain more than 1 numeric word and if a word doesn't contain a numeric word than it has to print 'geen' (none in dutch).
example:
Input = BETWEEN
Output = TWEE (two in dutch)
Input = ZEEVERS
Output = ZES (six in dutch)
Here is my code:
import sys
invoer = input()
letterwoorden = [['T','W','E','E'], ['D','R','I','E'], ['V','I','E','R'],
['V','I','J','F'], ['Z','E','S'], ['Z','E','V','E','N'], ['A','C','H','T'],
['N','E','G','E','N']]
antwoord = []
woord = [str(a) for a in str(invoer)]
L = len(woord)
a = 0
b = 0
c = 0
for i in range(0, 8):
for j in range(0, len(letterwoorden[a])):
if letterwoorden[a][b] == woord[c]:
antwoord.append(letterwoorden[a][b])
b = b + 1
c = c + 1
else:
c = c + 1
if antwoord == letterwoorden[a]:
print(antwoord)
break
else:
a = a + 1
antwoord.clear()
if antwoord != letterwoorden[a]:
print('geen')
Could someone help me with the error on line 21? (list index out of range)
Thanks!
The code is not fully done but when the input is TWEET the output is TWEE,
when the input is BETWEEN it gives the error.
Even though usr2564301's first solution looks good, I wanted to add a couple things. You'll find this in the comments in the code.
Here's how I'd modify your code:
## use strings instead of list of strings
## ['T', 'W', 'E', 'E'] ==> 'TWEE'
## they are also iterable (you can loop through them)
## as well as indexable (['T', 'W', 'E', 'E'][0] == 'TWEE'[0])
letterwoorden = ['TWEE', 'DRIE', 'VIER', 'VIJF', 'ZES', 'ZEVEN', 'ACHT', 'NEGEN']
## keep the string
woord = input()
print('Input:', woord)
## answer should be string as well
antwoord = ''
## name your variables something meaningful
## how does one differentiate between b and c? smh
letterWoordenIndex = 0
woordenIndex = 0
## for-loops can be powerful in Python
## you might've been used to index-based loops from other languages :|
## this way, tempWord can replace all occurrences of letterwoorden[a]
for tempWord in letterwoorden:
## reset your variables at the beginning of the loop
letterWoordenIndex = woordenIndex = 0
# """ ## debug output printing word
print('Word:', tempWord, '?')
# """
## loop through the length of word
## use _ to indicate that the variable won't be used
for _ in range(len(woord)):
# """ ## debug output comparing letters/indices
print(tempWord[letterWoordenIndex],
'({})'.format(letterWoordenIndex),
'<=>', woord[woordenIndex],
'({})'.format(woordenIndex))
# """
## check current indices equals match
if tempWord[letterWoordenIndex] == woord[woordenIndex]:
antwoord += tempWord[letterWoordenIndex] ## append char to string using +
## increment indices
letterWoordenIndex += 1
woordenIndex += 1
## check if index is filled
if letterWoordenIndex == len(tempWord):
break
else:
woordenIndex += 1
# """ ## debug output comparing final results
print(antwoord, '>==<', tempWord)
# """
## assert that the accumulated result (antwoord)
## equates to the tempWord
if antwoord == tempWord:
# """ ## debug assert true
print('Yep\n')
# """
print(antwoord)
break
## no need to use else here
## if the code inside the above if executes, then it's already game-over
antwoord = '' ## empty the string
# """ ## debug assert false
print('Nope\n')
# """
## antwoord would be empty if everything failed
if antwoord == '':
print('GEEN')
You are iterating over the wrong list with your line
for j in range(0, len(letterwoorden[a])):
as this increases a for all letterwoordenagain โ you already iterate over letterwoorden with the first loop, for i in range(0, 8):. Changing that to iterate over the word in question led to another error if you run out of 'source' characters (the length of invoer) OR of 'compare' characters (the word woord[c]). You must also take care to reset your b and c counters when restarting a compare.
At the very end, you test antwoord[a] but a may be out of range
The following code works
import sys
invoer = input()
letterwoorden = [['T','W','E','E'], ['D','R','I','E'], ['V','I','E','R'],
['V','I','J','F'], ['Z','E','S'], ['Z','E','V','E','N'], ['A','C','H','T'],
['N','E','G','E','N']]
antwoord = []
woord = [str(a) for a in str(invoer)]
L = len(woord)
a = 0
b = 0
c = 0
for i in range(len(letterwoorden)):
b = 0
c = 0
for j in range(len(woord)):
print ('test', a,b,c, letterwoorden[a][b], woord[c])
if letterwoorden[a][b] == woord[c]:
antwoord.append(letterwoorden[a][b])
b = b + 1
if b >= len(letterwoorden[a]):
break
c = c + 1
else:
c = c + 1
if antwoord == letterwoorden[a]:
print(antwoord)
break
else:
a = a + 1
antwoord = []
if antwoord == []:
print('geen')
A few additional notes: you don't need to maintain separate variables if you already have a loop variable. Where you use a, for example, you can also use the loop i; and the same with j.
About all of your comparing can be done much more efficiently, since Python can immediately check if a phrase contains another phrase: if straw in haystack. So, basically,
invoer = 'ZEEVERS'
letterwoorden = ['TWEE', 'DRIE', 'VIER', 'VIJF', 'ZES', 'ZEVEN', 'ACHT', 'NEGEN']
for word in letterwoorden:
if word in invoer:
print (word)
break
else:
print ('geen')
where the else is linked to the for and not to the else, to check if the loop stopped for a result.
I'm trying to make Conway's Game of Life where the user enters how big they want the grid and which cells start off as alive. Here's what I have:
def firstBoard(rows, cols, array):
myList = [[0]*cols for i in range(rows)]
for i in myList:
i.append(-1)
i.insert(0,-1)
myList.insert(0,[-1]* (cols+2))
myList.append([-1]* (cols+2))
while True:
rows = input("Enter the row or 'q': ")
if rows == 'q':
break
cols = input("Enter the column: ")
print()
myList[int(rows)][int(cols)] = 1
return myList
def nextGen(cols, rows, cur, nxt):
for i in range(1,rows-1):
for j in range(1,cols-1):
nxt[i][j] = processNeighbours(i, j, cur)
def processNeighbours(x, y, array):
nCount = 0
for j in range(y-1,y+2):
for i in range(x-1,x+2):
if not(i == x and j == y):
if array[i][j] != -1:
nCount += array[i][j]
if array[x][y] == 1 and nCount < 2:
return 0
if array[x][y] == 1 and nCount > 3:
return 0
if array[x][y] == 0 and nCount == 3:
return 1
else:
return array[x][y]
def printBoard(cols, rows, array):
for i in range(rows+2):
for j in range(cols+2):
if array[i][j] == -1:
print("#", end=" ")
elif array[i][j] == 1:
print(".", end=" ")
else:
print(" ", end=" ")
print()
def main():
rows = int(input("Please enter the number of rows: "))
cols = int(input("Please enter the number of columns: "))
myList = []
newList = []
myList = firstBoard(rows, cols, myList)
newList = myList
print()
generations = int(input("How many iterations should I run? "))+1
for gens in range(generations):
printBoard(cols, rows, myList)
nextGen(cols, rows, myList, newList)
myList, newList = newList, myList
main()
And if for the both the rows and columns I enter five and If I fill 3,4 4,4 5,4 i get this:
# # # # # # #
# #
# #
# . #
# . #
# . #
# # # # # # #
# # # # # # #
# #
# #
# . #
# . #
# . #
# # # # # # #
# # # # # # #
# #
# #
# . #
# . #
# . #
# # # # # # #
# # # # # # #
# #
# #
# . #
# . #
# . #
# # # # # # #
when for the second and fourth boxes the dots should be horizontal instead of vertical. Please help i've been working on this all day and I can't figure it out.
The problem is with your array initialization:
newList = myList
This isn't making a copy of myList, it's just making newList refer to myList, so then you only have one array. You can copy a 2D array like this:
from copy import copy, deepcopy
newList = deepcopy(myList)