Delete all occurrence of an item using stack properties - stack

Use only the below stack methods to define a function (delx) to delete ALL occurrences of item x from a stack.
*keep the order of the remaining items in the stack unchanged
*can change original stack
*returns a stack
`
class Stack:
def __init__(self, iL=[]):
self.aList = iL[:]
def push(self, newElem:int):
"""push a new element on top"""
self.aList.append(newElem)
def pop(self)->int:
"""return top item"""
return self.aList.pop()
#property
def empty(self):
"""Is the stack empty?"""
return self.aList == []
def __repr__(self):
return repr(self.aList)
# use only the above stack methods to define a function to
# delete *ALL* occurrance of item x from a stack,
# keep the order of the remaining items in the stack unchanged
# can change orginal stack
# return a stack
def delx(sk:Stack, x:'item')-> Stack:
#Your Code Here
if __name__ == "__main__":
sk = [121,1,3423,423,6,1,'d',1,1,1,1,1,1,1,1,1,1,1,767]
x = 1
print("Original:")
print(sk)
print("After deleting x:")
print(delx(sk, x))
`
I tried this but it's returning weird.
`
def delx(sk:Stack, x:'item')-> Stack:
for i in range(len(sk)-1):
sk.pop(x)
return sk
`

Related

Ruby overriding array access operator

