Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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
Closed 9 years ago.
Improve this question
I have a question about lists in python and how to print from them. Which of the following code snippets prints all 7 words found in the list "words"? I have compiled and tried it but I still don't know which of this snippets is correct.
1.
i = 0
while i < 7:
print(words[i], end=" ")
i += 1
2.
i = 0
while i < 7:
print(words[i], end=" ")
i += 1
3.
i = 1
while i < 7:
print(words[i], end=" ")
i += 1
4.
i = 0
sum = ""
while i < 7:
sum += words[i]
i += 1
print(sum)
5.
i = 0
sum = ""
while i <= 7:
sum += words[i]
i += 1
print(sum)
If your list looks something like this, words = ["a","b","c"..],
All you have to do is iterate over them using the for statement,
for i in words:
print i
That should print out the words:
a
b
c
....
This shouldn't be all that difficult to follow as a dry run (use pen and paper if you need to).
You'll need to remember that if words has 7 elements, they are words[0]...words[6]. ie the list index starts at 0
Obviously you haven't been able to run them. How did you try to run them? What went wrong?
If you still can't work it out, a good strategy is to fall back to the answer that has the most in common with the other answers...answer 2 :)
Answer: None are correct. They are all wrong. Presuming to know how many words that should be found is the starting point of why this is wrong.
The point of putting the words you found into a list is so that you can separate the responsibility of finding results to printing them. To decouple them one can't know about the other. More specifically; you don't care how many are in the list, you just need to know how print the list. As such you are really just asking "How do I print a list".
Secondly, there is no compiling in python. Have you tried reading http://docs.python.org/2/tutorial/ ?
or http://docs.python.org/3/tutorial/
For code of a correct answer see #enginefree's answer.
Even if you are going to do it the way you are doing it with indexes i would suggest
for i in range(0..MAX_ELEMENTS-1):
print words[i]
I also would strongly discourage use of while loops for a problem with a definite knowable boundary of operations such as iteration over a collection from the outset of the operation. While generally implies changing conditions, unknowable endpoints and the need for custom increment control.
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 6 months ago.
Improve this question
Python
Is it possible to increase the value of a for/while/if loop just once while the statement is true? E.g.,
n = [1,2,3,4,5,-1,4,5,6,3,-1,3,4,5,-1]
counter = 0
Let's say I want my counter to go up JUST once while i>0 for every element in the array until false. How can I translate this into coding language so that for 1 2 3 4 5 I get True but only once for 4 5 6 3 True, so counter up again?
I'm looking for a counter of 3 since the elements are > 0 three times, if that makes sense. I'm not quite sure how to explain it.
Not sure if understand you correctly but this will only increase the counter when the element equals -1.
counter = 0
n = [1,2,3,4,5,-1,4,5,6,3,-1,3,4,5,-1]
for element in n:
if element == -1:# increases the counter when reaching an element with value -1
counter += 1
continue
print(element, True)# ? not quite sure what you mean with "i should get TRUE"
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'm trying to make a run length decoder that doesn't use 1s. For example a string that could be passed through would be something like ''' A2C3GTA'''. I made what i thought would work and am having trouble finding where I went wrong. I'm a beginner to python so I am sorry for the simple question. Thank you!
def decode(compressed):
decoded= ""
count = 0
for x in compressed :
if x.isdigit():
count += int(x)
y = compressed
decoded += y[int(x)+1] * count
count = 0
else :
decoded += x
print (decoded)
When you find a number-letter pair, you fail to skip the letter after you expand the pair. This is because you used a for loop, which is a more restrictive structure than your logic wants. Instead, try:
idx = 0
while idx < len(compressed):
char = compressed[idx]
if char.isdigit():
# replicate next character
idx += 2
else:
decoded += char
idx += 1
That will take care of your iteration.
Your in appropriate replication, the 22 in your output, this comes from an incorrect reference to the position:
decoded += y[int(x)+1] * count
Here, x is the run length, not the position of the character. If the input were A7B, this ill-formed expression would fault because of an index out of bounds.
In the code I gave you above, simply continue to use idx as the index.
I trust you can finish from here.
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
Use while and if statements to count how many 0’s are before the first 1 (from left to right).
code = '00000000101100110001111110110011'
num_zero_before_1 = 0
for i in code:
if i != '1':
num_zero_before_1+=1
print(num_zero_before_1)
I cannot seem to get the answer
loops in python have two control statements: continue and break. Continue skips the rest of the iteration and starts from the top and break completely leaves the loop. So what you want here is to break on the else condition.
You have made a small mistake. You are counting zeroes by if condition using i != '1' but you should add else also to break the loop whenever the first '1' encountered, otherwise your loop will go on counting all zeroes.
Here is correct solution:
code = '00000000101100110001111110110011'
num_zero_before_1 = 0
for i in code:
if i != '1':
num_zero_before_1+=1
else:
break
print(num_zero_before_1)
Shouldn't you use while loop instead of for... in loop?
This solution should fulfill exercise assumptions:
iterator = 0
while True:
if code[iterator] != '1':
iterator += 1
else:
break # it stops the loop, goes out of it
print(iterator) # number of zero before '1'
However, this solution is shorter and easier, maybe it'll be useful to you:
iterator = 0
while code[iterator] != '1':
iterator += 1
print(iterator) # number of zero before '1'
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 does not meet Stack Overflow guidelines. It is not currently accepting answers.
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
Closed 9 years ago.
Improve this question
Write a while loop that sums the values 1 through end, inclusive. end is a variable that we define for you. So, for example, if we define end to be 6, your code should print out the result:
21
which is 1 + 2 + 3 + 4 + 5 + 6.
Is anybody able to guide me through this, without spoiling it for me?
There are two things you can do. The "fast" way (a la the story about the young Gauss) recognizes that
sum(1:N) = N * (N + 1) / 2
But I doubt that is what is asked.
You need to create a loop (look at the for command) over a range (look at the range command), and in each iteration add the current value of the loop variable to the sum (which you initialize to zero before the start of the loop).
There - you should now be OK.
EDIT with a while loop, and still leaving you to do a little bit of work:
mySum = 0
i = 1;
while( <<< put some condition here >>> ):
mySum = mySum + i
<<<<< do something clever with i >>>>>
print <<<<< what do you think you should print here? >>>>>
Note that indentation is important in Python, and the : at the end of the while statement matters