in python, I am trying to insert into a list recursively for a decimal to binary converter but the insert it is returning none
def dectob(num):
print(num)
if num==0:
return []
hnum = int(num/2)
if num - hnum == hnum:
asn="0"
else:
asn="1"
return dectob(hnum).insert(0,asn)
print(int(''.join(dectob(6666)))==1101000001010)
asn: answer
num: base ten number
hnum: integer of half of num
I tried everything I made this longer version so it prints all the data
def dectob(num):
print(num)
if num==0:
print("got")
blanklist=[]
print(blanklist)
return blanklist
hnum = int(num/2)
if num - hnum == hnum:
asn="0"
else:
asn="1"
ret= dectob(hnum)
print(ret)
print(asn)
return ret.insert(0,asn)
print(int(''.join(dectob(6666)))==1101000001010)
insert() modifies the list in place but does not return a value. Typically with functional programming you avoid side effects and treat most data structures as immutable, so insert() is probably the wrong choice here. Instead of mututaing the returned list, you can simply return the result of recursion along with the new value:
def dectob(num):
if num==0:
return []
hnum = int(num/2)
if num - hnum == hnum:
asn="0"
else:
asn="1"
return dectob(hnum) + [asn]
int(''.join(dectob(6666))) == 1101000001010
# True
Related
def isempty(qu):
if qu==[]:
return True
else:
return False
def push(qu,item):
qu.append(item)
if len(qu)==1:
front=rear=0
else:
rear=len(qu)-1
def pop(qu):
if isempty(qu):
return "underflow"
else:
item=qu.pop()[0]
if len(qu)==0:
front=rear=0
return item
def peek(qu):
if isempty(qu):
return "underflow"
else:
front=0
return qu[front]
def display(qu):
if isempty(qu):
print("Queue Empty")
else:
front=0
rear=len(qu)-1
print(qu[front],"<--- front")
for a in range(1,rear):
print(qu[a])
print(qu[rear],"<--- rear")
def summation():
def sum_arr(arr,size):
if (size == 0):
return 0
else:
return arr[size-1] + sum_arr(arr,size-1)
n=int(input("Enter number of elements in the queue for addition="))
queue=[]
for i in range(0,n):
queue.append(item)
print("The list is:")
print(queue)
print("sum of items :")
b=sum_arr(queue,n)
print(b)
queue=[]
for i in range(0,4):
print("----Queue Operations----")
print("1.Push/Enqueue")
print("2.Pop/Dequeue")
print("3.Peek")
print("4.Display Queue")
print("5.Exit")
print("6.Summation")
ch=int(input("Enter your choice="))
if ch==1:
item=int(input("Enter element="))
push(queue,item)
elif ch==2:
item=pop(queue)
if item=="underflow":
print("Queue Empty")
else :
print("Popped item=",item)
elif ch==3:
item=peek(queue)
if item=="underflow":
print("Queue Empty")
else:
print("Front most=",item)
elif ch==4:
display(queue)
elif ch==5:
break
elif ch==6:
summation()
else:
print("Invalid Choice")
this is the entire code which we are using here....
this actually for the implementation of queues using lists
it is compulsory to use queues method only here
Enter element=4
Enter element=5
Enter element=6
Enter the number of elements in the queue for addition=3
The list is:
[6, 6, 6]
the sum of items :
18
here the error is that the elements given are 4,5,6 but only the last element '6' is used for finding the sum thrice...
i hope i answered all the queries asked in the comments.....
any ideas with a little explanation are highly appreciated....
Zen of Python: Simple is better than complex
No matter what custom function you build, it will never be faster than a builtin.
l = [6,6,6]
total = sum(l)
print('The list is: {}'.format(l)
print('the sum of items : {}'.format(total))
If you must still need a custom function
def arr_sum(arr):
holder = 0
if len(arr) == 0:
return 0
else:
holder = [holder + i for i in arr if type(i) == int]
return holder
Can anyone explain this please?
def cube(number):
number = (number**3)
return number
def by_three(number):
if number % 3 == 0:
cube(number)
return number
else:
return False
by_three(3)
Oops, try again. by_three(3) returned 3 instead of 27
Why does this not return 27?
So the problem is that in your by_three function you are returning the parameter "number" passed into the by_three function and not returning the result of the cube function.
Your code:
def by_three(number):
if number % 3 == 0:
cube(number)
## problem is right here you should return cube(number) not number
return number
else:
return False
Fixed code.
def by_three(number):
if number % 3 == 0:
return cube(number) ## note the change here
else:
return False
Check you are not referring the returned value to variable number.The code will be like this.
def cube(number):
number = (number**3)
return number
def by_three(number):
if number % 3 == 0:
number=cube(number)
return number
else:
return False
print by_three(3)
Hope your problem is solved
For example, we have two functions:
def function1(num):
return num * 3
and second function
def function2(num):
if num%2 == 0:
print(num)
function1(num)
return num
If you call function(1), as expected it will return 1
If you call function(2), it will return 2 not 6. WHY?
Lets analyze this function2(2)
def function2(num): # num = 2
if num%2 == 0: # yes, it meets the condition
print(num)
function1(num) # it steps into function 1, this return num*3 == 6 however we do not know where it is saved (its address is unknown).
return num # this 'num' it is just the argument == 2
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.
So first, the assignment given was to make the function "compute" solves it and returns the value. If the given sting is not a valid equation, returns "None"
def compute(side):
val=int(side[0])
lastop=0
for i in range(1,len(side)):
if side[i].isdigit():
if lastop=='+':
val+=int(side[i])
elif lastop=='-':
val-=int(side[i])
elif lastop=='x':
val*=int(side[i])
elif lastop=='/':
val/=int(side[i])
else:
lastop=side[i]
return val
So at this point the value would be returned. But if the function is run for ("22-11x4"), it gives 0 not 44. I've turned them into integers and why would they still give me the wrong value?
def evaluate():
val=int(side[0])
lastop=0
for i in range(1,len(side)):
if side[i].true():
print('Congrats')
elif side[i].false():
print('Try again')
And when it gets to this evaluate function, it gives the error of "invalid literal for int() with base 10: '+'" and I am not too sure what this means and how to solve.
def solve():
pass
This function "solve" I was going to get to later after I have fixed the problems in the functions before.
def main():
print("22-11x4 =", compute("22-11x4"),"(expect 44)")
print("+11x4 =", compute("+11x4"),"(expect None)")
print("22-11x4 ?= 7x5+9", evaluate("22-11x4=7x5+9"),"(expect True)")
print("solving 288/24x6=18x13x8 :", solve("288/24x6=18x13x8"))
main()
The compute function you wrote does operation by digit, also you forgot to do one, last operation after for was finished:
2 - 1 - 1 x 4 = 0
this why you got this return from the function
Here is the correct function
def compute(side):
val = 0
buf = 0
lastop = '+'
for i in range(0, len(side)):
if side[i].isdigit():
buf = buf * 10 + int(side[i])
else:
val = op(val, buf, lastop)
lastop = side[i]
buf = 0
val = op(val, buf, lastop)
return val
def op(val, buf, lastop):
if lastop == '+':
val += buf
elif lastop == '-':
val -= buf
elif lastop == 'x':
val *= buf
elif lastop == '/':
val /= buf
return val
Also in your testing string:
print("+11x4 =", compute("+11x4"),"(expect None)")
why do you expect None? it should be 44?
PS. this function could be improved yet, but I had no time to do it. anyway it works.
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__()