When calling an array only the first element is used? - python

When calling QuarterlySales into the DetermineRate procedure it only uses the first number in the array every time the loop goes around. I think I have it indexed properly. Also it only prints out 9 numbers when it should print out 10.
def FillQuarterlySales(QuarterlySales):
#declare local variables
Index = 0
QuarterlySales = [0] * 10
#Loading the array
QuarterlySales = [21487, 22450, 7814, 12458, 4325, 9247, 18125, 5878, 16875, 10985]
#Determine the quarterly sales based on the index
return QuarterlySales
def DetermineRate(QuarterlySales):
#declare local variables
Rate = float()
Index = 0
Counter = 0
Rates = [Index] * 9
for Index in range (9):
if QuarterlySales[Counter] < 5000:
Rate = 0
elif QuarterlySales[Counter] < 10000:
Rate = 0.04
elif QuarterlySales[Counter] < 15000:
Rate = 0.08
elif QuarterlySales[Counter] < 20000:
Rate = 0.12
else:
Rate = 0.15
#end if
Rates[Index] = Rate
#end for
return Rates
There is no error code but when I print out rates to make sure they are correct the array is filled with the same number. This is happening anywhere I call QuarterlySales throughout the program as well.

It's because you use Counter to index QuarterlySales instead of Index.
But your question shows some inexperience with python, so let's try to address some other issues, too.
Rates = [Index] * 9
...
QuarterlySales = [0] * 10
This looks like you're trying to do allocation in advance, which is almost always unnecessary in python. Certainly for lists of only ten elements, it hurts more than it helps.
Instead do this:
Rates = []
...
QuarterlySales = []
and then just use the .append() method to add sequential data elements to the list.
For example:
def DetermineRate(QuarterlySales):
Rates = []
for sales in QuarterlySales:
if sales < 5000:
Rates.append(0.)
elif sales < 10000:
Rates.append(0.04)
elif sales < 15000:
Rates.append(0.08)
elif sales < 20000:
Rates.append(0.12)
else:
Rates.append(0.15)
return Rates

Related

is it possible to recheck an index in a list in the same loop again? python

What I'm trying to do is to make the loop goes to every index in the "investments" list then checks if it's equal to "aMoney" variable or not. if the statement is True then the same index of "investments" in "revenue" list data will be added to "totalMoney" variable and goes back again to do next.
My problem is that I want the loop to go back to the False statements to recheck if it's True again and add it to the "totalMoney" variable.
what's happening here is the loop will skip index[0] because 2040 >=/ 3000. but after many loops the condition will be True if we do it again with the new number.
note: Sorting won't work because index[] in first list must go with what same index[] in the second list, no changes.
here is my full code:
numOfProjects = int(7)
aMoney = int(2040)
investments = [3000,2040,3040,5000,3340,4000,7000]
revenue = [500,1000,300,450,2010,650,1500]
totalMoney = int()
totalMoney = aMoney
for j in range(len(investments)):
if(totalMoney >= investments[j]):
totalMoney += revenue[j]
investments[j] + 1
revenue[j] + 1
totalMoney -= aMoney
print("The profit is $", totalMoney)
the output of this code will be $3960
in papers, it should be $4910
because, first round should be
"2040 + 1000 + 300 + 2010 + 650" = 6000
then we go back at what we left
"6000 + 500 + 450" = 6950
6950 - 2040 = 4910
I tried my best explaining the idea, hope it's clear
In python, we don't need to initialise int variables as int(number), just declaring them with the corresponding value suffices. So instead of aMoney = int(2040), just aMoney = 2040 works.
You can use zip to sort the investments and revenue together. Here's a simplified code which does what you need -
initialMoney, currentMoney = 2040, 2040
investments = [3000,2040,3040,5000,3340,4000,7000]
revenue = [500,1000,300,450,2010,650,1500]
data = sorted(zip(investments, revenue))
print(data)
for investment, revenue in data:
if investment <= currentMoney:
currentMoney += revenue
netProfit = currentMoney - initialMoney
print("The profit is $", netProfit)
Output:
[(2040, 1000), (3000, 500), (3040, 300), (3340, 2010), (4000, 650), (5000, 450), (7000, 1500)]
The profit is $ 4910
What you see printed just before profit, is the (investment, revenue) sorted by investment.

Count the dice throws to get to file 5 100 times(board is 0-5)

