How to modify two inter-related lists simultaneously? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have two blank lists: intitialList and finalList and one initial value which is supposed to go into the initialList and a sample list sampleList = [12,3,1,4,25,3,2,22,12,32,34,2,1,5,7]. Now what I want to do is to write a program that will first insert initial values in the initialList then do some calculations and insert the value in finalList and then the first values of the finalList become the 2nd value of the initialList and again do some calculation and so on. Its kind of zigzag thing. Values are filling in zigzag way. My approach:
intialList = []
finalList = []
intialValue = 30
eff = 0.25
sampleList = [12,3,1,4,25,3,2,22,12,32,34,2,1,5,7]
for a in sampleList:
if a < 10:
intialList.append(intialValue)
finalList.append(intialValue + intialValue*eff)
else:
intialList.append(intialValue)
finalList.append(intialValue - intialValue*eff)
print("initial list:", intialList)
print("final list:", finalList)
I seriously don't know how to approach this.
desired output:
initial list: [30, 22.5, 28.125, 35.156, 43.954, 32.96, 24.72]
finalist list: [22.5, 28.125, 35.156, 43.945, 32.96, 24.72]
the results are stored in the finalList and first the initial value is stored at the index 0 of initialList after that the final result from the finalList is stored in the initialList.

according to your desired output you want to change the intalValue during sampleList iteration:
finalList = []
intialValue = 30
intialList = [intialValue]
eff = 0.25
sampleList = [12,3,1,4,25,3,2,22,12,32,34,2,1,5,7]
for a in sampleList:
if a < 10:
calculated_value = intialValue + intialValue * eff
else:
calculated_value = intialValue - intialValue * eff
intialValue = calculated_value
finalList.append(intialValue)
intialList.append(intialValue)
print(intialList)
print(finalList)
output:
[30, 22.5, 28.125, 35.15625, 43.9453125, 32.958984375, 41.19873046875, 51.4984130859375, 38.623809814453125, 28.967857360839844, 21.725893020629883, 16.294419765472412, 20.368024706840515, 25.460030883550644, 31.825038604438305, 39.78129825554788]
[22.5, 28.125, 35.15625, 43.9453125, 32.958984375, 41.19873046875, 51.4984130859375, 38.623809814453125, 28.967857360839844, 21.725893020629883, 16.294419765472412, 20.368024706840515, 25.460030883550644, 31.825038604438305, 39.78129825554788]

You could try this:
for a in sampleList:
if a < 10:
intialList.append(intialValue)
finalList.append(intialValue + intialValue*eff)
intialValue += initalValue*eff
else:
intialList.append(intialValue)
finalList.append(intialValue - intialValue*eff)
intialValue -= initalValue*eff

Related

