Convert the following while loop into a for loop. Your code should be written so that the return statement does not need to be altered. You are allowed to change the code before the while loop proper. string_list is a list of string that contains at least 15 instances of the string '***'
j=0
while i<15:
if string_list[j] ='***':
i +=1
j +=1
return j
I tried doing this first it says while i<15 and i = i+1 so i know i ranges from (0...15) not including 15 so basically we will have like i = range(15) so we will have something like:
for i in range(15):
I don't know what that j is doing there.
I will assume you meant to write string_list[j] == '***' instead of string_list[j] ='***'. I will also assume i is initialised to 0.
i, j = 0, 0
while i < 15:
if string_list[j] == '***':
i += 1
j += 1
return j
The first step is to understand what the loop is actually doing. It is iterating through string_list elements, and every time an '***' is encountered, i is incremented. The loop will terminate when i reaches 15, and since a precondition was given that string_list contains at least 15 copies of '***' we do expect the loop should terminate.
When the loop terminates, i will be equal to 15 and j will simply have counted the number of elements in the list up until this point.
So to start you off, you could try iterating like this:
for s in string_list:
if s == `***`:
# keep track of how many times this has happened
# break if you've seen it happen 15 times
j += 1
return j
j = [i for i,x in enumerate(string_list) if x=='***'][15]
return j
lazy version inspired by comments from Peter and astynax
from itertools import islice
j = next(islice((i for i,x in enumerate(string_list) if x=='***'), 15, None))
return j
Related
I am using following code to find sum of digits in Python but infinite loop gets started as I run program
def digit_sum(n):
k=str(n)
i=0
while i<range(len(k)):
l=int(i)
j=0
j=j+i
print j
i+=1
digit_sum(1234)
You have an indentation error.
So, for getting correct output try this way . You can check this code here .
def digit_sum(n):
k = str(n)
i = 0
j = 0
while i < len(k):
l = int(k[i])
j = j + l
i += 1
print j
digit_sum(1234)
The indentation is wrong. The while loop is outside of your function. Indent it to stay inside the function. Also give more meaningful names to your variables.
Its looks like you are new to python So i m going to help you out i have seen you code it seems like you have indentation problem and some logic problem also so i have updated it see it here
def digit_sum(n):
k = str(n)
j = 0 #sum for digits
i = 0
while i in range(len(k)):
#Add convert string to the int and add to the sum
j = j + int(k[i]);
#increment Counter
i = i+1
print j # print Sum
digit_sum(1234)
For more info about indentation you can See Here
I am trying to get multiple lines of the alphabet but it isn't working. At the moment I have 1 row but it won't work.
What I'm after is once the alphabet gets from a to z, it will add another letter on until aa to zz and on and on.
As Requested, the code I currently have is as follows:
import string
alphabets = string.ascii_lowercase
for i in alphabets:
print(i)
alphabets = string.ascii_lowercase
if i == 'z':
for b in alphabets:
print('{}{}'.format(b, b))
print('{}{}'.format(b, b))
I would recommend using nested for loops. The outer for loop will iterate through the alphabet, while the outer defines the number of times you want to add a given letter. Note that some string s times some integer i duplicates that string i times. This gives us:
for i in range(...) #However many instances of the alphabet you want
for j in range(26)
print(chr(ord('a')+j)*i)
EDIT: The answer above gives 'a'-'z', followed by 'aa', 'bb', ..., 'zz', etc, which is not what was being looked for.
Instead, we will construct an array and iterate through it in reverse. The code I came up with is kind of ugly, but it works. Apologies for the last line in particular.
def checkArr(arr):
for i in arr:
if i != 25:
return True
return False
arr = []
for i in range(5):
arr = []
for j in range(i+1):
arr.append(0)
while(checkArr(arr)):
s = ""
for j in arr:
s += chr(j + ord("a"))
print(s)
index = len(arr)-1
while (index > 0 and arr[index] == 25):
arr[index] = 0
index -= 1
arr[index] += 1
print("z"*(i+1))
I want to know if a number in a list is found j times consecutively ,this is my list :
list=[[1, 1, 1,1],
[0, 0, 0,0],
[2, 2, 2,2]
[2, 2, 2,2]]
And this is what i wrote :
def alignment(list,n,j):
for y in range (n):
for x in range (n-j):
counter = 0
for z in range(j):
if list[y][x]== list[y][x+z]:
counter+=1
if counter == j :
return True
But this function will check if any number is found consecutively,i want to add another parameter to this function so i can specify what number i want to look for in the list .
n means there are n rows and columns and j is how many times is how many times the number needs to be found .
Your requirements are unclear. However, this would be a slightly modified version of your code which would yield what I believe you're seeking.
target is the number for which you want to know if there are j consecutive entries.
def alignment(list,n,j,target):
for y in range (n):
for x in range (n-j):
counter = 0
if list[y][x] == target:
for z in range(j):
if list[y][x]== list[y][x+z]:
counter+=1
if counter == j :
return True
def alignment(nums,j,target):
for row in nums: # get each row
counter = 0
for i in row: # get each number
if i != target: # check if some other number was gotten
if counter == j:
return True
counter = 0 # reset counter
continue
counter += 1
if counter == j:
return True
return False
No need for the n argument.
There are a few problems with your code:
the n parameter is not needed, you can get the size of the list by using len(list)
you should not use list as a variable name, as it shadows the builtin list function
with for x in range (n-j) you are assuming that each sublist has the same number of elements as the parent list
your function also returns True if the number appears more than j times in a row
you are doing lots of double work by using three loops instead of just two
You can fix this, and also add the parameter for the number to be repeated, as shown in the other answers. However, using just loops and conditions, the resulting code will be very unwieldy.
Instead, you can create a function as you describe using any and itertools.groupby. groupby groups equal numbers, then you just have the check the len of those groups and see if any is long enough, and whether it's the correct number, for any of the sublists.
def alignment(lst, num, count):
return any(any(n == num and len(list(g)) == count
for n, g in itertools.groupby(l))
for l in lst)
This will return True if num appears exactly count times consecutively in any of the sublists.
I know I'm missing something really simple here....but I cannot put my finger on it.
My code is trying to find divisors for the items in "numbers". When count reaches 10 I know I have found the first item in numbers which has 10 divisors...but I cannot see to exit the loop. It just keeps printing the items in numbers that have 10 or more divisors.
I thought it was the indent, but no. I then moved the counter inside the first for loop to see if that was it, and still nothing.
numbers = []
numbers = [i for i in range(1, 100)]
for i in range(1, 100):
test = sum(numbers[0:i])
count = 0
for j in range(1, test+1):
if test % j == 0:
count +=1
if count == 10:
print test
break
Suggestions?
break breaks only the inner-most for loop. You need to check for count == 10 after that as well:
for i in range(1, 100):
test = sum(numbers[0:i])
count = 0
for j in range(1, test+1):
if test % j == 0:
count +=1
if count == 10:
print test
break # Breaks for j but not for i
if count == 10:
break # Breaks for i
You have to exit both for loops. There are two options:
1) Put the code in a function and use return instead of break
def process_something():
for a in items:
for b in other_items:
if some_condition:
return
2) Use a helper variable to detect that the outer loop should break too:
for a in items:
done = False
for b in other_items:
if some_condition:
done = True
break
if done:
break
In your case, you can use if count == 10: instead of if done: but I don't like duplicating "application logic" (DRY principle), so count == 10 should be in code only once. But this is a matter of taste.
3) Wrap the outer loop in a try:/catch ...: and raise exception instead of break, but please don't do this.
I'm stuck on a Python 101 type problem involving loops. Here are the directions:
The square numbers are the integers of the form K × K, e.g. 9 is a square number since 3 × 3 = 9. Write a program that reads an integer n from input and outputs all the positive square numbers less than n, one per line in increasing order. For example, if the input is 16, then the correct output would be
1
4
9
This is what I have so far but it sort of works but runs on forever. My code never reaches the if statement so it breaks(stops) before it gets to 17.
Suppose n = 17.
n=int(input())
counter = 1
while counter * counter < n:
for counter in range(1,n):
a = counter*counter
print(a)
if a < n:
break
Results:
1
4
9
16
25
36
49
64
81
Here is a correction of your code.
n=int(input())
counter = 1
for counter in range(1,n):
a = counter*counter
if a >= n:
break
print(a)
There were three things wrong with your code. First, the condition you want to break on is a >= n not a < n. Second, that condition needs to be tested before you print the number. Thus the if statement needs to be inside the for loop and before your print, statement. Third, the outer while loop is not really necessary :) Though you can add it, but a simple inner for loop will suffice.
if a < n: will never succeed unless n = 2; because inside the loop a is becoming (n-1)*(n-1) which is greater than n for n > 2; that's why the infinite loop. Try this:
>>> counter = 1
>>> n = 16 # int(input())
>>> r = counter**2
>>> while r<n:
print r
counter += 1
r = counter**2
1
4
9
Or just modify yours one by removing the outer loop, and placing the conditional inside the for loop like:
for counter in range(1,n):
a = counter*counter
if a >= n:break
print(a)
Your code loops might be the case in you semantics error try this out light on the memory and simple
def number(n):
for i in range(0,n):
w=i*i
if w>n-1:
break
print(w)
number(144)
You've got three issues here, but, as you can tell, you're on the right track.
First off, you're using two loops when you only need to be using one, and I think it's because you're a little unclear as to how the while loop works. The while loop checks that the condition is true before each time it runs. If the condition becomes false while going through the loop, the loop will still finish - it just won't start another. For example:
n = 17
while n < 18:
n += 1
print n
n += 1
print n
prints:
18
19
In your case, each iteration through the while loop creates a for loop. In order for a single iteration through the while to take place, your computer has to go through for every number from 1 to n, meaning that it'll print out all those extra numbers before your while loop even has a second chance to do its check. The easiest way to fix this is to remove the while loop and structure your code a little differently. As I'll show you in a few lines, you don't really need it.
When you say if a < n:, you've got your sign backwards and you need an equals sign. The problem asks that you give all values less than n, but, without the =, the program won't stop until it's greater than n. It should be if a >= n:.
Finally, the order of the operations isn't what you want it to be. You'd like it to check that a is less than n before printing, but you print before you do that check. If you switch them around, you'll get something like this:
n=int(input())
for counter in range(1,n):
a = counter*counter
if a >= n:
break
print(a)
which should do the trick.
What about
n= int(input())
counter= 1
while counter * counter < n:
print( counter * counter )
counter+= 1
?
Turtle man was perfect but for me. I needed to be able to get all the way to 100 so if you need to get past 81 do this
n = int(input())
counter = 1
for counter in range(1,n + 1):
a = counter*counter
if a > n:
break
print(a)