I'm trying to find out how many times you have to throw the dice to get on file 5 100 times(board is played from 0 to 5). This is how I tried(I know the answer is 690 but I don't know what I'm doing wrong).
from random import *
seed(8)
five = 0
count = 0
add = 0
while five < 100:
count = count + 1
print(randint(1,6))
add = add + randint(1,6)
if add % 5 == 0 :
five = five + 1
else: add = add + randint(1,6)
print(count)
This is the code I think you were trying to write. This does average about 600. Is it possible your "answer" came from Python 2? The random seed algorithm is quite likely different.
from random import *
seed(8)
five = 0
count = 0
add = 0
while five < 100:
count += 1
r = randint(0,5)
if r == 5:
five += 1
else:
add += r
print(count, add)
You're adding a second dice throw every time you don't get on 5, this makes the probability distribution irregular (i.e. advancing by 7 will be more probable (1/6) than any other value, e.g. 1/9 for 5) so your result will not be the same as counting single throws.
BTW there is no fixed result for this, just a higher probability around a given number of throws. However, given that you seeded the random number generator with a constant, every run should give the same result. And it should be the right one if you don't double throw the dice.
Here is an example of the process that arrives at 690:
import random
random.seed(8)
fiveCount = 0
throwCount = 0
position = 0
while fiveCount < 100:
position = (position + random.randint(1,6)) % 6
throwCount += 1
fiveCount += position == 5
print(throwCount) # 690
Other observations:
Updating the position wraps around using modulo 6 (there are 6 positions from 0 to 5 inclusively)
Your check of add%5 == 0 does not reflect this. It should have been add%6 == 5 instead but it is always preferable to model the computation as close as possible to the real world process (so keep the position in the 0...5 range)

How can I improve the time complexity of this algorithm for finding the max stock price?

