Stop for loop when the if statement is true [closed] - python

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'

Related

Organizing a list of values in ascending order with only slicing [closed]

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 10 days ago.
Improve this question
I am attempting to organize a list in Python without using sort(), mutable default arguments, loops or variables outside of the function.
The only basic option I have is slices, but I am unsure how to set up a slice to compare each value to the preceding value.
def ascending_nums(numbahs):
if len(numbahs) == 1:
return False #set a base case where if only one numbah is entered we return false
else:
ascending = ascending_nums(numbahs[::1])
if numbahs[0:] < ascending:
return True
print(ascending_nums([1,2,3,4,5,6]))
an attempt
This is what I have so far, unfortunately it exceeds the recursion limit because of how the base case is set up.
The code is not supposed to sort, just return whether or not the list is sorted. I was able to submit a solution that I will upload later.
Here is what I came up with
def list_min(numbahs):
if len(numbahs) == 0
return True #set up a base case to be true, and eliminate numbers as we move through the list
else:
overall_list = list_min(numbahs[1:]) #this makes it so the 2nd and every following member is run through the list
if numbahs[0] < overall_list: #if the first numbah in the list is less than the second
overall_list = numbahs[0] #set the second to the first value
return overall_list
Is there a specific reason why you can't use sort()? You can get pretty creative with the key= kwarg.
The standard bubble sort looks something like this:
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
swapped = False
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if (swapped == False):
break
Taken from Geeks for Geeks.
Info on sort can be found here, and info on sorted can be found here
Also, I'm sure that someone else has asked your question before. Please refer to other answers or Google before asking your question here. Stackoverflow has a LOT of questions that have already been answered.

Is it possible to increase the value of a for/while/if loop JUST once while the statement is True? [closed]

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"

Run length decompression python [closed]

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.

Only one for loop runs in python [closed]

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 4 years ago.
Improve this question
When I put 'HelLO' into this code, it should put out 10, but only puts out 5, why?
The programme is meant to add 5 to the score if a word contains a lower case letter, and another if it contains a upper case letter. However, it only has to have at least one in for the score to be added. HellO has both uppercase and lowercase letters, so should add up to 10.
capitals="A","B","C","D","E","F","G","H","I","J",
"K","L","M","N","O","P","Q","R","S","T","U",
"V","W","X","Y","Z"
characters="a","b","c","d","e","f","g","h","i","j",
"k","l","m","n","o","p","q","r","s","t","u",
"v","w","x","y","z"
word=raw_input("word please")
score=0
for i in range(0,len(word)):
a=i
for i in range(0,26):
if word[a]==characters[i]:
score=score+5
break
for i in range(0,26):
if word[a]==capitals[i]:
score=score+5
break
print score
After the execution of the loop for i in range(0,len(word)): a=i the value of a becomes len(word)-1 (in your case, 4) and never changes again. Here's what you are looking for:
import string
score = 0
# Does the string have at least one uppercase char?
if set(string.ascii_uppercase) & set(word):
score += 5
# Does the string have at least one lowercase char?
if set(string.ascii_lowercase) & set(word):
score += 5
It looks like what you want to do is have nested for loops. so that you check each letter in word to see if it meets the criteria.
but in that case you would also need to have a flag or some indication that a capital or lower case letter has been found so you don't double count.
Here are some changes you can make to get to your intended answer, however I'd also add that you there are a couple of other improvements you could make to this code for simplification/efficiency.
look into using the in functionality of lists: like letter in capitals
look into .upper() functionality built into all strings
list comprehensions
Anyways here is a fix that gets to your intended functionality.
capitals="A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
characters="a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"
word=raw_input("word please")
score=0
capital_found = False
lower_found = False
for i in range(0,len(word)):
a=i
if not lower_found:
for i in range(0,26):
if word[a]==characters[i]:
score=score+5
lower_found = True
break
if not capital_found:
for i in range(0,26):
if word[a]==capitals[i]:
score=score+5
capital_found = True
break
print score

Python read from list [closed]

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.

Categories