I have this code that should break once it fulfills a certain condition, ie when the isuniquestring(listofchar) function returns True, but sometimes it doesn't do that and it goes into an infinite loop. I tried printing the condition to check if there's something wrong with the condition, but even when the condition is printed true the function still continues running, I have no idea why.
one of the strings that throws up an infinite loop is 'thisisazoothisisapanda', so when I do getunrepeatedlist('thisisazoothisisapanda'), it goes into an infinite loop.
would be really grateful if someone could help
thanks!
Here's my code:
def getunrepeatedlist(listofchar):
for ch in listofchar:
if isrepeatedcharacter(ch,listofchar):
listofindex = checkrepeatedcharacters(ch,listofchar)
listofchar = stripclosertoends(listofindex,listofchar)
print (listofchar)
print (isuniquestring(listofchar))
if isuniquestring(listofchar):
return listofchar
#print (listofchar)
else:
getunrepeatedlist(listofchar)
return listofchar
just for reference, these are the functions I called
def isrepeatedcharacter(ch,list):
if list.count(ch) == 1 or list.count(ch) == 0:
return False
else:
return True
def checkrepeatedcharacters(ch,list):
listofindex=[]
for indexofchar in range(len(list)):
if list[indexofchar] == ch:
listofindex.append(indexofchar)
return listofindex
def stripclosertoends(listofindices,listofchar):
stringlength = len(listofchar)-1
if listofindices[0] > (stringlength-listofindices[-1]):
newstring = listofchar[:listofindices[-1]]
elif listofindices[0] < (stringlength-listofindices[-1]):
newstring = listofchar[listofindices[0]+1:]
elif listofindices[0] == (stringlength-listofindices[-1]):
beginningcount = 0
endcount = 0
for index in range(listofindices[0]):
if isrepeatedcharacter(listofchar[index],listofchar):
beginningcount += 1
for index in range(listofindices[-1]+1,len(listofchar)):
if isrepeatedcharacter(listofchar[index],listofchar):
endcount += 1
if beginningcount < endcount:
newstring = listofchar[:listofindices[-1]]
else:
#print (listofindices[0])
newstring = listofchar[listofindices[0]+1:]
#print (newstring)
return newstring
def isuniquestring(list):
if len(list) == len(set(list)):
return True
else:
return False
It may be due to the fact that you are changing listofchar in your for loop. Try cloning that variable to a new name and use that variable for manipulations and return the new variable.
Related
I have this linear search where there is a list of words and a single word. the search checks whether the word is in the list or not. I keep on trying to pass my parameters to test the function but when i run the program nothing comes up. it would be great if you could look at this code and tell me where im going wrong.
def isin(alist, word):
found = False
length = len(alist)
pos = 0
while found == False and pos < length:
if alist[pos] == word:
found == True
else:
pos = pos + 1
return found
words = ["child","adult","cat","dog","whale"]
if isin(words, "dog"):
print("yes")
else:
print("no")
You are doing a lot extra works. Do it like this:
def isin(alist, word):
if word in alist:
return True
else:
return False
words = ["child","adult","cat","dog","whale"]
if isin(words, "dog"):
print("yes")
else:
print("no")
You have a problem with line found == True. It should be found = True.
def isin(alist, word):
found = False
length = len(alist)
pos = 0
while found == False and pos < length:
if alist[pos] == word:
found = True
else:
pos = pos + 1
return found
You could simplify the method to do the same task in one line as:
def isin(alist, word):
return True if word in alist else False
I am writing a file overlap function that takes two arguments: longestFile and shorterFile. I want to see if two files have the same numbers and if they do, it will append that number to an empty list.
These are the two lists I am using for the program:
The first file that I am using to compare and The second file that I use
def longestFile(firstFile, secondFile):
if len(firstFile)>len(secondFile):
return firstFile
else:
return secondFile
def shortestFile(firstFile, secondFile):
if len (firstFile) < len(secondFile):
return firstFile
else:
return secondFile
def middleNumber(theLongestFile):
return theLongestFile[len(theLongestFile)//2]
def fileOverlap(lstFirstFile,lstSecondFile):
lstMatchingNums = []
lstLongerFile = longestFile(lstFirstFile,lstSecondFile)
lstShortestFile = shortestFile(lstFirstFile,lstSecondFile)
for eachLines in range(len(lstShortestFile)):
lstLongerFile = longestfile(lstFirstFile,lstSecondFile)
for eachLine in range(len(lstLongerFile)):
if lstShortestFile[eachLines] == middleNumber(lstLongerFile):
lstMatchingNums.append(lstShortestFile[eachLines])
break
elif lstShortestFile[eachLines] < middleNumber(lstLongerFile):
lstLongerFile = lstLongerFile[0:len(lstLongerFile)//2+1]
if len(lstLongerFile) <= 2 and lstLongerFile[0] == lstShortestFile[eachLines]:
lstMatchingNums.append(lstShortestFile[eachLines])
break
elif middleNumber(lstLongerFile) != lstShortestFile[eachLines] and len(lstLongerFile) <=2:
break
elif lstShortestFile[eachLines] > middleNumber(lstLongerFile):
lstLongerFile = lstLongerFile[len(lstLongerFile)//2:]
if len(lstLongerFile) <= 2 and lstLongerFile[0] == lstShortestFile[eachLines]:
lstMatchingNums.append(lstShortestFile[eachLines])
break
elif middleNumber(lstLongerFile) != lstShortestFile[eachLines] and len(lstLongerFile) <= 2:
break
return lstMatchingNums
lstHappyNums = open('happynumbs.txt','r')
lstReadingHappyLines = lstHappyNums.readlines()
lstHappyNums.close()
lstPrimeNumsFile = open('primenumbers.txt','r')
lstReadingPrimeLines = lstPrimeNumsFile.readlines()
lstPrimeNumsFile.close()
print(fileOverlap(lstReadingHappyLines,lstReadingPrimeLines))
If I was to run this program, it would give me an empty list and I am not sure why.
I want to use recursion here but my code is wrong. Help me where I'm wrong. It is only return True. I have to return recursive statement as well as the condition in which the function return False. Basically, I want to expand my code.
def mypalindrome(l):
if l==[] or len(l) == 1:
return(True)
else:
return(mypalindrome(l[1:-1]))
You seem to have most of it right. You just need to call the arguments properly and fix the return value. Additionally, you are missing the check that checks the first and the last character, here's an example:
string = "reallear"
def mypalindrome(string):
if len(string) <= 1:
return True
elif string[0] == string[-1]:
return mypalindrome(string[1:-1])
else:
return False
print mypalindrome(string)
Few ways to check word palindrome
def mypalindrome(l):
if len(l) < 2:
return True
if l[0] != l[-1]:
return False
return mypalindrome(l[1:-1])
or more elegant way
def mypalindrome(l):
return l == l[::-1]
def mypalindrome(l):
if l==[] or len(l) == 1:
return(True)
else:
return(mypalindrome(l[1:-1]) and l[0] == l[-1])
Currently, what I have is
ntries = 0
def test_guess(code,guess):
if guess == code:
return True
ntries += 1
else:
return False
blackpegs = 0
whitepegs = 0
code_remainder = ''
guess_remainder = ''
ntries += 1
for x, y in zip(code,guess):
if x==y:
blackpegs += 1
elif not x==y:
code_remainder += x
guess_remainder += y
for i in guess_remainder:
if code_remander.find(i) != -1: #if i is found in the remainder of the code
whitepegs += 1
code_remainder = code_remainder.replace(i, 'X', 1)
return code_remainder
return guess_remainder
return blackpegs
return whitepegs
Right below, I have
if test_guess(code,guess)==True:
print 'You won!"
elif test_guess(code,guess)==False:
print 'Not quite. You get',blackpegs,'black pegs,',whitepegs,'white pegs.'
blackpegs in my final print statement keeps coming up as undefined. Why is it not set to be equal to the blackpegs counter?
if guess == code:
return True
ntries += 1
if your guess == code, then return true, next step can't be executed!
You can only have one return statement.
return code_reminder
Causes the function to immediately exit. You will want to do something like
return code_remainder, guess_remainder, blackpegs, whitepegs
and then when you call the function, use:
code_remainder, guess_remainder, blackpegs, whitepegs = test_guess(code,guess)
General Tip:
Variables/references declared within a function only exist within that function. You will need to explicitly return those variables/references if you want to use them outside of the function. Of course there are also some exceptions to this rule, but it is best that you stick to this method for now.
blackpegs doesn't have a value unless the else statement is reached. i.e. if guess == code, blackpeg is not defined.
It needs to be set to zero before the if else statements or otherwise addressed prior to being called in the return statement.
So i wrote this code and it passes the first test case, and fails all the rest. However, I can't seem to find an input that breaks it. Maybe it's because I've been staring at the code too long, but i would appreciate any help.
The algorithm uses two priority queues for the smallest and largest halves of the current list. Here's the code:
#!/bin/python
import heapq
def fix(minset, maxset):
if len(maxset) > len(minset):
item = heapq.heappop(maxset)
heapq.heappush(minset, -item)
elif len(minset) > (len(maxset) + 1):
item = heapq.heappop(minset)
heapq.heappush(maxset, -item)
N = int(raw_input())
s = []
x = []
for i in range(0, N):
tmp = raw_input()
a, b = [xx for xx in tmp.split(' ')]
s.append(a)
x.append(int(b))
minset = []
maxset = []
for i in range(0, N):
wrong = False
if s[i] == "a":
if len(minset) == 0:
heapq.heappush(minset,-x[i])
else:
if x[i] > minset[0]:
heapq.heappush(maxset, x[i])
else:
heapq.heappush(minset, -x[i])
fix(minset, maxset)
elif s[i] == "r":
if -x[i] in minset:
minset.remove(-x[i])
heapq.heapify(minset)
elif x[i] in maxset:
maxset.remove(x[i])
heapq.heapify(maxset)
else:
wrong = True
fix(minset, maxset)
if len(minset) == 0 and len(maxset) == 0:
wrong = True
if wrong == False:
#Calculate median
if len(minset) > len(maxset):
item = - minset[0]
print int(item)
else:
item = ((-float(minset[0])) + float(maxset[0])) / 2
if item.is_integer():
print int(item)
continue
out = str(item)
out.rstrip('0')
print out
else:
print "Wrong!"
Your original was not so legible, so first I made it object-oriented:
MedianHeapq supports methods rebalance(), add(), remove(), size(), median(). We seriously want to hide the members minset,maxset from the client code, for all sorts of sensible reasons: prevent client from swapping them, modifying them etc. If client needs to see them you just write an accessor.
We also added a __str__() method which we will use to debug visually and make your life easier.
Also added legibility changes to avoid the indexing with [i] everywhere, rename s,x arrays to op,val, add prompts on the raw_input(), reject invalid ops at the input stage.
Your actual computation of the median confuses me (when do you want float and when integer? the rstrip('0') is a bit wack), so I rewrote it, change that if you want something else.
A discussion of the algorithm is here.
Now it is legible and self-contained. Also makes it testable.
You might be making sign errors in your code, I don't know, I'll look at that later.
Next we will want to automate it by writing some PyUnit testcases. doctest is also a possibility. TBC.
Ok I think I see a bug in the sloppiness about locating the median. Remember the minset and maxset can have a size mismatch of +/-1. So take more care about precisely where the median is located.
#!/bin/python
import heapq
class MedianHeapq(object):
def __init__(self):
self.minset = []
self.maxset = []
def rebalance(self):
size_imbalance = len(self.maxset) - len(self.minset)
if len(self.maxset) > len(self.minset):
#if size_imbalance > 0:
item = heapq.heappop(self.maxset)
heapq.heappush(self.minset, -item)
#elif size_imbalance < -1:
elif len(self.minset) > (len(self.maxset) + 1):
item = heapq.heappop(self.minset)
heapq.heappush(self.maxset, -item)
def add(self, value, verbose=False):
if len(self.minset) == 0:
heapq.heappush(self.minset,-value)
else:
if value > self.minset[0]:
heapq.heappush(self.maxset, value)
else:
heapq.heappush(self.minset, -value)
self.rebalance()
if verbose: print self.__str__()
return False
def remove(self,value,verbose=False):
wrong = False
if -value in self.minset:
minset.remove(-value)
heapq.heapify(self.minset)
elif value in maxset:
maxset.remove(value)
heapq.heapify(self.maxset)
else:
wrong = True
self.rebalance()
if verbose: print self.__str__()
return wrong
def size(self):
return len(self.minset)+len(self.maxset)
def median(self):
if len(self.minset) > len(self.maxset):
item = - self.minset[0]
return int(item)
else:
item = (-self.minset[0] + self.maxset[0]) / 2.0
# Can't understand the intent of your code here: int, string or float?
if item.is_integer():
return int(item)
# continue # intent???
else:
return item
# The intent of this vv seems to be round floats and return '%.1f' % item ??
#out = str(item)
#out.rstrip('0') # why can't you just int()? or // operator?
#return out
def __str__(self):
return 'Median: %s Minset:%s Maxset:%s' % (self.median(), self.minset,self.maxset)
# Read size and elements from stdin
N = int(raw_input('Size of heap? '))
op = []
val = []
while(len(val)<N):
tmp = raw_input('a/r value : ')
op_, val_ = tmp.split(' ')
if op_ not in ['a','r']: # reject invalid ops
print 'First argument (operation) must be a:Add or r:Remove! '
continue
op.append(op_)
val.append(int(val_))
mhq = MedianHeapq()
for op_,val_ in zip(op,val): # use zip to avoid indexing with [i] everywhere
wrong = False
if op_ == 'a':
wrong = mhq.add(val_)
elif op_ == 'r':
wrong = mhq.remove(val_)
assert (mhq.size()>0), 'Heap has zero size!'
assert (not wrong), 'Heap structure is wrong!'
if not wrong:
print mhq.__str__()