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

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)

Related

show function approaches certain value [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
the following is my code for to solve this question :
wrote three functions to Show that as n increases (e.g. with a doubling experiment), from n = 2 to n = 1,000, the value of “day_sim(n)” approaches “sqrt(pi * n / 2)”.
"show that is approaching “sqrt(pi * n / 2)” -> but the graph doesn't look like it is approaching to such sqrt value at all...
Please help me with cracking this
import random
from random import randint
import numpy as np
def randomgen(n):
np.random.randint(low = 0, high = n)
return random.randint(0,n-1)
randomgen(100)
def day(n):
result = []
random = randomgen(n)
count =0
while random not in result:
result.append(random)
random = randomgen(n)
count += 1
return count
day(100)
def day(n):
result = []
random = randomgen(n)
count =0
while random not in result:
result.append(random)
random = randomgen(n)
count += 1
return count
def day_sim(n):
n_trails = 10000
for n in range(2,n_trails,50):
sq_rt = math.sqrt(math.pi*n/2)
day_sim = day(n)
print("n =",n,"Absolute difference=",abs(sq_rt - day_sim),"SQ value",sq_rt)
plt.scatter(n,day_sim, color='skyblue')
plt.scatter(n,sq_rt, color='red')
plt.xlim(0,10000)
plt.ylim(0,200)
day_sim(n_trails)
enter image description here
One way to do this would be to plot the variance as you progress:
variance = the (x - y^)**2/n
results = []
for n in range(2000):
y = day_sim(n)
x = (math.pi*n/2)**.5
variance = (x-y)**2/n
results.append((n, variance))
then plot the results and you should see the variance approach zero

How to create a list of numbers that go up and down 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 2 years ago.
Improve this question
I need to create a list in Python from a minimum and a maximum value. Half of the list needs to go up, and the other half needs to go down. Here's what I'm doing for now:
random_data = np.random.uniform(min_value, max_value, 6))
up_data = np.sort(random_data)
down_data = -np.sort(-random_data)
df = np.concatenate((up_data, down_data))
I create a list of 6 random numbers between a minimum and a maximum.
I sort them from down to up in a list.
I sort them from up to down in another list.
I put the two lists together.
It's working, but I don't like how it looks. I'm sure there must be a better way to do this but I just can't find anything. Thank you for your help!
Is it intentional that both sides have the same numbers ? If not, you should generate random numbers for the full size and concatenate ascending and descending sorts of half the values on each side:
import numpy as np
min_value = 75
max_value = 100
size = 12
random_data = np.random.uniform(min_value, max_value, size)
left_side = np.sort(random_data[::2])
right_side = np.sort(random_data[1::2])[::-1]
df = np.concatenate((left_side,right_side))
output:
print(df)
[84.35962408 84.86455724 84.86643652 85.95444697 86.97411648 95.55028286
97.6394171 94.16644573 94.05654689 92.12869314 88.52363283 80.19109841]
You could also do it "in-place" directly in the resulting array:
df = np.random.uniform(min_value, max_value, size)
df[:size//2].sort()
df[size//2:][::-1].sort()
In normal Python (i.e. not using the numpy module), you can take a similar approach:
import random
values = [random.randrange(min_value,max_value) for _ in range(size)]
values[:size//2] = sorted(values[:size//2])
values[size//2:] = sorted(values[size//2:],reverse=True)
print(values)
# [78, 79, 80, 80, 87, 93, 98, 92, 90, 86, 85, 81]
Not sure if you need this, but, here is the idea I suggested in comments:
import math
import random
size = 20
dec = 3
mx = 113
mn = 67
domain = sorted([random.uniform(0, math.pi) for _ in range(size)])
use_this = [round(fctr * math.sin(x), dec) for x in domain]
mx_l = max(use_this)
mn_l = min(use_this)
fctr = (mx - mn)/(mx_l - mn_l)
use_this = [round((fctr * (x - mn_l)) + mn, 0) for x in use_this]
print(use_this)
Note:
sin() is monotonically increasing between 0 and pi/2 and decreasing between pi/2 and pi
Used the logic at this SO answer

How to modify two inter-related lists simultaneously? [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 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

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

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