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 9 years ago.
Improve this question
I have question and a solution. But the solution doesnt seem to be satisfy all test cases :
Question:
variable N denotes the naming boundary(0,N-1)
variable K denotes the number of test cases
each test case is of format (x,y)...(a,b)
such that if (x,y) is given x,y belongs to same class
and if (x,y) and (y,z) is given x,y,z belongs to same class
The output should be number of possible ways of selecting 2 items from different class
Solution :
inp=raw_input()
inp1=inp.split(' ')
n=int(inp1[0])
k=int(inp1[1])
classes=[[]for i in xrange(0,n)]
no_classes=0
def in_list(c):
for i in range(0,no_classes):
if c in classes[i]:
return i;
return -1
for i in range(0,k):
inp=raw_input()
inp1=inp.split(' ')
c1=int(inp1[0])
c2=int(inp1[1])
l1=in_list(c1)
l2=in_list(c2)
if l1<0 and l2<0:
classes[no_classes].append(c1)
classes[no_classes].append(c2)
no_classes+=1
elif l1>=0 and l2<0:
classes[l1].append(c2)
elif l2>=0 and l1<0 :
classes[l2].append(c1)
elif l1>=0 and l2>=0 and l1!=l2:
classes[l1]=list(set(classes[l1]+classes[l2]))
del classes[l2]
no_classes-=1
tot_combntns=0;
for i in range(0,no_classes):
for j in range(i+1,no_classes):
tot_combntns=tot_combntns+len(classes[i])*len(classes[j])
print tot_combntns
Sample test case :
6 3
0 1
2 3
4 5
ans : 12
5 4
0 1
1 2
2 3
3 4
ans = 0 because there is only one class(0,1,2,3,4)
But I am not sure this solution satisfies all test cases
Because this is a practice programming challenge, I won't get you the answer. I will tell you enough to figure it out if you are competent. I'm leaving it at what I consider a reasonable difficulty level. If you're capable of creating objects, performing recursion, etc, then it should be straightforward. If you're not capable of that, then failing this programming challenge is a sign that you need to learn more basics.
If you have a group of n items, the number of ways of picking a pair from them is n*(n-1)/2. The number of ways of picking a pair from different classes is the number of ways of picking a pair minus, for each class, the number of ways of picking a pair from that class. The challenge is, therefore, to find the classes and count each one.
Figuring out that two elements are in the same class can involve many possible chains of reasoning. For instance the rules (a, b), (x,y), (b, y) imply that a and x are in the same class. How do you efficiently go through all possible reasoning chains? A simple and efficient method is to create an object that can take any element and map it to the smallest known member of its class. (Under the hood it suffices for it to map every element that is not minimal to a smaller known one, and lazily figure out the smallest known one on demand.)
Figuring out how to implement that object I leave as an exercise. As is, once you have it, figuring out how to count how many are in each class.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to work out the average sum of a list without index 0, is this possible in python? as you can see below, my list includes 1 name and 4 numbers. can I work out the average of the 4 numbers without including the name?
student = [Dan, 60, 70, 80, 90]
I have tried to achieve this in a number of different ways such as copying the list and removing index 0 however, this wasn't sufficient as I need this function to be looped a number of times inputted by the user previously.
I also tried to use the sum(student)/len(student) but that also gave an error as the list is a mix of int and str
Try excluding the first element, you can achive that with:
studentWithoutFirstElement = student[1:]
Then you can calculate the mean doing the following:
sum(studentWithoutFirstRow)/len(studentWithoutFirstRow)
You can also use the function provided by the numpy library by typing:
import numpy as np
np.mean(studentWithoutFirstRow)
You can use this code for general case not only for your case.
sum_ = 0
count = 0
for i in student:
if type(i) == int or type(i) == float:
sum_ += i
count += 1
avg = sum_/count
This code loop though list and check whether the type of element is int/float or not, if so adds it to sum and increase count by one. Finally you just divide sum to count.
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 6 years ago.
Improve this question
I had recently got the following question in an interview for a software position. As far as I can remember, it goes like : There are n houses at a stretch represented by an array A[1...n] containing their respective positions in sorted order.
For example, consider the array A[] = {1,3,5,10}. Each of the houses has a single gold coin, and you, being a thief, want to steal gold coins from k houses.
But there is a constraint: If I select k houses, then the difference in distance between any two of the selected houses must be more than k.
In the above example: If k = 3, then I can select houses with positions: 1,5,10. If k = 4, I cannot select 4 houses based on the above constraint.
I want to maximize k.
In the above example, k = 3 is the expected answer.
Currently, I have a brute force naive algorithm where for every value of k starting from 1, I check if that many number of house selections are possible. If possible, I increment kand do the same thing again.
Can you help me solve it more efficiently?
Idea: Binary search the value of k.
Let the array be sorted
low=1
high=min(n,sqrt(a[n] - a[1]))
while(low<=high)
mid = (low+high)/2
if( mid is a valid answer)
low=mid+1
else
high=mid-1
return high
Now to check if a given value of mid is a valid answer, you just use the greedy strategy:
Pick 1st house, then keep choosing next house which is at least mid distance away from last chosen house and if at the end, the number of robbed house are more then or equal to mid, then a valid theft is possible otherwise not.
Complexity: O(n log n)
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've been staring at an ACM programming problem for days and can't figure out why my solution in Python isn't accepted. It fails on "Test 28" and the computer does not tell you what the input for "Test 28" looks like. I left the question in the original wording--it is from some ACM website in Russia or China. This is the question:
A child receives a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description and the child is asked to choose the correct answer.
The child did not read his book beforehand and does not know the answer. Fortunately, he has devised a clever strategy. The child will follow this algorithm:
1. If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great.
2. If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice).
You are given a multiple-choice question, can you predict the child's choice?
Input:
The first line starts with "A." (without quotes), then followed by the description of choice A. The next three lines contain the descriptions of the other choices in the same format. They are given in the order B, C, D. Please note that the description goes after prefix "X.", so the prefix must not be counted in description's length.
Each description is non-empty and consists of at most 100 characters. Each character can be either uppercase English letter or lowercase English letter, or "_".
Output:
Print a single line with the child's choice: "A", "B", "C" or "D" (without quotes).
Sample Input:
Input
A.VFleaKing_is_the_author_of_this_problem
B.Picks_is_the_author_of_this_problem
C.Picking_is_the_author_of_this_problem
D.Ftiasch_is_cute
Output
D
Input
A.ab
B.abcde
C.ab
D.abc
Output
C
Input
A.c
B.cc
C.c
D.c
Output
B
My solution is here: http://ideone.com/FzXvvc
You don't seem to deal with the solution in which there is more than one good solution (larger = 3 and smaller = 3). In your case, minkey will be returned, not c. The problem requires c in that case.
Try:
if larger == 3:
if smaller == 3:
return "C"
else:
return minkey
elif smaller == 3:
return maxkey
else:
return "C"
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 8 years ago.
Improve this question
I am trying to randomly generate an array of integers of range between -10^7 to 10^7 such that there exists a sub-array with a sum of zero.
For example : 7 6 4 8 -4 -8
1<=Size of array<=10^5
I am able to do it using brute-force but it is taking a lot of time as I have to generate very big such arrays. Is there any efficient way of achieving this using python or c++?
Edit: Actually I want to generate a lot of such arrays with different scenarios. I am generating these arrays as testcases for a problem to determine whether any given array of positive and negative integers contain a sub-array with zero sum.
Tried brute force code:
import random
N = random.randint(10,100)
mylist = []
for i in xrange(1,N):
mylist.append(random.randint(-100,100))
list2 = [1,-1]
mylist = mylist[1:N-2] + list2 + mylist[N-2:N]
print mylist
So I have to manually tweak it a lot.
Thanks!
The answer depends on how random you want your array to be. Like some of the commenters mentioned, you can always include a zero and are thus guaranteed to have a subarray with sum of zero. I thought it would be helpful to your eventual solution, so I want to mention that you can check if an array has a subarray with sum of zero in O(N^2) time.
def array_has_zerosubarray( A ):
for _begin in xrange(0,len(A)-1):
for _end in xrange(_begin+1,len(A)):
sum = 0
for ai in range(_begin,_end):
sum = sum + A[ai]
if sum==0:
return True
return False
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have been asked the following:
Using a while-loop, write a program that generates a Fibonacci
sequence of integers. Your program should ask the user how many
Fibonacci sequence entries to generate and print this quantity of them
to the screen.
I don't know where to begin. Can someone point me in the right direction?
use a variable to hold last value and current value, print the current value, and then update the last value... don't want to write it for you :)
Let's think about this problem a little bit before just giving out the answer:
The fibonacci sequence is of the form
0 1 1 2 3 5 8 13 21 ...
So as you can see your next number is the sum of the previous two numbers so, based on its definition you can tell you need two variables to store the previous two numbers in and a variable to store the sum in. You also need to know when you need to terminate your loop (the number you get from the user).
Looks like someone has already posted it for you...never mind.
Every fibonacci number is generated as the sum of the previous two fibonacci numbers. The first two fibonacci numbers are 0 and 1.
Using the above as the definition, let's start designing your code:
function fibonnacci:
n := ask user how many numbers to output # hint: use raw_input() and int()
if n is 1:
output 0
else if n is 2:
output 0, 1
else:
output 0, 1
lastNumber := 1
twoNumbersAgo := 0
count up from 3 to n:
nextNumber := twoNumbersAgo + lastNumber
output nextNumber
twoNumbersAgo := lastNumber
lastNumber = nextNumber
end function