interviews | Everything you need to know to get the job | Learning library
kandi X-RAY | interviews Summary
Support
Quality
Security
License
Reuse
- Decodes a string .
- Returns the minimal window .
- Get the vertical order of the node in the tree
- Generate matrix .
- Returns a list of integers .
- Returns the level order in the tree rooted at the tree
- Merge k lists .
- Group an array of Strings
- Determine how many substrings are unique
- Return the minimum cost of an array of costs .
interviews Key Features
interviews Examples and Code Snippets
Now why would we care?
expenses: Expense[]; ngOnInit() { this.getExpenses() .subscribe(expenses => { this.expenses = expenses; }); }
expenses: Expense[] = []; filter = "food"; ngOnInit() { this.getExpenses() .subscribe(expenses => { this.expenses = expenses.filter(e => e.type === this.filter); }); this.getFilter() .subscribe(filter => { this.filter = filter; this.expenses = this.expenses.filter(e => e.type === filter); }); }
expenses: Expense[] = []; ngOnInit() { this.getExpenses() .combineLatest(this.getFilter()) .subscribe(([expenses, filter]) => { this.expenses = expenses.filter(e => e.type === filter); }); }
expenses$: Observable; ngOnInit() { this.expenses$ = this.getExpenses() .combineLatest(this.getFilter()) .map(([expenses, filter]) => expenses.filter(e => e.type === filter)); }
import { switchMap } from 'rxjs/operators'; import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { Observable } from 'rxjs'; import { EmployeeService } from '../employee.service'; import { Employee} from '../employee; @Component({ selector: 'app-employee-detail', templateUrl: './employee-detail.component.html', styleUrls: ['./employee-detail.component.css'] }) export class EmployeeDetailComponent implements OnInit { employee$: Observable; constructor( private route: ActivatedRoute, private router: Router, private service: EmployeeService ) {} ngOnInit() { this.employee$ = this.route.paramMap.pipe( switchMap((params: ParamMap) => this.service.getEmployee(params.get('id'))) ); } } }
@Component({ selector: "async-pipe", template: ` AsyncPipe
{{ observable | async }}
{{ observable | async }}
(1) ` }) class AsyncPipeComponent { observable: Observable; constructor() { this.observable = this.getObservable(); } getObservable() { return Observable.interval(1000) .take(10) .map(v => v * v); } }
function performOperation(secondInteger, secondDecimal, secondString) { // Declare a variable named 'firstInteger' and initialize with integer value 4. const firstInteger = 4; // Declare a variable named 'firstDecimal' and initialize with floating-point value 4.0. const firstDecimal = 4.0; // Declare a variable named 'firstString' and initialize with the string "HackerRank". const firstString = 'HackerRank '; // Write code that uses console.log to print the sum of the 'firstInteger' and 'secondInteger' (converted to a Number type) on a new line. console.log(firstInteger + Number(secondInteger)); // Write code that uses console.log to print the sum of 'firstDecimal' and 'secondDecimal' (converted to a Number type) on a new line. console.log(firstDecimal + Number(secondDecimal)); // Write code that uses console.log to print the concatenation of 'firstString' and 'secondString' on a new line. The variable 'firstString' must be printed first. console.log(firstString + secondString); }
function reverseStringHalfIndex(str) { let strArr = str.split(''); let len = strArr.length; let halfIndex = Math.floor(len / 2) - 1; let tmp = []; for (var i = 0; i <= halfIndex; i++) { tmp = strArr[len - i - 1]; strArr[len - i - 1] = strArr[i]; // So for the first iteration I am doing str[len - 1] = str[0] strArr[i] = tmp; } return strArr.join(''); }
function inPlaceReverse(arr) { var i = 0; while (i < arr.length - 1 ) { arr.splice(i, 0, arr.pop()); i++; } return arr; }
Trending Discussions on interviews
Trending Discussions on interviews
QUESTION
I want to get 20 most common words from the descriptions of top 10 longest movies from data.csv, by using Python. So far, I got top 10 longest movies, however I am unable to get most common words from those specific movies, my code just gives most common words from whole data.csv itself. I tried Counter, Pandas, Numpy, Mathlib, but I have no idea how to make Python look exactly for most common words in the specific rows and column (description of movies) of the data table
My code:
import pandas as pd
import numpy as np
df = pd.read_csv("data.csv")
small_df = df[['title','duration_min','description']]
result_time = small_df.sort_values('duration_min', ascending=False)
print("TOP 10 LONGEST: ")
print(result_time.head(n=10))
most_common = pd.Series(' '.join(result_time['description']).lower().split()).value_counts()[:20]
print("20 Most common words from TOP 10 longest movies: ")
print(most_common)
My output:
TOP 10 LONGEST:
title duration_min description
6840 The School of Mischief 253.0 A high school teacher volunteers to transform ...
4482 No Longer kids 237.0 Hoping to prevent their father from skipping t...
3687 Lock Your Girls In 233.0 A widower believes he must marry off his three...
5100 Raya and Sakina 230.0 When robberies and murders targeting women swe...
5367 Sangam 228.0 Returning home from war after being assumed de...
3514 Lagaan 224.0 In 1890s India, an arrogant British commander ...
3190 Jodhaa Akbar 214.0 In 16th-century India, what begins as a strate...
6497 The Irishman 209.0 Hit man Frank Sheeran looks back at the secret...
3277 Kabhi Khushi Kabhie Gham 209.0 Years after his father disowns his adopted bro...
4476 No Direction Home: Bob Dylan 208.0 Featuring rare concert footage and interviews ...
20 Most common words from TOP 10 longest movies:
a 10134
the 7153
to 5653
and 5573
of 4691
in 3840
his 3005
with 1967
her 1803
an 1727
for 1558
on 1528
their 1468
when 1320
this 1240
from 1114
as 1050
is 988
by 894
after 865
dtype: int64
Here is the data table: https://www.dropbox.com/s/hxch4v08bkthvz1/data.csv?dl=1
ANSWER
Answered 2022-Mar-03 at 20:05You can select the first 10 rows of your dataframe with iloc[0:10]
.
In this case, the solution would look like this, with the least modification to your existing code:
import pandas as pd
import numpy as np
df = pd.read_csv("data.csv")
small_df = df[['title','duration_min','description']]
result_time = small_df.sort_values('duration_min', ascending=False)
print("TOP 10 LONGEST: ")
print(result_time.head(n=10))
most_common = pd.Series(' '.join(result_time.iloc[0:10]['description']).lower().split()).value_counts()[:20]
print("20 Most common words from TOP 10 longest movies: ")
print(most_common)
QUESTION
I am preparing for interviews and came across this question while practicing some SQL questions recently asked in Amazon. I could not find the table though, but the question is as follows:
Find the cumulative sum of the top 10 most profitable products of the last 6 months for customers in Seattle.
Does the approach to solving this type of query look correct? If not, what would be the best way to approach this problem?
SELECT t.day,
t.product_count,
@running_total:=@running_total + t.product_count AS cumulative_sum
FROM
( SELECT
date(purchase_date) as day,
count(product_id) as product_count
FROM products
where day > DATE_SUB(now(), INTERVAL 6 MONTH)
AND customer_city = 'Seattle'
GROUP BY day
ORDER BY product_count desc) t
JOIN (SELECT @running_total:=0) r
ORDER BY t.day
LIMIT 10;
ANSWER
Answered 2022-Feb-21 at 07:02use this
select day,product_count,
sum(product_count) over (order by t.day ROWS UNBOUNDED PRECEDING) as cumulative_sum from (
SELECT
date(purchase_date) as day,
count(product_id) as product_count
FROM products
where day > DATE_SUB(now(), INTERVAL 6 MONTH)
AND customer_city = 'Seattle'
GROUP BY day
ORDER BY product_count desc
)t
QUESTION
I have a css grid layout that looks like this,
When a box is clicked is grows in height to show information about the service. What I was hoping to be able to do was the "relayout" the grid so grid wrapped around the tallest item? Instead what I have is when I an item grows that row and it's children grow with it.
What I was hoping for was if report writing was clicked it would grow and take up benchmarking space, benchmarking would move left and consultancy would wrap onto a new line?
I am using tailwind so my HTML looks like this,
Report Writing
DBC can provide reports on any activity for organisations wishing to change any aspect of its operation or strategic direction. David has written consultancy reports for many countries on library and information transformation projects, various institutions seeking to gain taught degree awarding powers (TDAP), leadership and management benchmarking exercises and organisational training provision.
Notable recent examples include three reports written for for SCONUL to assess the strategic role of libraries and their leaders from the viewpoint of the universities’ senior management. This resulted in a publication for the commissioning body SCONUL to highlight the expectations of university leadership in the development of relevant library strategies. As a further phase of this work, Alison Allden and David Baker looked at the opportunities and transferable skills relating to international movement amongst library leaders.
David has been working with the University of London since March 2020 to develop a new strategy for Senate House Library, along with the School of Advanced Study, Federal Member Institute Libraries and the University of London Worldwide. The initial report was accepted by the University in September 2020. In the light of this, David has created a major Library Transformation Programme (LTP). The work involved in developing and operationalising the report included surveys, benchmarking, focus groups and workshops.
Mentoring
David has experience of mentoring professionals from different sectors and academics reaching back to 1990. He is currently heavily involved in mentoring for CILIP Chartership, Certification and Fellowship status (the UK’s library and information association). The focus is on developing and nurturing staff while learning new ideas and approaches from other professionals. Mentoring can be undertaken in person, by email, by telephone or through online platforms.
Workshops
DBC has a wealth of experience in delivering face-to-face and online workshops for a range of projects and purposes. These can be for the purpose of stakeholder engagement, data gathering or as part of a communications strategy. Workshops, interviews and focus groups are carried out consistently and coherently to give maximum value of data and information gathered. This is done through agreed pro forma and protocols.
Training
The DBC team can offer project management and change management training using previous live (anonymised) projects. A DBC Associate is PRINCE2 trained.
David Baker has delivered training in library management and information systems for senior leaders, library tecnhnicians and assistants for many countries of the world including, Slovenia, Ireland, Kuwait, Hungary, Germany and Portugal and has published several training guides, including on the subject of co-operative training in this area. He has also provided training and development for third world countries such as Ethiopia and Nigeria and has published a book on this.
Benchmarking
In 2022, DBC is undertaking a major international benchmarking exercise based on the Association of Commonwealth Universities (ACU) model. It is being led by David, Caroline (Librarian of the University of Queensland for academic and research libraries in the Australia and South Pacific region), Cliff and Lucy. The title is "Benchmarking Library, Information And Education Services: New Strategic Choices In Challenging Times". An Elsevier book publication bearing the same title will be published in early 2023. The benchmarking model can be adapted for any organisational purpose.
Research Services
DBC Associates worked in 2021 on a scoping study commissioned by Research Libraries UK (RLUK) and funded by the Arts and Humanities Research Council (AHRC). It resulted in a wealth of evidence of the role and potential of research libraries as partners and leaders of research, contributing to longer-term strategic development in the process. A range of research techniques were used for this and other consultancies such as surveys, benchmarking, focus groups and workshops. Two senior associates have research backgrounds and PhDs and the Director, Professor, has a substantial and significant track record in research and publishing.
Organisation Development
DBC has been developing strategic plans at organisational and pan-organisational levels for many years, not least through working in chief executive and governance roles as well as high-level consultancy work. We are accustomed to working with governing bodies, steering committees, task forces and other groupings to shape strategic direction and effect major organisational change as a result.
Our biographical details demonstrate that we have developed, written and implemented many strategic plans, including for the Higher Education Statistics Agency (HESA) and the Joint Information Systems Committee (Jisc), as well as contributing to strategy development for the Society of College, National and University Libraries (SCONUL) and Research Libraries UK (RLUK).
Consultancy
DBC delivers high-quality consultancy projects in higher education both nationally and internationally, with a long-standing track record, especially in strategy development. Associates have a broad and deep knowledge of the field.
Here is a codepen of my current solution
ANSWER
Answered 2022-Jan-21 at 17:51A couple of things.
You can make the clicked item span two rows by setting grid-row: span 2
This will have the effect of 'pushing' other grid items around.
In the JS you had a call to remove
which I think should have been removeClass
Here's a (slightly messy) SO snippet created from your codepen:
CodePen - A Pen by Simon Ainley
Report Writing
DBC can provide reports on any activity for organisations wishing to change any aspect of its operation or strategic direction. David Baker has written consultancy reports for many countries on library and information transformation projects, various
institutions seeking to gain taught degree awarding powers (TDAP), leadership and management benchmarking exercises and organisational training provision. Notable recent examples include three reports written for for SCONUL to assess the strategic
role of libraries and their leaders from the viewpoint of the universities’ senior management. This resulted in a publication for the commissioning body SCONUL to highlight the expectations of university leadership in the development of relevant
library strategies. As a further phase of this work, Alison Allden and David Baker looked at the opportunities and transferable skills relating to international movement amongst library leaders. David Baker has been working with the University
of London since March 2020 to develop a new strategy for Senate House Library, along with the School of Advanced Study, Federal Member Institute Libraries and the University of London Worldwide. The initial report was accepted by the University
in September 2020. In the light of this, David has created a major Library Transformation Programme (LTP). The work involved in developing and operationalising the report included surveys, benchmarking, focus groups and workshops.
Mentoring
Professor David Baker has experience of mentoring professionals from different sectors and academics reaching back to 1990. He is currently heavily involved in mentoring for CILIP Chartership, Certification and Fellowship status (the UK’s library
and information association). The focus is on developing and nurturing staff while learning new ideas and approaches from other professionals. Mentoring can be undertaken in person, by email, by telephone or through online platforms.
Workshops
DBC has a wealth of experience in delivering face-to-face and online workshops for a range of projects and purposes. These can be for the purpose of stakeholder engagement, data gathering or as part of a communications strategy. Workshops, interviews
and focus groups are carried out consistently and coherently to give maximum value of data and information gathered. This is done through agreed pro forma and protocols.
Training
The DBC team can offer project management and change management training using previous live (anonymised) projects. A DBC Associate is PRINCE2 trained. David Baker has delivered training in library management and information systems for senior leaders,
library tecnhnicians and assistants for many countries of the world including, Slovenia, Ireland, Kuwait, Hungary, Germany and Portugal and has published several training guides, including on the subject of co-operative training in this area.
He has also provided training and development for third world countries such as Ethiopia and Nigeria and has published a book on this.
Benchmarking
In 2022, DBC is undertaking a major international benchmarking exercise based on the Association of Commonwealth Universities (ACU) model. It is being led by David Baker, Caroline Williams (Librarian of the University of Queensland for academic
and research libraries in the Australia and South Pacific region), Cliff Wragg and Lucy Ellis. The title is "Benchmarking Library, Information And Education Services: New Strategic Choices In Challenging Times". An Elsevier book publication bearing
the same title will be published in early 2023. The benchmarking model can be adapted for any organisational purpose.
Research Services
DBC Associates worked in 2021 on a scoping study commissioned by Research Libraries UK (RLUK) and funded by the Arts and Humanities Research Council (AHRC). It resulted in a wealth of evidence of the role and potential of research libraries as partners
and leaders of research, contributing to longer-term strategic development in the process. A range of research techniques were used for this and other consultancies such as surveys, benchmarking, focus groups and workshops. Two senior associates
have research backgrounds and PhDs and the Director, Professor Baker, has a substantial and significant track record in research and publishing.
Organisation Development
DBC has been developing strategic plans at organisational and pan-organisational levels for many years, not least through working in chief executive and governance roles as well as high-level consultancy work. We are accustomed to working with governing
bodies, steering committees, task forces and other groupings to shape strategic direction and effect major organisational change as a result. Our biographical details demonstrate that we have developed, written and implemented many strategic plans,
including for the Higher Education Statistics Agency (HESA) and the Joint Information Systems Committee (Jisc), as well as contributing to strategy development for the Society of College, National and University Libraries (SCONUL) and Research
Libraries UK (RLUK).
Consultancy
DBC delivers high-quality consultancy projects in higher education both nationally and internationally, with a long-standing track record, especially in strategy development. Associates have a broad and deep knowledge of the field.
QUESTION
This question is an extension to this one (Is there a technical reason why it would be better for the COM DLL to delete the passed in temporary JSON when it is finished with it?) where it was suggested I pass JSON content as a BSTR
to my C# COM DLL.
Here is an example of the type of data being passed:
{
"BibleReading": "Bible Reading",
"BibleReadingMain": "Bible Reading (Main)",
"BibleReadingAux": "Bible Reading (Aux)",
"InitialCall": "Initial Call",
"InitialCallMain": "Initial Call (Main)",
"InitialCallAux": "Initial Call (Aux)",
"ReturnVisit": "Return Visit",
"ReturnVisitMain": "Return Visit (Main)",
"ReturnVisitAux": "Return Visit (Aux)",
"BibleStudy": "Bible Study",
"BibleStudyMain": "Bible Study (Main)",
"BibleStudyAux": "Bible Study (Aux)",
"Talk": "Talk",
"TalkMain": "Talk (Main)",
"TalkAux": "Talk (Aux)",
"Assistant": "Assistant",
"QuestionsAndAnswers": "Questions and Answers",
"DiscussionWithVideo": "Discussion with Video",
"SampleConversation": "Sample Conversation",
"InitialCallVideo": "Initial Call Video",
"ReturnVisitVideo": "Return Visit Video",
"Video": "Video",
"Presentations": "Prepare This Month’s Presentations",
"SpiritualGems": "Spiritual Gems",
}
I want to extent this JSON to include 15 more items:
{
"BibleReading": "Bible Reading",
"BibleReadingMain": "Bible Reading (Main)",
"BibleReadingAux": "Bible Reading (Aux)",
"InitialCall": "Initial Call",
"InitialCallMain": "Initial Call (Main)",
"InitialCallAux": "Initial Call (Aux)",
"ReturnVisit": "Return Visit",
"ReturnVisitMain": "Return Visit (Main)",
"ReturnVisitAux": "Return Visit (Aux)",
"BibleStudy": "Bible Study",
"BibleStudyMain": "Bible Study (Main)",
"BibleStudyAux": "Bible Study (Aux)",
"Talk": "Talk",
"TalkMain": "Talk (Main)",
"TalkAux": "Talk (Aux)",
"Assistant": "Assistant",
"QuestionsAndAnswers": "Questions and Answers",
"DiscussionWithVideo": "Discussion with Video",
"SampleConversation": "Sample Conversation",
"InitialCallVideo": "Initial Call Video",
"ReturnVisitVideo": "Return Visit Video",
"Video": "Video",
"Presentations": "Prepare This Month’s Presentations",
"SpiritualGems": "Spiritual Gems",
"Discuss": "Discussion",
"DiscussDemos": "Discussion with Demonstration(s)",
"DiscussDemosInterviews": "Discussion with Demonstration(s) and Interview(s)",
"DiscussInterviews": "Discussion with Interview(s)",
"DiscussVideo": "Discussion with Video",
"DiscussVideos": "Discussion with Videos",
"QuestionAnswer": "Questions and Answers",
"QuestionAnswerDemos": "Questions and Answers with Demonstration(s)",
"QuestionAnswerDemosInterviews": "Questions and Answers with Demonstration(s) and Interview(s)",
"QuestionAnswerInterviews": "Questions and Answers with Interview(s)",
"TalkDemos": "Talk with Demonstration(s)",
"TalkDemosInterviews": "Talk with Demonstration(s) and Interview(s)",
"TalkInterviews": "Talk with Interview(s)",
"TalkVideo": "Talk with Video",
"TalkVideos": "Talk with Videos"
}
Is it still going to be acceptable to pass this amount of information as a BSTR
to my COM API method? I assume there is some kind of limit as to how much data can be passed.
Thanks for confirming.
ANSWER
Answered 2022-Jan-21 at 05:06You could always write a test program if you don't know the answer. Here's one that verifies 1 megabyte BSTR
which is way more than your example. You could change the amount allocated to whatever you want. At some point it will break.
#include
#include
#include
#include
#include
using namespace std;
int main(int argc, char* argv)
{
const size_t MEGABYTEPLUSONE = 1024 * 1024 + 1;
auto pChar = std::make_unique(MEGABYTEPLUSONE);
for (size_t i = 0; i < MEGABYTEPLUSONE - 2; ++i)
pChar[i] = (i % 26) + 65;
pChar[MEGABYTEPLUSONE - 1] = 0;
_bstr_t bstr(pChar.get());
int len = bstr.length();
wcout << L"Length of BSTR: " << len << endl;
const WCHAR* const pwcStart = bstr.GetBSTR();
for (const WCHAR* pwc = pwcStart; pwc < pwcStart + 52; ++pwc)
wcout << *pwc;
wcout << endl;
return 0;
}
QUESTION
I came across a problem while doing technical interviews for matrix pattern matching. I was able to solve the problem using brute force but wonder if there is a more efficient solution as I only got about half credit for efficiency. Thank you in advanced for your input.
Given a matrix containing the numbers 0, 1, 2 and the pattern [1, 2, 0, 2, 0, 2, 0] find the max length of the matching pattern starting from any point in the matrix but can only travel diagonally.
here is an example of where we would expect the function to return 12.
here is where we would expect the function to return 7.
and empty matrix should return 0.
Here is my code, like I said previously it does work and passed all the tests but I got docked points.
def max_diagonal_match(matrix) -> int:
max_len = 0
pattern_match = [1, 2, 0, 2, 0, 2, 0]
for i in range(0, len(matrix)):
for j in range(0, len(matrix[i])):
max_len = max(
max_len,
find_i_minus_j_minus(matrix, i, j, pattern_match, 7),
find_i_minus_j_plus(matrix, i, j, pattern_match, 7),
find_i_plus_j_minus(matrix, i, j, pattern_match, 7),
find_i_plus_j_plus(matrix, i, j, pattern_match, 7)
)
return max_len
# i-, j-
def find_i_minus_j_minus(matrix, i, j, pattern, mod):
count = 0
while i >= 0 and j >= 0:
if matrix[i][j] != pattern[count % mod]:
return count
count += 1
i -= 1
j -= 1
return count
# i-, j+
def find_i_minus_j_plus(matrix, i, j, pattern, mod):
count = 0
while i >= 0 and j < len(matrix[i]):
if matrix[i][j] != pattern[count % mod]:
return count
count += 1
i -= 1
j += 1
return count
# i+, j-
def find_i_plus_j_minus(matrix, i, j, pattern, mod):
count = 0
while i < len(matrix) and j >= 0:
if matrix[i][j] != pattern[count % mod]:
return count
count += 1
i += 1
j -= 1
return count
# j+, i+
def find_i_plus_j_plus(matrix, i, j, pattern, mod):
count = 0
while i < len(matrix) and j < len(matrix[i]):
if matrix[i][j] != pattern[count % mod]:
return count
count += 1
i += 1
j += 1
return count
Many thanks for taking the time to read and any input is much appreciated.
ANSWER
Answered 2022-Jan-15 at 22:48Building on the accept answer to this question. It's based on a few key ideas:
You can use np.diagonal
over a range to slice every possible diagonal out of the array. You can flip the array around to make sure you get all angles.
You can tile
the pattern to make sure it's at least as long or longer than the largest diagonal.
You can zip
the diagonal and the pattern and the extra values in the pattern will be dropped automatically due to the way zip works.
Then you can use takewhile
on the zipped (diag,pattern) to check how many consecutive matches there are len(set(x))==1
.
If you do this for all the possible combinations and take the max, you should have your answer.
import numpy as np
from math import ceil
from itertools import takewhile
def max_sequence(arr):
solns = []
i = arr.shape[0]
for x in range(-i, i+1):
values = arr.diagonal(x)
N = len(values)
possibles = np.where(values == pattern[0])[0]
for p in possibles:
check = values[p:p+N]
m = len(list(takewhile(lambda x:len(set(x))==1, zip(pattern,check))))
solns.append(m)
return max(solns)
def find_longest(arr):
if len(arr)>0:
return max([max_sequence(x) for x in [arr, np.fliplr(arr), np.flipud(arr), arr[::-1]]])
else:
return 0
arr = np.array([
[1,0,2,1,1,1,1,0,0,0,0,0,0],
[1,2,2,1,1,1,1,0,0,0,0,0,0],
[1,0,0,1,1,1,1,0,0,0,0,0,0],
[1,0,0,2,1,1,1,0,0,0,0,0,0],
[1,0,0,2,0,1,1,0,0,0,0,0,0],
[1,0,0,1,1,2,1,0,0,0,0,0,0],
[1,0,0,1,1,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,2,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,2,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0],
])
arr1 = np.array([
[1,0,2,1,1,1,1],
[1,2,2,1,1,1,1],
[1,0,0,1,1,1,1],
[1,0,0,2,1,1,1],
[1,0,0,2,0,1,1],
[1,0,0,1,1,2,1],
[1,0,0,1,1,1,0]
])
arr2 = np.array([])
pattern = [1, 2, 0, 2, 0, 2, 0]
# Make sure pattern repeats longer than the max diagonal
pattern = np.tile(pattern,ceil(arr.shape[1] / len(pattern)))
for a in [arr, arr1, arr2]:
print(find_longest(a))
Output
12
7
0
QUESTION
I have this array that combines different data and then if the array contains true, then I'm showing some text. So for example, even if video is the only one that has a length greater than 0 (true), and the rest are false, the text 'Click to go to list' will be still shown. Is there a clean/simplier way of doing this check?
const relatedLists = [
videos.length > 0, // returns true or false
interviews.length > 0,
pdf.length > 0,
audio.length > 0,
book.length > 0,
];
Link={
relatedList.includes(true) ? 'Click to go to list' : ''
}
ANSWER
Answered 2021-Dec-23 at 20:38You can check to see if atleast one length property in the array is truthy
Link={relatedList.some(v => !!v.length) ? 'Click to go to list' : ''}
QUESTION
Below is a table that has candidate_id, two interviews they attended with the interviewer's name, and results for each interview.
candidate_id interview_1 interview_2 result_1 result_2 1 Interviewer_A Interviewer_B Pass Pass 2 Interviewer_C Interviewer_D Pass RejectI need help to combine column interview_1 and interview_2 into one column, and count how many pass and reject each interviewer gave to the candidate, the result I expected to see as below:
interviewer_name pass_count reject_count Interviewer_A 1 0 Interviewer_B 1 0 Interviewer_C 1 0 Interviewer_D 0 1SQL or Python either would work for me! Much appreciated!
ANSWER
Answered 2021-Dec-08 at 21:00In SQL Server, it becomes a small matter for a CROSS APPLY
Example
Select [candidate_id]
,B.[Interview_name]
,pass_count = case when result='Pass' then 1 else 0 end
,reject_count = case when result='Pass' then 0 else 1 end
From YourTable A
Cross Apply ( values ([interview_1],[result_1])
,([interview_2],[result_2])
) B(Interview_name,result)
Results
candidate_id Interview_name pass_count reject_count
1 Interviewer_A 1 0
1 Interviewer_B 1 0
2 Interviewer_C 1 0
2 Interviewer_D 0 1
QUESTION
I have transcriptions of interviews that are partly irregularly formed:
tst <- c("In: ja COOL; #00:04:24-6# ",
" in den vier, FÜNF wochen, #00:04:57-8# ",
"In: jah, #00:02:07-8# ",
"In: [ja; ] #00:03:25-5# [ja; ] #00:03:26-1#",
" also jA:h; #00:03:16-6# (1.1)",
"Bz: [E::hm; ] #00:03:51-4# (3.0) ",
"Bz: [mhmh, ]",
" in den bilLIE da war;")
What I need to do is structure this data by extracting its key elements into columns of a dataframe. There are four such key elements:
Role
in interview: interviewee or interviewerUtterance
: the interview partners' speechTimestamp
indicated by#
to both endsGap
indicated by decimal number in brackets
The problem is that both Timestamp
and Gap
are inconsistently provided. While I can make the last capture group for Gap
optional, those strings that have neither Timestamp
nor Gap
are not rendered correctly:
I'm using extract
from tidyr
for the extraction:
library(tidyr)
data.frame(tst) %>%
extract(col = tst,
into = c("Role", "Utterance", "Timestamp", "Gap"),
regex = "^(\\w{2}:\\s|\\s+)([\\S\\s]+?)\\s*#([^#]+)?#\\s*(\\([0-9.]+\\))?\\s*")
Role Utterance Timestamp Gap
1 In: ja COOL; 00:04:24-6
2 in den vier, FÜNF wochen, 00:04:57-8
3 In: jah, 00:02:07-8
4 In: [ja; ] 00:03:25-5
5 also jA:h; 00:03:16-6 (1.1)
6 Bz: [E::hm; ] 00:03:51-4 (3.0)
7
8
How can the regex be refined so that I get this desired output:
Role Utterance Timestamp Gap
1 In: ja COOL; 00:04:24-6
2 in den vier, FÜNF wochen, 00:04:57-8
3 In: jah, 00:02:07-8
4 In: [ja; ] 00:03:25-5
5 also jA:h; 00:03:16-6 (1.1)
6 Bz: [E::hm; ] 00:03:51-4 (3.0)
7 Bz: [mhmh, ]
8 in den bilLIE da war;
ANSWER
Answered 2021-Nov-27 at 13:41You could update your pattern to use your 4 capture groups, and make the last part optional by optionally matching the 3rd group and then the 4th group and assert the end of the string:
library(tidyr)
tst <- c("In: ja COOL; #00:04:24-6# ",
" in den vier, FÜNF wochen, #00:04:57-8# ",
"In: jah, #00:02:07-8# ",
"In: [ja; ] #00:03:25-5# [ja; ] #00:03:26-1#",
" also jA:h; #00:03:16-6# (1.1)",
"Bz: [E::hm; ] #00:03:51-4# (3.0) ",
"Bz: [mhmh, ]",
" in den bilLIE da war;")
data.frame(tst) %>%
extract(col = tst,
into = c("Role", "Utterance", "Timestamp", "Gap"),
regex = "^(\\w{2}:\\s|\\s+)([\\s\\S]*?)(?:\\s*#([^#]+)(?:#\\s*(\\([0-9.]+\\))?\\s*)?)?$")
Output
Role Utterance Timestamp Gap
1 In: ja COOL; 00:04:24-6
2 in den vier, FÜNF wochen, 00:04:57-8
3 In: jah, 00:02:07-8
4 In: [ja; ] #00:03:25-5# [ja; ] 00:03:26-1
5 also jA:h; 00:03:16-6 (1.1)
6 Bz: [E::hm; ] 00:03:51-4 (3.0)
7 Bz: [mhmh, ]
8 in den bilLIE da war;
QUESTION
Hello, (apologies for my bad English) I made the previous table I'm a new at SQL and wondering to how can I make a query that will return the names of the people who had interviews in different rooms regardless of the day so will would not come up since he had interviews in the same rooms
my approach
SELECT name
FROM worktable
DISTINCT room > 2
I don't' know what else to do thank you any help appreciated
ANSWER
Answered 2021-Nov-24 at 13:22In addition to @Beso answer I would also use DISTINCT in COUNT to be sure there are different rooms.
SELECT name
FROM worktable
GROUP BY name
HAVING COUNT(DISTINCT name) > 1
In this case only Sam will be included in the select output.
QUESTION
I'm trying to understand the time and space complexity of an algorithm for generating an array's permutations. Given a partially built permutation where k
out of n
elements are already selected, the algorithm selects element k+1
from the remaining n-k
elements and calls itself to select the remaining n-k-1
elements:
public static List> permutations(List A) {
List> result = new ArrayList<>();
permutations(A, 0, result);
return result;
}
public static void permutations(List A, int start, List> result) {
if(A.size()-1==start) {
result.add(new ArrayList<>(A));
return;
}
for (int i=start; i
My thoughts are that in each call we swap the collection's elements 2n
times, where n
is the number of elements to permute, and make n
recursive calls. So the running time seems to fit the recurrence relation T(n)=nT(n-1)+n=n[(n-1)T(n-2)+(n-1)]+n=...=n+n(n-1)+n(n-1)(n-2)+...+n!=n![1/(n-1)!+1/(n-2)!+...+1]=n!e
, hence the time complexity is O(n!)
and the space complexity is O(max(n!, n))
, where n!
is the total number of permutations and n
is the height of the recursion tree.
This problem is taken from the Elements of Programming Interviews book, and they're saying that the time complexity is O(n*n!)
because "The number of function calls C(n)=1+nC(n-1)
... [which solves to] O(n!)
... [and] ... we do O(n)
computation per call outside of the recursive calls".
Which time complexity is correct?
ANSWER
Answered 2021-Nov-14 at 15:07The time complexity of this algorithm, counted by the number of basic operations performed, is Θ(n * n!)
. Think about the size of the result
list when the algorithm terminates-- it contains n!
permutations, each of length n
, and we cannot create a list with n * n!
total elements in less than that amount of time. The space complexity is the same, since the recursion stack only ever has O(n)
calls at a time, so the size of the output list dominates the space complexity.
If you count only the number of recursive calls to permutations()
, the function is called O(n!)
times, although this is usually not what is meant by 'time complexity' without further specification. In other words, you can generate all permutations in O(n!)
time, as long as you don't read or write those permutations after they are generated.
The part where your derivation of run-time breaks down is in the definition of T(n). If you define T(n) as 'the run-time of permutations(A, start)
when the input, A, has length n
', then you can not define it recursively in terms of T(n-1) or any other function of T(), because the length of the input in all recursive calls is n
, the length of A.
A more useful way to define T(n) is by specifying it as the run-time of permutations(A', start)
, when A' is any permutation of a fixed, initial array A, and A.length - start == n. It's easy to write the recurrence relation here:
T(x) = x * T(x-1) + O(x) if x > 1
T(1) = A.length
This takes into account the fact that the last recursive call, T(1), has to perform O(A.length)
work to copy that array to the output, and this new recurrence gives the result from the textbook.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install interviews
You can use interviews like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the interviews component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page