how to get the sum of all the elements in here? - python

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

Related

Creating two list using three validation functions

Hello this is my first question and sorry I don't know how to phrase it,
I am trying to create a two list. The first list is for one set of codes (code1) and is validated in the VC function. The second function (VC) is to validate the second list. Both functions work well in validating the numbers. However in the third function (add_validations). In that function I want to repeat VC and VQ until the user either types in END or either of the functions return False. When true I want the inputs to be appended into the two separate lists. However, the third function not only does not append any of the list it does not identify/run either of the two functions and comes up with:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
And I'm sorry I didn't know which code to add so I added everything (delete if not allowed sorry):
Code:
def add_validations():
code1 = []
code2 = []
VC()
VQ()
while True:
record = []
i = VC()
q = VQ()
if i != "END":
VQ()
VC()
code1.append(int(i))
code2.append(int(q))
elif VC == True and VQ() == True:
VQ()
VC()
code1.append(int(i))
code2.append(int(q))
elif VC == False and VQ() == True:
print("Invalid code")
else:
print("Invalid quantity")
return code1,code2
def VC():
i = input("What is the item code \n")
minimum = 0
maximum = 39
if i == "END":
i = "END"
return showRecord()
elif int(i) > minimum and int(i) <= maximum:
return int(i)
True
else:
False
def VQ():
q = input("What quanity \n")
minimum = 0
maximum = 49
if q == "END":
isValidCode = "END"
return showRecord()
elif int(q) > minimum and int(q) <= maximum:
True
else:
False

Problem in coding with function in python: Base 2 & 10 integer palindrome

There was a question which asked to write a code, to get continuous integer input from user until a negative integer is input and for each input I should evaluate if it is a palindrome in both base 10 and 2. If yes then print 'Yes' else print 'No'.
For example: 99 = (1100011)base2, both versions are palindrome so it prints 'Yes'
This is a usual elementary method.
while 1:
num = int(input('Input: '))
if num > 0:
num1 = str(num)
if num1 == num1[::-1]:
list1 = list(bin(num))
list1.pop(0)
list1.pop(0)
n = ''.join(list1)
if n == n[::-1]:
print('Yes')
else:
print('No')
else:
print('No')
else:
break
But when I tried to type a code using defining a new function it didn't work well. Here following is the code. Can you note what is wrong with this.
def palindrome(n):
n = str(n)
if n == n[::-1]:
return True
else:
return False
def b2_palindrome(n):
list1 = list(bin(n))
list1.pop(0)
list1.pop(0)
n = ''.join(list1)
palindrome(n)
while 1:
num = int(input('Input: '))
if num > 0:
if b2_palindrome(num) and palindrome(num):
print('Yes')
else:
print('No')
else:
break
#dspencer: edited the indentations
you're not returning the value of the palindrome call in b2_palindrome
see below:
def b2_palindrome(n):
list1 = list(bin(n))
list1.pop(0)
list1.pop(0)
n = ''.join(list1)
return palindrome(n) # <-- added return here

Trying to make a maze

Hi I am learning Python from the week, and I got the idea to make maze in python. After a long time trying to do this, I always came to this starting point:
I would like to get the effect of what is on the 2 selection
My code:
def make(x):
if x%2 !=0:
return False
else:
table = []
for i in range(0,x):
if i == 0:
table.append([0]*x)
elif i == x-1:
table.append([0]*x)
return table
else:
if i == 1:
table.append([0])
table[i].extend([1]*(x-2))
table[i].extend([0])
elif i==x-2:
table.append([0])
table[i].extend([1]*(x-2))
table[i].extend([0])
else:
table.append([0]*(x))
for j in make(20):
print j
Try this. It's generic enough for any value of x that satisfies x%2==0:
def make(x):
if x%2 != 0:
return False
else:
table = []
for i in range(0,x):
if i>=x/2:
fac, rem = divmod(x-i-1,2)
else:
fac, rem = divmod(i,2)
table.append([0,1]*(fac+rem))
table[i].extend([rem]*(x-4*(fac+rem)))
table[i].extend([1,0]*(fac+rem))
return table
Probably better form to raise an exception instead of returning false but I don't know the larger context of what this fits into so I'll just leave it as is.
Or using the same approach as above you can split the single loop into two loops with a separate function like this:
def makeRow(x,fac,rem):
row=[0,1]*(fac+rem)
row.extend([rem]*(x-4*(fac+rem)))
row.extend([1,0]*(fac+rem))
return row
def make2(x):
if x%2 != 0:
return False
else:
table = []
for i in range(0,int(x/2)):
table.append(makeRow(x,*divmod(i,2)))
for i in range(int(x/2),x):
table.append(makeRow(x,*divmod(x-i-1,2)))
return table
Or if you prefer to turn the above into something more pythonic:
def make3(x):
if x%2 != 0:
return False
else:
table=[makeRow(x,*divmod(i,2)) for i in range(0,int(x/2))]
table.extend([makeRow(x,*divmod(x-i-1,2)) for i in range(int(x/2),x)])
return table
Why point out the error "table [i + j]. extend ([int (j% 2)] * (x-(4 * s))) IndexError: list index out of range" and whether in general has the right to work
def fun(x):
table=[]
s=0
for i in range(0,int(x/2)):
if i ==0:
table.append([0]*x)
else:
if i==((x/2)-1):
table.append([0,1]*(x/4))
table[i].extend([1,0]*(x/4))
elif i==(x/2):
table.append([0,1]*(x/4))
table[i].extend([1,0]*(x/4))
elif i == (x/2-1):
table.append([0]*x)
return table
else:
if i<(((x/2)/2)-2):
s+=1
for j in range(0,2):
table.append([0,1]*s)
table[i+j].extend([int(j%2)]*(x-(4*s)))
table[i+j].extend([1,0]*s)
if i>((x/2)/2):
for j in range(0,2):
if len(table) == (x-2):
break
else:
table.append([0,1]*s)
table[i+j].extend([int(j%2)]*(x-(4*s)))
table[i+j].extend([1,0]*s)
s-=1
for j in fun(20):
print j