Working with two Two-dimensional arrays in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
my_list = [['Chris',33,'JAN'],['Katia',40,'JAN'],['Petunia',54,'JAN'],['Clee',26,'JAN'],['katt',73,'JAN'],['battt',83,'JAN'],['FRIES',59,'FEB'],['GGEEZ',89,'FEB'],['SHEEESH',25,'MAR']]
threshold = [[217, 'JAN'], [104, 'FEB'], [18, 'MAR']]
output: [['Chris','Katia','Petunia','Clee','katt'],['FRIES','GGEEZ'],['SHEEESH']]
I want to make a new list with the first element in the nested array (the names) until the sum of the second elements in the nested array passes the 217 for JAN, 104 for FEB and 18 for MARCH.
I dont know how to do it since both of the lists are are indented and I find that hard to work with, But it should check it in a loop if my_list[2] == threshold[1] and sum the my_list[1]s until it is greater or equal to threshold[0] than it should go and check if the and check if my_list[2] == threshold[1] (but this time we skip the remaining januaries and check if the february is equal to the mylist and so on, its hard to articulate
Try:
my_list = [['Chris',33,'JAN'],['Katia',40,'JAN'],['Petunia',54,'JAN'],['Clee',26,'JAN'],['katt',73,'JAN'],['battt',83,'JAN'],['FRIES',59,'FEB'],['GGEEZ',89,'FEB'],['SHEEESH',25,'MAR']]
threshold = [[217, 'JAN'], [104, 'FEB'], [18, 'MAR']]
results = []
for max_num, month in threshold:
accumulator = []
count = 0
for s, num, month_ in my_list:
if month == month_ and count < max_num:
accumulator.append(s)
results.append(accumulator)
print(results)
output:
[['Chris', 'Katia', 'Petunia', 'Clee', 'katt', 'battt'], ['FRIES', 'GGEEZ'], ['SHEEESH']]
output = []
for a,b in threshold:
sum = 0
curr = []
for x,y,z in my_list:
if z == b and sum < a:
sum += y
curr.append(x)
output.append(curr)

Element-wise subtraction of two lists of numbers represented as strings [duplicate]

This question already has answers here:
Subtracting 2 lists in Python
(16 answers)
Closed 2 years ago.
I am trying to get the margin of two items in an array, the array consists of 4 float values each, and I want the first array item to be subtracted by the first array item in the second array, and so on for the rest of the array.
My current code looks like this:
buyPrice = [
'456.3',
'2346.5',
'123.5',
'43.5',
]
sellPrice = [
'426.3',
'1346.5',
'23.5',
'13.5',
]
total = 0
amount = 0
userInput = int(input("How much coins do you want to spend?: "))
for x in buyPrice:
while total <= userInput:
total += float(x)
amount += 1
for y in sellPrice:
k = float(x) - float(y)
print("Profit: " + str(k))
print("Total Cost: " + str("{:.1f}".format(total)))
print("Buy: " + str(amount))
print("----------")
amount = 0
total = 0
k = 0
And the MARGIN output is this:
Item 1: -382.8
Item 2: -1303,0
Item 3: 20
Item 4: 30.0
Output should be:
Item 1: 30
Item 2: 1000
Item 3: 100
Item 4: 30
I think my other code is interrupting this, as I am trying to get:
1. Total amount of items I can buy with the user Input (product price: 10k - userInput = 100k - total amount of items that can be bought: 10 - and so on)
2. The profit the user can make if they are selling the item for a higher price.
3. The total cost of buying all the products (total = buyprice + buyprice)
I could just be completely of right now, it is early in the morning, but I am completely lost.
EDIT: After some debugging on this I see that "X" never changed value, it kept being "426.3", most likely because of my for loop? How can I fix that?
Thanks
change your loop to this:
for x in range(len(buyPrice)):
k = float(buyPrice[x])- float(sellPrice[x])
your problem is you have for loop inside a for loop which cause to every array item in buyprice to be substracted with every array item in sellprice.
for example:
buyprice[0] will be substracted with sellprice[0],sellprice[1],sellprice[2] and sellprice[4], and so on..
The way I've understood the question:
You have 2 lists as input:
buyPrice = [
'456.3',
'2346.5',
'123.5',
'43.5',
]
sellPrice = [
'426.3',
'1346.5',
'23.5',
'13.5',
]
You want 1 list as output:
Item 1: 30
Item 2: 1000
Item 3: 100
Item 4: 30
You can do this in multiple ways. First, let's make the lists into lists of floats instead of strings:
buyPriceFloat = list(map(float, buyPrice))
sellPriceFloat = list(map(float, buyPrice))
Then you can subtract the second list from the first using:
difference = [sellPriceFloat[i] - buyPriceFloat[i] for i in range(len(sellPriceFloat))]
You can also use numpy arrays:
import numpy as np
buyPriceArray = np.array(buyPriceFloat)
sellPriceArray = np.array(sellPriceFloat)
difference = sellPriceArray - buyPriceArray

Loop the below way in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a column 'Distance' with value from 0 to n. I want to write a loop such that, if distance is above 0.5km it should say M1. When it is less than 0.5, it should be H1. When it crosses 0.5 again it should give M2.
My dataset:
Expected output:
How can i do this?
Here is an algorithm to get you started. Improve it to suit your needs
df = pd.read_csv("input.csv")
m_count = 0
h_count = 0
current = "H"
status_halt = []
for idx in df.index:
if df["Distance_km"][idx] < 0.5:
if current == "M":
h_count += 1
status_halt.append(f"H{h_count}")
current = "H"
elif df["Distance_km"][idx] > 0.5:
if current == "H":
m_count += 1
status_halt.append(f"M{m_count}")
current = "M"
df["Status_halt"] = status_halt

Returning wrong maximum sum sub array(kadane's algorithm), but correct maximum sum [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 7 years ago.
Given below is my code for the kadane's algorithm in Python 2.7 for returning the maximum sub array. Although, i'm getting the correct maximum sum(MSS variable) ,for the given example list,
it's returning the wrong sub array. Could someone please explain to me why ?
A = [-2,1,-3,4,-1,2,1,-5,4]
M = max(A)
L = len(A)
if(M < 0):
print M
ans = []
subans = []
MSS,subsum,i = 0,0,0
while(i<L):
subans.append(A[i])
subsum = sum(subans)
if(subsum<0):
subans=[]
i+=1
else:
if(subsum>MSS):
MSS=subsum
ans=subans
i+=1
else:
i+=1
print ans
Your issue is because when you do -
ans=subans
You are just storing the reference of subans to ans , when you change something within subans, the changes also reflect in ans (as they are the same reference).
You need to store a copy of subans in ans , instead of the direct reference.
Example -
ans = []
subans = []
MSS,subsum,i = 0,0,0
while(i<L):
subans.append(A[i])
subsum = sum(subans)
if(subsum<0):
subans=[]
i+=1
else:
print('subsum - ' + str(subsum))
print('MSS - ' + str(MSS))
if(subsum>MSS):
MSS=subsum
ans=list(subans) #more ways to do this, like subans[:] also works, and copy.copy(subans) , etc.
i+=1
else:
i+=1

reaching the goal number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am a beginner so if this question sounds stupid/unclear or very easy , please bear with me.
How can I add a list of numbers together in order to reach a target number or get as close as possible? For example, here is a list of numbers: (2,3,4,7,20,25), goal = 105. The result should be this: (25,25,25,25,3,2). The order of given numbers matters; always start with the biggest number in the list and add them up in order get close to the given value, so it will choose the next digit to test. the result could be also (20, 20, 20, 20, 25), which is not right in this case, because it doesn't follow the order of numbers. The algorithm only jump for the next number if it can feet otherwise can't jump.
Best M
l=(2,3,4,7,20,25)
goal = 105
a=max(l)
b=0
res=[]
while b<=goal-24:
b+=a
t=goal-b
res.append(a)
g=0
for x in l:
g+=x
if g==t:
res.append(x)
res.append(g-x)
break
print (res)
Output:
>>>
[25, 25, 25, 25, 3, 2]
>>>
I found this solution, however, really annoyed me :-)! Tricky part is while b<=goal-24: , other codes are basic Python.
I would take a dynamic-programming approach:
def fewest_items_closest_sum_with_repetition(items, goal):
"""
Given an array of items
where each item is 0 < item <= goal
and each item can be used 0 to many times
Find the highest achievable sum <= goal
Return any shortest (fewest items) sequence
which adds to that sum.
"""
assert goal >= 0, "Invalid goal"
# remove any duplicate or invalid items
items = set(item for item in items if 0 < item <= goal)
# sort descending (work with largest values first)
items = sorted(items, reverse=True)
# start with the no-item sequence
best = {0: []}
active = {0: []}
# while we have further seeds to work from
while active:
nactive = {}
for item in items:
for total, seq in active.items():
# find next achievable sum
ntotal = total + item
# if it is a valid subgoal and has not already been found
if (ntotal <= goal and ntotal not in best):
# save it
best[ntotal] = nactive[ntotal] = [item] + seq
if ntotal == goal:
# best possible solution has been found!
break
active = nactive
# return the best solution found
return best[max(best)]
which then runs like
>>> fewest_items_closest_sum_with_repetition([2,3,4,7,20,25], 105)
[25, 20, 20, 20, 20]
>>> fewest_items_closest_sum_with_repetition((40,79), 80)
[40, 40]
Is this right? I don't have time to test right now.
def solution(numbers, goal):
curr = 0
numbers = sorted(numbers)
while curr < goal:
if not numbers: break
n = numbers.pop()
while n + curr <= goal:
yield n
curr += n
list(solution([2,3,4,7,20,25], 105))
Results:
[25, 25, 25, 25, 4]
If speed is not an issue, here's an ultimately correct response:
import itertools
def change_maker(coins, amount):
for r in range(amount//max(coins), amount//min(coins)+1):
possibilities = (combo for combo in itertools.combinations_with_replacement(coins, r) if sum(combo) == amount)
try:
result = next(possibilities)
except StopIteration:
# no solution with current r
continue
else:
return result
This will always return the optimum result, but in some cases can calculate an ABSURD number of combinations to get there.
DEMO:
>>> coins = (2, 3, 4, 7, 20, 25)
>>> goals = 105
>>> print(change_maker(coins, goal))
[20, 20, 20, 20, 25]

Categories