I am currently passing the sample tests and 2 of the other 10 cases so 4 out of 12. However, I don't make it through all of the data. I am getting a Terminated due to timeout error which means that my solution isn't fast enough.
def stockmax(prices):
total = 0
for index, price in enumerate(prices):
if index < len(prices) - 1:
section = max(prices[index+1:])
if prices[index] < section:
total += section - prices[index]
return total
I tried to do everything in only one loop. But how exactly can speed this type of question up. I also tried to cut some lines of the code but it is equally as inefficient.
def stockmax(prices):
total = 0
for index, price in enumerate(prices):
if index < len(prices) - 1 and prices[index] < max(prices[index+1:]):
total += max(prices[index+1:]) - prices[index]
return total
Though it passes the same amount of test cases.
I also tried to use heapq but it passes the same test cases and fails due to time.
def stockmax(prices):
total = 0
for index, price in enumerate(prices):
if index < len(prices) - 1:
section = heapq.nlargest(1,prices[index+1:])[0]
if prices[index] < section:
total += section - prices[index]
return total
https://www.hackerrank.com/challenges/stockmax/topics/dynamic-programming-basics
for details on the problem.
https://hr-testcases-us-east-1.s3.amazonaws.com/330/input09.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1538902058&Signature=3%2FnfZzPO8XKRNyGG0Yu9qJIptgk%3D&response-content-type=text%2Fplain
for a link of some test cases but will expire after a while.
Problem
Your algorithms have become so good at predicting the market that you now know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for the next number of days.
Each day, you can either buy one share of WOT, sell any number of shares of WOT that you own, or not make any transaction at all. What is the maximum profit you can obtain with an optimum trading strategy?
For example, if you know that prices for the next two days are prices = [1,2], you should buy one share day one, and sell it day two for a profit of 1. If they are instead prices = [2,1], no profit can be made so you don't buy or sell stock those days.
Function Description
Complete the stockmax function in the editor below. It must return an integer that represents the maximum profit achievable.
stockmax has the following parameter(s):
prices: an array of integers that represent predicted daily stock prices
Input Format
The first line contains the number of test cases t.
Each of the next t pairs of lines contain:
The first line contains an integer n, the number of predicted prices for WOT.
The next line contains n space-separated integers prices [i], each a predicted stock price for day i.
Constraints
1 <= t <= 10
1 <= n <= 50000
1 <= prices [i] <= 100000
Output Format
Output lines, each containing the maximum profit which can be obtained for the corresponding test case.
Sample Input
3
3
5 3 2
3
1 2 100
4
1 3 1 2
Sample Output
0
197
3
Explanation
For the first case, you cannot obtain any profit because the share price never rises.
For the second case, you can buy one share on the first two days and sell both of them on the third day.
For the third case, you can buy one share on day 1, sell one on day 2, buy one share on day 3, and sell one share on day 4.
Clearly, for any price we can buy, we would want to sell it at the highest price. Fortunately, we are given that highest price. So, iterating backwards, we know the highest future price seen at any point we visit in our travel "back in time."
Python code:
def stockmax(prices):
n = len(prices)
highest = prices[n - 1]
m = [0] * n
# Travel back in time,
# deciding whether to buy or not
for i in xrange(n - 2, -1, -1):
# The most profit buying stock at this point
# is what we may have made the next day
# (which is stored in m[i + 1])
# and what we could make if we bought today
m[i] = m[i + 1] + max(
# buy
highest - prices[i],
# don't buy
0
)
# Update the highest "future price"
highest = max(highest, prices[i])
return m[0]
If you can use Numpy, then something similar to the below should be rather quick (I believe it's the same idea as the answer from #גלעד ברקן).
import numpy as np
with open('.../input09.txt') as fd:
numtests = int(fd.readline().strip())
counter = 0
numvals = 0
vals = None
steps = None
for line in fd:
if (counter % 2 == 0) :
numvals = int(line.strip())
else:
vals = np.fromstring(line, dtype=int, sep=' ', count=numvals)
assert len(vals) == numvals
cum_max = np.maximum.accumulate(vals[::-1])
np.roll(cum_max, -1)
cum_max[len(cum_max) - 1] = 0
delta = (cum_max - vals)
print('#', counter + 1, 'sum:', np.sum(delta * (delta > 0)))
counter += 1
it runs almost instantly on tests from the input09.txt.
Here is my solution written in ruby.
The solution obtained perfect score.
def solution(a)
gain = 0
i = a.count - 1
min = false
mi = false
while i > 0
s = a.delete_at(i)
unless min
mi = a.index(a.min)
min = a[mi]
end
g = s - min
gain = g if g > gain
i -= 1
min = false if i == mi
end
gain
end

Copy float values from within lists of lists

I do apologize if I'm not looking in the right places, but I cannot for the life of me figure out how to get a value from say
list[[1,2,3][4,5,6.01]] , list[1][2] integrated into code as anything but a list.
import random
fruits = [
['mango',7],
['apple',4],
['kiwi',6],
['grape',12],
['pear',3]
]
#Finding Probability
def setup():
fsum = 0;
prob = 0;
i = 0
#Finding the sum
while i < len(fruits):
fsum += fruits[i][1]
i += 1
i = 0
#Calculating Probability
while i < len(fruits):
prob = [fruits[i][1] / fsum]
fruits[i].append(prob)
i += 1
print(fsum)
print(fruits)
setup()
def pick(x):
rand = random.random()
index = 0
while rand > 0:
#How do I get the value of the float in the list from the next line
#(fruits[index][2])
#to be stored in a variable that I can plug into this.
#rand = rand - (var)
index+=1
pick (fruits)
Any feedback would be greatly appreciated.
Your problem is this line:
prob = [fruits[i][1] / fsum]
You are defining prob to be a list with one value, just eliminate the unnecessary list, e.g.:
prob = fruits[i][1] / fsum
Then fruits[index][2] will be the probability.
You should consider replacing your while loops with for loops, e.g.:
while i < len(fruits):
fsum += fruits[i][1]
i += 1
i = 0
Is equivalent to:
for fruit in fruits:
fsum += fruit[1]
Which could be be accomplished with a generator expression:
fsum = sum(fruit[1] for fruit in fruits)
But if what you are looking to do is just pick the fruit based on the relative weights (fruits[i][1]) then there is an easier way to do this in Py3.6, without the setup(), e.g.:
def pick(fruits):
items, weights = zip(*fruits)
return random.choices(items, weights)[0]
Prior to Py3.6 you could do:
def pick(fruits):
return random.choice([f for fruit in fruits for f in [fruit[0]]*fruit[1]])
Just access the first item of the list/array, using the index access and the index 0:
var = fruits[index][2][0]

How can I average multiple outputs independently in python

PYTHON 3: Hi, so I have this piece of code
for money in range(0, 2501, 500):
print("{} Euro".format(money), end='')
throws = 0
d = trump.possession(board)
while False in d.values():
prevLoc = piece.location
piece.move(trump.throw())
throws += 1
if piece.location < prevLoc:
money += 200
if board.names[piece.location] in d and d[board.names[piece.location]] == False and money >= board.values[piece.location]:
money -= board.values[piece.location]
d[board.names[piece.location]] = True
return throws
and this code takes 0 money to start with, runs the code, looks for amount of throws required to buy the entire board, does the same with 500 starting money, 1000 and so forth
my question is, how can i take the average of the throws to buy the entire board for each starting value? the way my code is now it returns the amount of throws for all the starting values, but simulated once, so it may not be accurate.
I searched a lot, and tried some things but i had problems with this one because I want to like run it, say for example, 2000 times, and get the average for each starting value for the money.
anyone got any tips for this? been struggling on it for a while..
i tried making a for loop from 0 to 2000 and then inside of that another for loop that prints 0-2500 and then uses the code below in a function, appends the return value of throws into a list and sums it up and devides it by 2000, it did not turn out so good...
I'm going to assume this is in a function, due to the return statement. You need to collect outputs into a list and then average that at the end.
def calc_throws(simulations):
throw_list = []
average = lambda x: sum(x)/len(x)
for i, money in enumerate(range(0, 2501, 500)):
print("{} Euro".format(money), end='')
throw_list.append([money, []])
for _ in range(simulations):
throws = 0
d = trump.possession(board)
while False in d.values():
prevLoc = piece.location
piece.move(trump.throw())
throws += 1
if piece.location < prevLoc:
money += 200
if board.names[piece.location] in d and d[board.names[piece.location]] == False and money >= board.values[piece.location]:
money -= board.values[piece.location]
d[board.names[piece.location]] = True
throw_list[i][1].append(throws)
throw_list[i][1] = average(throw_list[i][1])
return throw_list
Rather than a single number, this returns a list of lists like #[[0,20],[500,15],...[2500,3]] (or whatever reasonable numbers are) which gives you the average for each amount of starting money.

Categories

Resources