I have to set worksheet cell value on command ws['First Col'][1]= 255 for example.
I have tried this:
def [](*args)
return Column.new(self.find_column_index(args[0])) if args[0].is_a?(String) and args[1] != nil
return cell_name_to_row_col(args[0]) if args[0].is_a?(String) and args[1] == nil
(row, col) = parse_cell_args(args)
cells[[row, col]] || ''
end
class Column
def initialize(column)
#column = column
end
def []=(row, value)
self[row+1,#column] = value
self.save
end
end
It's not working.
In def [](*args), I have few ifs because for input ws['First Col'], it has to return all rows from first column, and for ws[1,2] it has to return second cell in first row for example.
I have also tried to tweak it a bit but I could not make it work.

Lua table overridden

This is supposed to be a simple backtracking function. The dest is a global table that is being properly edited in the function. The prev table is supposed to keep track of my previous positions as to not revisit them. However, my prev table always turns out empty. I'm a novice. If there is any other helpful information I will be happy to provide it. u
function GoTo(dest, prev)
-- base case
if dest[1] == position[1] and dest[2] == position[2] and dest[3] == position[3] then
return true
end
local prev = prev or {}
-- save destination as to not return here
prev[table.concat(position)] = true
-- create key for next move
local key = {0,0,0}
for i,v in ipairs(dest) do
if dest[i] ~= 0 then
key[i] = dest[i]/math.abs(dest[i])
end
end
-- attempt to move in optimal direction
for i,v in ipairs(key) do
if key[i] ~= 0 then
-- check if next move leads to a visited destination
position[i] = position[i] + v
local check = prev[table.concat(position)]
position[i] = position[i] - v
if not check then
if moveTo(i,v) then
if GoTo(dest, prev) then
return true
end
-- go back
if not moveTo(i, -v) then
error("cannot backtrack")
end
end
end
end
end
end
local prev = prev or {}
You create a local variable in your function and initialize it from a parameter with the same name that is being passed in, which hides all the changes inside the function and that's likely why you don't see any changes for that table. You need to initialize that table outside the function and pass its value in (and remove that local prev statement).

array.select not iterating through every element

I have a rails controller and this code only loop through the first element in the metrics array? Why is that?
# /metrics/:id
def values
#metric = metrics.select do |metric|
id = metric['href'].split('/').last
p "id == params[:id] = #{id == params[:id]}" # false on the first iteration (but never gets to the next iteration
return id == params[:id]
end
p "HERE?" # We never get here!
end
You need to remove the return statement from your method, Ruby uses implicit return (see https://jtrudell.github.io/blog/ruby_return_values/), so the result of a block is the last line that is evaluated in that block, the return statement in your code is treated as a return from the values method. Your method needs to look something like:
def values
#metric = metrics.select do |metric|
metric['href'].split('/').last == params[:id]
end
end

Wrong return value when calling a method

I need to Add a tractor_beam instance method that takes a string description of an item as a parameter (e.g., "cow"). When called, the method should disable the shield, add the item to the inventory along with the ship's current location if it isn't too heavy to pick up (see algorithm below), enable the shield again, and return true. If the item is too heavy to pick up, the method should skip the inventory update and return false.
Algorithm:
An item is too heavy to pick up if its letters add up to more than 500. using .ord (Not very scientific, i know.) For example, the letters of cow add up to 329, so our tractor beam can abduct a cow, no problem.
My problem is that it returns nil and an empty hash, how do i break down the item to add each together?
Code:
class Spaceship
attr_accessor :name, :location, :item, :inventory
attr_reader :max_speed
def initialize (name, max_speed, location)
puts "Initializing new Spaceship"
#name = name
#max_speed = max_speed
#location = location
#item = item
#inventory = {}
end
def disable_shield
puts "Shield is off!"
end
def enable_shield
puts "Shield is on!"
end
def warp_to(location)
puts "Traveling at #{max_speed} to #{location}!"
#location = location
end
def tractor_beam(item)
disable_shield
item = item.split('')
item.each do |let|
let.ord
let + let.next
end
return item
if item > 500
enable_shield
#inventory[#location] = item
return true
else
return false
end
end
end
Driver Code:
uss_enterprise = Spaceship.new("USS Enterprise","200,000 mph", "China")
hms_anfromeda = Spaceship.new("HMS Andromeda", "108,277 mph", "China")
uss_enterprise.disable_shield
hms_anfromeda.enable_shield
p hms_anfromeda.location
hms_anfromeda.warp_to("Namibia")
p hms_anfromeda.location
hms_anfromeda.tractor_beam("cow")
p hms_anfromeda.item
Terminal:
Initializing new Spaceship
Initializing new Spaceship
Shield is off!
Shield is on!
"China"
Traveling at 108,277 mph to Namibia!
"Namibia"
Shield is off!
nil
Firstly, you have a return statement before your if conditional, so the conditional will never be ran. Remove that.
Secondly, you get the weight of the item by using ord, but you aren't assigning the value to anything:
item.each do |let|
let.ord
let + let.next
end
return item
if item > 500
This should do the trick:
item = item.split('')
weight = 0
item.each do |let|
weight += let.ord # add the ord of this letter to the weight
end
if weight > 500 # weight is now the ord of each letter of item 'cow'
enable_shield
#inventory[#location] = item
return true
else
return false
end
This line return item in your tractor_beam method will get run every time before getting to your if statement I think that is causing the problem.
Also you are not using the instance variable #item that you are created in the initialize method I think you might actually want something like this:
def tractor_beam(item)
disable_shield
#item = item.split('')
weight = 0
#item.each do |let|
weight += let.ord
end
if weight < 500
enable_shield
#inventory[#location] = #item
return true
else
return false
end
end
end

Dynamic Image Table in Swift for iOS8

I am new to programming applications, although I have a rudimentary handle on it.
I would like to get user input for # of columns and # of rows, then create a table of images (identical) scaled to fit on the screen.
I would then like to be able to cycle through these and change their color one at a time.
I can program this in python (see below) but I have no idea how to do this graphically.
Thoughts?
print("Welcome to Well Tracker!")
r=input('number of rows? ')
while r.isdigit()!=True:
print('invalid try again')
r=input('number of rows? ')
r=int(r)
c=input('number of collumns? ')
while c.isdigit()!=True:
print('invalid try again')
c=input('number of rows? ')
c=int(c)
print('\nTap enter to cross of a well, \nenter anything else to end\n')
wellC=[0]*c
def showWell(well):
print('The Well')
for i in well:
print(i)
def fillNumbers(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j]=j+1
return matrix
def makeWell(rows, collumns):
i = 0
well=[]
while i<rows:
well+=[collumns[:]]
i+=1
well=fillNumbers(well)
return well
wellPlate=makeWell(r,wellC)
showWell(wellPlate)
def crossOff(well):
end='';
for col in range(len(well[0])):
row=0
while row < len(well):
end=input();
if end != '':
return False
well[row][col]='x'
row+=1
showWell(well)
def checkForX(well):
xs=0
for i in range(len(well)):
for j in range(len(well[i])):
if well[i][j] == 'x':
xs+=1
return xs
def main():
platesComplete=0
while True:
wellPlate=makeWell(r,wellC)
if crossOff(wellPlate) == False:
break
platesComplete+=1
wellsComplete=checkForX(wellPlate)+platesComplete*r*c
main()
Updated:
okay, my recommendation is to look to use a UICollectionView. Example here:
https://github.com/bluedome/DragToReorderCollectionView

Resources