data = input("Input:")
def parse_to_int(dat): # parse input data to int list
individuals = dat.split(" ")
num = []
for individual in individuals:
num.append((int)(individual))
return num
def get_Max_and_MaxIndex_MinIndex(num_list): # get maximul value, its index and minimum value
sign = 1
val = 0
max_val = 0
min_val = 0
max_ind = 0
count = 0
for num in num_list:
count += 1
val = val + sign * num
sign = -1 * sign
if (max_val < val):
max_val = val
max_ind = count
if (min_val > val):
min_val = val
return max_val, max_ind, min_val
def sub_sum(ind): # calculate subsum until ind
global num_input
global subsum
subsum = 0
for i in range(ind + 1):
subsum += num_input[i]
return subsum
def sub_sum_with_sign(ind): # calculate subsum with sign until ind
global num_input
global subsum_withsign
subsum_withsign = 0
sign = 1
for i in range(ind + 1):
subsum_withsign += sign * num_input[i]
sign = -1 * sign
return subsum_withsign
def fill_data(ind): # fill data for print in empty data
global print_data
global cur_x
global cur_y
if ind % 2 == 0:
str = '/'
dx = 1
dy = 1
else:
str = '\\'
dx = 1
dy = -1
for _ in range(num_input[ind]):
print_data[cur_y][cur_x] = str
cur_x += dx
cur_y += dy
if ind % 2 == 0:
cur_y -= 1
else:
cur_y += 1
return print_data
# main program
num_input = parse_to_int(data)
col_num = 0 # column count
for elem in num_input:
col_num += elem
max_min_num = get_Max_and_MaxIndex_MinIndex(num_input)
row_num = max_min_num[0] - max_min_num[2] # row count
start_num = 0
for i in range(max_min_num[1]):
start_num += num_input[i] # maximum height element number
subsum = 0
subsum_withsign = 0
cur_x = 0
cur_y = -1 * max_min_num[2]
# start output
print("Output:\n")
print(" " * start_num + "o" + " " * (col_num - start_num))
print(" " * (start_num - 1) + "/|\\" + " " * (col_num - start_num - 1))
print(" " * (start_num - 1) + "< >" + " " * (col_num - start_num - 1))
# prepare data for print
print_data = []
for i in range(row_num):
print_data.append([])
for j in range(col_num):
print_data[i].append(" ")
for ind in range(len(num_input)):
fill_data(ind)
# print data
for indr in range(row_num - 1, -1, -1):
print("".join(print_data[indr]))
The above code will give this Output
In this code, a graph is generated using python without using any libraries. The Highest tip of the graph is marked.
I want to mark the lowest tip of the graph as shown in the image below. I completely have no idea about this one. which values should be changed in order to mark the lowest tip in the generated graph?
I am a newbie to stackoverflow, please comment if you need more clarity with this..
How to mark the lowest tip here Please Help me with this
Related
I'm trying to create an algorithm that basically see the stocks list in the program (Not real stocks just the one inside program :D) and buy when stocks is at lowest and sell when it's at highest and tell me how much is the profit. Here is an example:
Here is my code:
from turtle import st
mxdiff = 0
buy = 0
sell = 0
a = [] # min array from left
b = [0] * len(st) # max array from right
d = [] # difference array
minleft = st[0]
maxright = st[len(st) - 1]
for i in range(0, len(st)):
if (st[i] < minleft):
minleft = st[i]
a.append(st[i])
else:
a.append(minleft)
for i in range(len(st) - 1, -1, -1):
if (st[i] > maxright):
maxright = st[i]
b[i] = st[i]
else:
b[i] = maxright
for i in range(0, len(st)):
d.append(b[i] - a[i])
mxdiff = max(d)
for i in range(0, len(st)):
if (d[i] == mxdiff and d[i + 1] == mxdiff):
buy = i
break
for i in range(len(st) - 1, -1, -1):
if (d[i] == mxdiff and d[i - 1] == mxdiff):
sell = i
break
print("stocks has to be bought on day ")
print(buy + 1)
print("stocks has to be sold on day ")
print(sell + 1)
.st() (.showturtle) is a function of the turtle module. Use some other variable and try.
what‘s the problem with my code and how can I fix it.
The problems are in lines:
world[r].append(element)
world = createWorld()
world = createWorld()
Now I show all of the code, but it seems too long need more text to make it available to post, so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.
This was the error given:
IndexError: list index out of range
There are more details in the code below, appreciate it if you can help:)
import random
SIZE = 4
EMPTY = " "
PERSON = "P"
PET = "T"
POOP = "O"
ERROR = "!"
CLEANED = "."
MAX_RANDOM = 10
def clean(world, endRow, endColumn):
print("Scooping the poop")
for r in range(SIZE):
for c in range(SIZE):
if world[r][c] == POOP:
world[r][c] = CLEANED
def count(world, endRow, endColumn):
print("Counting number of occurances of a character")
number = 0
element = input("Enter character: ")
for r in range(SIZE):
for c in range(SIZE):
if world[r][c] == element:
number += 1
return(element, number)
def createElement():
tempNum = random.randrange(MAX_RANDOM)+1
if ((tempNum >= 1) and (tempNum <= 5)):
tempElement = EMPTY
elif ((tempNum >= 6) and (tempNum <= 7)):
tempElement = PERSON
elif (tempNum == 8):
tempElement = PET
elif ((tempNum >= 9) and (tempNum <= 10)):
tempElement = POOP
else:
tempElement = ERROR
return(tempElement)
def createWorld():
world = []
r = 0
while (r < SIZE):
world.append([])
c = 0
while (c < SIZE):
element = createElement()
world[r].append(element)
c = c + 1
r = r + 1
return(world)
def display(world):
print("OUR WORLD")
print("========")
r = 0
while (r < SIZE):
c = 0
while (c < SIZE):
print(world[r][c], end="")
c = c + 1
print()
r = r + 1
print("========\n")
def getEndPoint():
endRow = int(input("Enter the row: "))
while not 0 <= endRow <= 3:
print("Invalid input. Row value should be in range 0-3")
endRow = int(input("Enter the row: "))
endColumn = int(input("Enter the column: "))
while not 0 <= endColumn <= 3:
print("Invalid input. Column value should be in range 0-3")
endColumn = int(input("Enter the column: "))
return (endRow, endColumn)
def start():
world = createWorld()
display(world)
endRow, endColumn = getEndPoint()
element, number = count(world, endRow, endColumn)
print("# occurances of %s=%d" % (element, number))
clean(world, endRow, endColumn)
display(world)
start()
You need to update the r value in the outer loop, currently it is being updated in the inner loop.
def createWorld():
world = []
r = 0
while (r < SIZE):
world.append([])
c = 0
while (c < SIZE):
element = createElement()
world[r].append(element)
c = c + 1
r = r + 1
return (world)
I tried the implementation given here for knapsack problem using Branch and Bound.
The solution seems fine but it doesn't give the final selected items to reach the optimal value.
Is there a way to get this by changing the following code minimally?
import sys
def bound(vw, v, w, idx):
if idx >= len(vw) or w > limit:
return -1
else:
while idx < len(vw) and w + vw[idx][1] <= limit:
v, w, idx = v + vw[idx][0], w + vw[idx][1], idx + 1
if idx < len(vw):
v += (limit - w) * vw[idx][0] / (vw[idx][1] * 1.0)
return v
def knapsack(vw, limit, curValue, curWeight, curIndex):
global maxValue
if bound(vw, curValue, curWeight, curIndex) >= maxValue:
if curWeight + vw[curIndex][1] <= limit:
maxValue = max(maxValue, curValue + vw[curIndex][0])
knapsack(vw, limit, curValue + vw[curIndex][0], curWeight + vw[curIndex][1], curIndex + 1)
if curIndex < len(vw) - 1:
knapsack(vw, limit, curValue, curWeight, curIndex + 1)
return maxValue
maxValue = 0
if __name__ == '__main__':
with open(sys.argv[1] if len(sys.argv) > 1 else sys.exit(1)) as f:
n, limit = map(int, f.readline().split())
vw = []
taken = n * [0]
for ln in f.readlines():
vl, wl = map(int, ln.split())
vw.append([vl, wl, vl / (wl * 1.0)])
print(knapsack(sorted(vw, key=lambda x: x[2], reverse=True), limit, 0, 0, 0))
print(taken)
Lets say we have an input file with following contents
4 11
8 4
15 8
4 3
10 5
I am expecting a result like the following
19
0 1 1 0
I wrote my own implementation which gives the above desired output but it's taking too long for large problems like this one
I reorganised the provided code a bit, and then added the logic to keep track of the optimal selection. As you want that selection to be a list of zeroes and ones, I used a bitmap for it (a big integer), and each item gets a bit assigned in that bitmap.
Here is how it would look:
from collections import namedtuple
Item = namedtuple("Item", "value, weight, bit")
def knapsack(items, limit):
maxValue = 0
bestTaken = 0
def bound(value, weight, index):
if index >= len(items) or weight > limit:
return -1
else:
item = items[index]
while weight + item.weight <= limit:
value, weight, index = value + item.value, weight + item.weight, index + 1
if index >= len(items):
return value
item = items[index]
else:
return value + (limit - weight) * item.value / item.weight
def recur(taken, value, weight, index):
nonlocal maxValue, bestTaken
if maxValue < value:
maxValue = value
bestTaken = taken
if index < len(items) and bound(value, weight, index) >= maxValue:
item = items[index]
if weight + item.weight <= limit:
recur(taken | item.bit, value + item.value, weight + item.weight, index + 1)
recur(taken, value, weight, index + 1)
# Add bit mask for each item:
items = [Item(*item, 1 << index) for index, item in enumerate(items)]
items.sort(key=lambda item: -item.value / item.weight)
recur(0, 0, 0, 0)
return maxValue, ('{:0{width}b}').format(bestTaken, width=len(items))[::-1]
if __name__ == '__main__':
# Demo input
s = """4 11
8 4
15 8
4 3
10 5"""
lines = s.splitlines(False)
_, limit = map(int, lines.pop(0).split())
items = [tuple(map(int, line.split())) for line in lines]
value, bits = knapsack(items, limit)
print("Maximised value:", value)
print("Item selection:", bits)
I have two codes which should perform the same thing but in the first, I am not getting the result but in the second one I am getting output
if (Method == "EMM" ):
if ((Loan_Obligation/12)+EMI) !=0:
DSCR_Post = EBITDA_EMM/((Loan_Obligation/12)+EMI)
else:
0
elif (Method != "EMM" ):
if ((Loan_Obligation/12)+EMI) !=0:
DSCR_Post = EBITDA/((Loan_Obligation/12)+EMI)
else:
0
and other one is:
if (Method == "EMM"):
DSCR_Post = EBITDA_EMM/((Loan_Obligation/12)+EMI) if ((Loan_Obligation/12)+EMI) !=0 else 0
else:
DSCR_Post = EBITDA/((Loan_Obligation/12)+EMI) if ((Loan_Obligation/12)+EMI) !=0 else 0
print('DSCR_Post:',DSCR_Post)
Can someone help me what is the difference between the two codes
In your first code snippet, you are not assigning the 0 to DSCR_Post as you do in the second. Modify as follows:
if Method == "EMM" :
if (Loan_Obligation / 12) + EMI !=0:
DSCR_Post = EBITDA_EMM / ((Loan_Obligation / 12) + EMI)
else:
DSCR_Post = 0 # the 0 has to be assigned!
else: # you do not need a condition here! It can either be equal or not, no third state possible.
if (Loan_Obligation / 12) + EMI !=0:
DSCR_Post = EBITDA / ((Loan_Obligation / 12) + EMI)
else:
DSCR_Post = 0
print('DSCR_Post:',DSCR_Post)
Which can be simplified to the following:
ebid = EBITDA_EMM if Method == "EMM" else EBITDA
DSCR_Post = 0 # 0 will be overwritten if ...
if (Loan_Obligation / 12) + EMI != 0:
DSCR_Post = ebid / ((Loan_Obligation / 12) + EMI)
print('DSCR_Post:',DSCR_Post)
Below is what I have done but it Does not handle the max requirement on insert.
how do I Give the class a max value and check it in the insert and then remove the least significant element. Then figure out what is the least significant element in the implementation.
Having some issues trying to figure this out.
import math
import random
class BinaryHeap:
def __init__(self, array, direction=1, size=100):
if(size > len(array)):
self.size = len(array)
else:
self.size = size;
self.bBinaryHeap = array[:]
if 0 < direction:
self.compare = self.greater
else:
self.compare = self.less
self.buildBinaryHeap()
def node(self, index):
return (index << 1) + 1
def parent(self, index):
return (index - 1) >> 1
def bBinaryHeapifyDown(self, index):
swap = self.bBinaryHeap[index]
while self.node(index) < self.size:
node = self.node(index)
if node + 1 < self.size and self.compare(self.bBinaryHeap[node], self.bBinaryHeap[node + 1]) > 0:
node += 1
if self.compare(swap, self.bBinaryHeap[node]) > 0:
self.bBinaryHeap[index] = self.bBinaryHeap[node];
else:
break
index = node
self.bBinaryHeap[index] = swap
def upheapify(self, index):
while 0 < index and self.compare(self.bBinaryHeap[index], self.bBinaryHeap[self.parent(index)]) < 0:
parent = self.parent(index)
swap = self.bBinaryHeap[parent]
self.bBinaryHeap[parent] = self.bBinaryHeap[index]
self.bBinaryHeap[index] = swap
index = parent
def buildBinaryHeap(self):
indices = range(0, int(self.size / 2))
reversed(indices)
for index in indices:
self.bBinaryHeapifyDown(index)
def insert(self, value):
self.shrink()
index = self.size
self.bBinaryHeap[index] = value
self.size += 1
self.upheapify(index)
def search(self, value):
for index in range(self.size):
if self.bBinaryHeap[index] == value:
return index
def delete(self, value):
index = self.search(value)
self.size -= 1
self.bBinaryHeap[index] = self.bBinaryHeap[self.size]
parent = self.parent(index)
if (index == 0) or (self.compare(self.bBinaryHeap[parent], self.bBinaryHeap[index]) < 0):
self.bBinaryHeapifyDown(index)
else:
self.upheapify(index)
def shrink(self):
capacity = len(self.bBinaryHeap)
if capacity == self.size:
self.bBinaryHeap.extend([0] * capacity)
def greater(self, value1, value2):
if value1 == value2:
return 0
elif value1 < value2:
return 1
elif value1 > value2:
return -1
def less(self, value1, value2):
if value1 == value2:
return 0
elif value1 < value2:
return -1
elif value1 > value2:
return 1
def getLevel(self, index):
return int(math.floor(math.log(index + 1, 2)))
def displayBinaryHeap(self):
printBinaryHeap = str(self.bBinaryHeap)
height = self.getLevel(self.size)
previous = -1
for index in range(self.size):
getLevel = self.getLevel(index)
n = height - getLevel
indent = int(math.pow(2, n + 1) - 2)
spacing = 2 * indent
if getLevel != previous:
printBinaryHeap += '\n'
printBinaryHeap += ' ' * indent
previous = getLevel
else:
printBinaryHeap += ' ' * spacing
printBinaryHeap += '%4d' % self.bBinaryHeap[index]
print(printBinaryHeap)
if __name__ == "__main__":
size =10
array = [random.randint(0, 100) for i in range(size)]
bBinaryHeap = BinaryHeap(array, 1, 100)
print('Binary bBinaryHeap:')
bBinaryHeap.displayBinaryHeap()
Your code has numerous indentation errors. In python, indentation counts.
As for this code:
if 0 < direction:
self.compare = self.greater
else:
self.compare = self.less
self.greater and self.less don't exist. You are doing the equivalent of this:
x = elephant
That's nice, but unless you've set the variable elephant to some value prior to that line, that is an error.
how do I Give the class a max value
class BinaryHeap:
pass
BinaryHeap.max = 10
print(BinaryHeap.max)
--output:--
10
and check it in the insert
class BinaryHeap:
max = 10
def insert(self):
print(self.max)
bh = BinaryHeap()
bh.insert()
--output:--
10
then remove the least significant element
x = 0b1111
print(x) #15
y = x >> 1
print("{:b}".format(y)) #111
print(y) #7
Then figure out what is the least significant element in the implementation
x = 0b1110
print(x) #=>14
b_str = "{:b}".format(x)
print(repr(b_str)) #=> '1110'
for direction in [1, -1]:
if direction > 0:
least_signif = b_str[-1]
else:
least_signif = b_str[0]
print(least_signif)
--output:--
0
1