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"
Related
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 months ago.
Improve this question
I am within my first week of python coding. well, first week of coding ever. I am trying to do a random name generator. However, I want to have it that if certain letters are chosen, another letter is added
I have lists for the consonants and vowels:
import random
vowels = ["a","e","i","o","u","y"]
consonants = ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","z"]
first = (consonants[random.randint(0,19)])
second = (vowels[random.randint(0,5)])
third = (consonants[random.randint(0,19)])
...
(however many letters desired. might do more randomness up to x letters)
However, I wanted:
if first == "q":
first == "qu"
Let's say qezba was the name generated. I am trying to make conditions so that if a "q" is the first letter, it auto adds a "u" onto the string of the variable first. Or, if an "l" was the third letter, to add a "j" after it, half of the time
How could this be done?
You can.
if first == "q":
first = "qu"
Given your usecase, you can try:
if first == "q":
first = first + "u"
== is the equality operator ( whether a equal to b ). = is the assignment operator.
There are several ways to do it:
if first=="q":
first="qu"
if first=="q":
first+="u"
first = (consonants[random.randint(0,19)])+"u"
Provided you are just starting out I suggest trying to solve the question yourself before asking here. Good luck
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
Suppose I have a list of strings
['elvis','elo','eels','acdc']
Is there a function that accept this string and returns a unique character for each of the strings? For example, in this case, I expect to get
['e','l','s','a']
Edit: To clarify my meaning.
I want a function that will return an identifier character or string that is based on the input list members. jme answer and bonit's one are a good example.
I think I see your point. There is no built-in for this.
Correct me if I am wrong, but it seems like you want to take the first not already taken character in each string and take one only.
Here is some code to do that
def get_first_not_know(l):
chars = []
for word in l:
for letter in word:
if letter not in chars:
chars.append(letter)
break
return chars
If you don't care about order of letters you take, you can do something quicker using sets.
Assuming Benoît Latinier's interpretation of your question is right (which, it looks like it is), then there will be some cases where a unique letter can't be found, and in these cases you might throw an exception:
def unique_chars(words):
taken = set()
uniques = []
for word in words:
for char in word:
if char not in taken:
taken.add(char)
uniques.append(char)
break
else:
raise ValueError("There are no unique letters left!")
return uniques
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
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.
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 9 years ago.
Improve this question
I am a newbie on python. I have just create a program taking a 2's complement binary number and convert it to decimal value. (The way of conversion is described at http://sandbox.mc.edu/~bennet/cs110/tc/tctod.html.)
I am aware that there are some certain rules on how to format your program and some "good habits" on how to design your program. Like how you put a header, comment, etc. And how you design the structure of it. I could not find a guide on Internet so I decide to ask here.
This is my first time making post on stackoverflow, so please bear with me if I make any mistakes. : )
Here is my code.
def secBiToDecimal(number):
""" This program takes a 2's complement binary number as input and returns its decimal value
"""
output = ""
" Check the sign of this number and calculate its value in according way."
if number[0]=='0':
output += "+"
temp = 0
for i in range(1,len(number)):
temp += (int(number[i]) * (2**(len(number)-i-1)))
output += str(temp)
print output
elif number[0]=='1':
output += "-"
carryout = 1
" flip the digits"
number = list(number)
for i in range(len(number)):
if number[i] == "1":
number[i]='0'
else:
number[i]='1'
" add 1 to number in binary sense "
for i in range(1,len(number)):
if carryout == 0 and number[len(number)-i]=='0':
break
elif carryout == 1 and number[len(number)-i]=='0':
number[len(number)-i]='1'
break
elif carryout == 0 and number[len(number)-i]=='1':
number[len(number)-i]='1'
break
elif carryout == 1 and number[len(number)-i]=='1':
number[len(number)-i]='0'
number = "".join(number)
temp = 0
for i in range(1,len(number)):
temp += int(number[i]) * (2**(len(number)-1-i))
output += str(temp)
print output
One of the most important things to consider with regard to code formatting, styling and conventions is the "house rules". If your "house" (i.e. work place, team, school, teacher, etc.) expects things done in a certain way, then that is the way you should do it.
Standards and conventions found on the internet can be used as source material for discussions on changing the house rules, or to develop your own personal standard for personal projects.
But do use some standard, and keep an offline copy of the documentation for that standard if you can, so that you can read your own code 6, 12, 24 months down the line ;).