I have to confirm that the nested loops have been implemented correctly
Furthermore, the questions says, "After filling the blanks in the code, run this check to see if your implementation works correctly." What do they mean when they say "After filling the blanks in the code?"
Here is the code I have so far:
for x in range(len(companies)):
print(companies[x])
for y in range(len(companies[x])):
print(str(len(companies[x][y])))
After running the code, the output produces this:
['Warner Bros. Pictures', '20th CenturyFox', 'Universal Pictures']
21
15
18
['Whole foods', 'Starbucks', 'Walmart']
11
9
7
However, the intended output is supposed to be:
['Google', 'Facebook', 'Apple']
6
8
5
['Warner Bros. Pictures', '20th CenturyFox', 'Universal Pictures']
21
15
18
['Whole foods', 'Starbucks', 'Walmart']
11
9
7
How do I rewrite my code to match the correct output?
do you know?
how many words do you know
See also questions close to this topic

How return length of array when using recursion?
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is nonnegative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.
I created this program using recursion and I want to return the length of the array. Do you know how to do it? I would like to keep (If it's possible) the same logic I wrote. Thanks in advance **
def count_bits(n): base = n count = [] base = n // 2 if base: if base % 2 ==1: count.append(base % 2) count += count_bits(base) else: count += count_bits(base) return count print(count_bits(1234)) # return the array and I want the length #print(len(count_bits(1234))) # I can not use this method

How to print percentage at the beginning of string?
I would like to create and print string variable with percentage at the beginning. I use python 3.7.3
For example, I code:
a = '% some characters %' print(a)
what I get: " some characters %"
what I expect: "% some characters %"
Can anyone help, please?

What does 'import ___ as ____" mean, followed by a line of "from _____ import ____"
What does:
import pandas as pd from chembl_webresource_client.new_client import new_client
Mean in:
'import' 'as' 'from', and secondly, why do we use import in the second line? Why do we use 'client.new client', and 'new client' as well?

FIND THE ATTACHED DATASET YOU NEED TO APPLY TWO ALGORITHMS
FIND THE ATTACHED DATASET. YOU NEED TO APPLY TWO ALGORITHMS I.E. RANDOM FOREST AND ANN(ARTIFICIAL NEURAL NETWORK). CREATE TWO SEPARATE MODELS AND MAKE PREDICTIONS. USE GINI INDEX AS SPLIT CRITERIA. YOU CAN MEASURE THE PERFORMANCE BY R2 (R SQUARE)

Get function to know when a worker has to leave his station due to insufficient workload
I have a data frame which contains the following information:
Date Shift Time Box TimeDelta 0 20210514 Shift 1 14:05:13 1 NaN 1 20210514 Shift 1 14:29:43 1 0.408333 2 20210514 Shift 1 14:34:43 1 0.083333 3 20210514 Shift 1 14:34:51 1 0.002222 4 20210514 Shift 1 14:36:08 1 0.021389 ... ... ... ... ... ... 44288 20210910 Shift 8 23:19:16 1 0.011111 44289 20210910 Shift 8 23:19:45 1 0.008056 44290 20210910 Shift 8 23:20:16 1 0.008611 44291 20210910 Shift 8 23:21:20 1 0.017778 44292 20210910 Shift 8 23:21:40 1 0.005556
TimeDelta is the difference between each time a box is received. If the worker has to wait more than 0.0028 hours, ie. TimeDelta >= 0.0028, until he receives the next box, the worker leaves the station and waits until 20 boxes have accumulated. ie. wait until the sum of the next df["Box"][i] add up to 20. If the time difference between boxes is not more than 0.0028 hours he keeps working. When 20 boxes have accumulated, the worker returns to the working station and keeps working. Again the worker waits for another box to come in with a time difference bigger than 0.0028, else he keeps working. This function is only applied for rows within the same day and work shift.
This is one of my many tryings:
groups = df.groupby(by=["Date", "Shift"]) for name, group in groups: df1 = group[["Box", "TimeDelta"]] df1.reset_index(inplace=True, drop=True) for rows in range(len(df1)): boxes = [] sum_of_boxes = sum(boxes) while sum_of_boxes < 20: if df1.iloc[rows]["TimeDelta"] >= 1/360: boxes.append(df1.iloc[rows]["Box"]) else: boxes.append(df1.iloc[rows]["Box"])
My goal is to create a list of the same length as the first DataFrame that says wether the worker is in the station working or out of the station waiting for the boxes to be accumulated.

How to load images from a folder into pandas with class name
I have a folder which comprises of different images like dell_01.png, hp_01.png, toshiba_01.png and would like to create a dataframe from it which would look like this:
If the file starts with hp, it should be assigned to class 1. If it starts with toshiba, it should be assigned to class 1. If it starts with dell, it should be assigned to class 2 as seen in the below expected dataframe output.
filename class hp_01.png 0 toshiba_01.png 1 dell_01.png 2

Nested whileloop not iterating through the column in Python
I am quite a noob in coding so I would appreciate any help. I have a time series data frame with seven columns: "gid" (index that goes from 1 to 387), "x", "y", "month", "year", "spei" and "drought". Each "gid" represents one specific coordinate (387), 190403 rows in total (I have 492 rows with gid = 1, 492 gid =2,... and so on until 387).
I need to get a column "drought" filled with values (0's and 1's) based on conditions on another column in my data frame:
 When values on spei column are less os equal to 1, then this should fill 1 in "drought", else the value should be 0.
 And, when "drought" value is 1, further values should be filled with 1 in "drought" column until the values from the spei column turn positive (so spei value >= 0). This should be done for each gid, without mixing, so as each one represent a different coordinate.
I tried doing this with a nested while loop, the problem is that it only fills the first 493 rows of the drought column of my data frame, and stops with the first gid == 2 row.
this is the code I am using:
spei = dataframe.spei.array; gid = dataframe.gid.array; month = 0; np.max(dataframe.gid); ids = 1; while ids <=np.max(dataframe.gid1): id_pos = np.where(gid==ids) data_temp = spei[id_pos] while month<=len(data_temp): drought_month_save=0 if spei[month]<=1 : dataframe.drought[month] = 1 spei2 = spei[month:len(data_temp)] drought_month = 0 while drought_month<=len(spei2): if spei2[drought_month]<0: dataframe.drought[month+drought_month] = 1 elif spei2[drought_month]>0: drought_month_save = drought_month drought_month=len(spei2) drought_month +=1 else: dataframe.drought[month]=0 month +=1 month = month + drought_month_save print('gid: ' + str(ids) + '  month: ' + str(month) + ' / 190403') month=0 ids +=1 print(str(ids))
I am stuck at this point and I do not know why it doesn't iterate throughout the whole gid column. I am doing something wrong for sure, any help would be appreciated.

Time complexity of linear search in a loop?
For I=1 to n For J=1 to n k = b[I] F = Linear_search(a,k) Print F J=J*2
What will be the time complexity of above algorithm? I thought it would be O(nlogn) but there is a linear search too in algorithm which has complexity O(n).So what will be the complexity O(nlogn) or O(n) or will it be O(n^2 logn)?

How to randomly pull rows in a groupby until x value is met, then iterate through multiple columns with different 'x' input for each column/group
How can I group a dataset by the 'year' column and then randomly pull from each group the sum of that matching year column is greater than the input value? I am using groupby to try and avoid pulling in the '0' values when taking a random sample
So if I was to use 2024 as an example. The input is 'input_24' and the value is 11. so randomly pull rows where 'year'=2024 until the sum of that column is grater than or equal to 11.
input_23 = 5 input_24 = 11 input_25 = 8 sum_23 = int() sum_24 = int() sum_25 = int() output_rows= [] data = { 'Year':['2023', '2023', '2023', '2024', '2024', '2024', '2025', '2025', '2025', '2025', '2026'], 'Name':['Item1','Item2','Item3','Item4','Item5','Item6','Item7','Item8','Item9','Item10','Item11'], '2022':[3,2,2,0,0,0,0,0,0,0,0], '2023':[10,5,6,2,1,0,0,0,0,0,0], '2024':[0,1,0,9,8,5,3,1,2,1,0], '2025':[0,0,0,0,0,0,7,6,11,7,2], '2026':[0,0,0,0,0,0,0,0,0,0,9] } df = pd.DataFrame(data)
I have tried a few different methods but am completely stuck on this. Currently I am trying to use groupby but I dont know how to cycle through each column and get it to use the next 'input_xx' value.
grouped = data.groupby(['year']) for name, group in grouped: for i in data.sample(frac=1).iterrows(): if (sum_23 + i[1]['FY23']) <= input_23: sum_23 += i[1]['FY23'] output_row.append(i[1]) if output_row['FY23'].sum() >= input_23: break
but using a loop similar to this I can only get it to pull a specific number of rows from every group including the '0' values, or own column at a time and then I have to duplicate the code for each column.
I also read that I could try a groupby lamda function but have not figured out how that would work.
df.groupby('year').apply(lambda x: x.sample(1)).reset_index(drop=True)
Does anyone have an idea or suggestion?

How to compute an injective/surjective map with minimum weight?
We are given an
m x n
matrixw
which represents the edge weights in a complete bipartite graphK_m,n
. We wish to find a map{1,...,m} > {1,...,n}
with minimal weight, which is injective or surjective. Choosing a map is equivalent to, for every vertexv
in{1,...,m}
, choosing exactly one edge incident tov
.
Let
m<=n
. An injective function with minimal weight can be found by searching for the perfect matching with minimal weight. In Python, this is implemented inscipy
:import numpy as np import scipy, scipy.optimize w=np.random.rand(5,10) print(scipy.optimize.linear_sum_assignment(w))
Let
m>=n
. How can a surjective function with minimal weight be found? I'm looking for a concrete implementation in Python. 
Binary search Implementation complexity
i want to share with you my impl for binary search algo
my idea is to check not just the mid element but first & last elements every time before we check the mid one, so if any of first or last have the value needed there is no need to loop and divide searching for mid anymore. i think this way take less execution time, is it true or not? and why (if not) ?
#include<bits/stdc++.h> using namespace std; main() { vector<int> v(100000); int n; sort(v.begin(),v.begin()+n); int first =0; int last= n1; int mid; int idx=1; int x; cin>>x; while(first<=last) { if(x==v[last]  x== v[first]) { idx=x==v[last]?last:first; break; } else { mid= first+(lastfirst)/2; if(v[mid]<x) first=mid+1; else if (v[mid]>x) last=mid1; else if (v[mid]==x) { idx=mid; break; } } } if(idx ==1) cout<<"NOT FOUND"; else cout<< idx; }
it will return the last occurrence of the element if the element is found in the first or last position

Implementing a trait for anything that implements a trait?
I want to implement the trait Add trait for anything that implements
Into<u64>
.I tried this,impl<T> Add<Into<T>> for Sequence { type Output = Self; fn add(self, rhs: T) > Self::Output { todo!(); } }
This gives me two errors,
doesn't have a size known at compiletime = help: the trait `Sized` is not implemented for `(dyn Into<T> + 'static)`
And,
`Into` cannot be made into an object = note: the trait cannot be made into an object because it requires `Self: Sized` = note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rustlang.org/reference/items/traits.html#objectsafety>
I've tried replacing that with,
impl<T> Add<dyn Into<T> + 'static + Sized> for Sequence {
But I'm still getting errors
doesn't have a size known at compiletime = help: the trait `Sized` is not implemented for `(dyn Into<T> + 'static)` note: required by a bound in `Add`
What's the right syntax here, I'm going down a rabbit hole?

Creating a push() function that will be used to add new items to the stack
The prompt further tells me to name the function push(). I already defined the function correctly, so that is out of the way. The prompt also tells me to take in two arguments: stack(the listbased stack you made) and new_item (the item that is about to be added to the stack). The function is not supposed to return anything, as stated in the prompt.
This was my attempt and I am trying to figure out my mistake:
stack = [] def push(stack, new_item): stack.append(item)
 Python: Functions and methods