Issue with Python Slot Machine

import random
balance = 50
def generator():
slot = 0
count = 0
gen = random.random()
while count < 3:
count = count + 1
if gen <= 0.01:
slot = 'Cherry'
elif gen <= 0.06:
slot = 'Diamond'
elif gen <= 0.16:
slot = 'Heart'
elif gen <= 0.36:
slot = 'Spade'
elif gen <= 0.66:
slot = 'Club'
elif gen <= 1:
slot = 'Monkey'
else:
break
return slot
def win(generator):
if generator() == 'Monkey' and generator() == 'Monkey' and generator() == 'Monkey':
balance = balance + 2122
print "Welcome to the International Slot Machine"
print ""
print "Balance: $",balance
print ''
spinyn = (raw_input("Would you like to spin? $5 per spin. Enter y or n:\n"))
while True:
if spinyn == "y":
break
elif spinyn == "n":
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spinyn = raw_input('\033[31mPlease enter only y or n.\033[0m\n')
spin = (raw_input("Press enter to spin for $5:\n"))
while True:
if spin == '':
balance = balance - 5
if balance <= 0:
print ""
print "Final Balance: $",balance
print "You have run out of money, the game has now ended."
raise SystemExit
print ""
print "\033[34mResult:\033[0m"
print "\033[34m-------\033[0m"
print generator()
print generator()
print generator()
print ""
print "New balance:$",balance
print ""
spinagain = (raw_input("Would you like to spin again? Press enter to spin again, type anything to exit.\n"))
while True:
if spinagain == "":
break
else:
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spin = (raw_input("Please press enter to spin.\n"))
I'm trying to make a very basic slot machine.
My question is: How do I make the generator function repeat 3 times and return 3 outputs, and then how do I make it recognise certain combinations?
Is this possible at all, keeping with my current format?
Also, how could I incorporate arrays into my code?
Thanks
Make the generator return a list or tuple of three values after generating three values, also it would be easier to use random.choice() rather than random.random() . random.choice() randomly selects a element for a list of values/iterable with equal probability for all elements. Example -
def generator():
ret = []
for _ in range(3):
ret.append(random.choice(['Cherry','Diamond','Heart','Spade','Club','Monkey']))
return tuple(ret)
If you want to have different probabilities for different elements, you can keep the current method, just loop over that three times and append to ret like done above and return ret from it.
Then in your win function, keep a dictionary such that the key is the tuple of combination and the value is the amount the user wins, then you can simply use .get() with a default value of 0 , to get how much the user won. Do not pass in generator as an argument. Example -
def win():
roll = generator()
d = {('Monkey','Monkey','Monkey'):21222,...}
return d.get(roll,0)
Then in your main loop, call this win() function to roll and see how much the user won.
Use the range function to choose 3 times and store it in a list.
import random
choices_list=[]
for ctr in range(3):
gen = random.choice(['Cherry', 'Diamond', 'Heart',
'Spade', 'Club', 'Monkey'])
choices_list.append(gen)
print choices_list

Inteviewstreet Median in python. Fails on all but the first test case

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__()

Categories