Nested while loop to draw pattern - python

Hi I'm wondering on how to use a nested loop to draw this pattern on the output
##
# #
# #
# #
# #
# #
# #
# #
I found out how to do it in a loop without nested, but I am curious as to how to draw this using a nested while loop.
while r < 7:
print("#{}#".format(r * " "))
r = r + 1

Here is an answer to your actual question: using two nested while loops.
num_spaces_wanted = 0
while num_spaces_wanted < 7:
print('#', end='')
num_spaces_printed = 0
while num_spaces_printed < num_spaces_wanted:
print(' ', end='')
num_spaces_printed += 1
print('#')
num_spaces_wanted += 1
As the print statements show, this is for Python 3.x. Adjust them for 2.x or add the line from __future__ import print_function to get the 3.x style printing.

If you intend to do this in python
You don't need a nested loop.
Edit With two loops
#!/bin/python
import sys
n = int(raw_input().strip())
for i in xrange(n):
sys.stdout.write('#')
for j in xrange(i):
sys.stdout.write(' ')
sys.stdout.write('#')
print

There are a number of other answers which already correctly answer the question, but I think the following does so in a conceptually more simple way, and it should make it easier to learn from.
spaces = 0
while spaces < 8:
to_print = "#"
count = 0
while count < spaces:
to_print += " "
count += 1
to_print += "#"
print to_print
spaces += 1

The most efficient solution for a nested loop:
#!/bin/python
n = int(raw_input().strip())
for i in xrange(n):
string = "#" + i * " " + "#"
print string
for -1 in xrange(n)
# Do nothing

Related

How Can I avoid the Trailing whitespace and produce the desired 8 x 8 grid in the code below using Python?, my code is below as well

for i in range(n):
for j in range(n):
z = i * n + j
if z < 10:
print(f" {z}", end = " ")
else:
print(f"{z}" , end = " ")
print()
I have tried the end= " " method but I keep getting the whitespace error, I am a beginner thus I am unable to implement other methods to address the same. The image embedded below has the desired output
[The output required ][1]
[1]: https://i.stack.imgur.com/StAVT.png
This approach creates the full matrix as a string s first and then only prints once in the end:
s = ''
for i in range(n):
for j in range(n):
z = i * n + j
s += ' '
if z < 10:
s += ' '
s += str(z)
s += '\n'
print(s)

Can you explain me the RLE algorithm code in python

I I've finally found how to make a RLE algorithm by watching a tutorial but This tutorial didn' t explain something in that code I didn't get why we write j = i instead of j = 0 (Knowing that I = 0) it's the same no ?
I didn't get why i = j + 1 either. Why i = j + 1 At the end of the function ? Why not simply i += 1 but if we want to repeat a loop in a loop then we do j + 1 ?
Did the first while loop is supposed to repeat the second while loop until the string is finished ?
And finally why encoded_message is repeated two times ? instead of one. We return encoded_message so that's it ? We can simply do print(encode(text)) instead of
"print('The encoded message is the output ',encoded_message)" (when we put encode(text) into encoded_message)
I know i'm asking a lot of questions but I just can't memorize the code without understanding it, it would be totally useless and unproductive
def encode(message):
encoded_message = ""
i = 0
while(i<len(message)):
count = 1
ch = message[i]
j = i # ???
while(j<len(message)-1): # GET IT -----------------------------------------------------------
if message[j] == message[j+1]: # if the previous and next characters are the same
count = count + 1 # we increase count variable
j += 1 # we increase j position
# GET IT ----------------------------------------------------------------------------
else:
break
encoded_message = encoded_message + str(count) + ch # "" + count converted to string + character (ch)
i = j + 1 # ???
return encoded_message
text = input('enter your charcter chain...')
encoded_message = encode(text)
print('The encoded message is the output ',encoded_message)
When I replaced j = i by j = 0 nothing is displayed in the terminal
see : no result
There is an outer loop and an inner loop. The outer loop with the variable i starts iterating over the message. The inner loop uses the variable j and starts at the current position of i.
That is: when i=0 then j=0. But when i=5 (for example) then j=5 also.
The inner loops task is to check whether 2 or more identical characters follow one another. If they do i is increased accordingly at the end of the inner loop. So that each letter of the message is only looked at once.
That is why j should not be set to a constant value. Setting it to j=0 would cause the inner loop to start at the beginning of the message at every iteration.
I added two simple print() statements to your code to clarify:
def encode(message):
encoded_message = ""
i = 0
while(i<len(message)):
print(f'outer loop: i={i}')
count = 1
ch = message[i]
j = i
while(j<len(message)-1):
print(f'\tinner loop: j={j}')
if message[j] == message[j+1]: # if the previous and next characters are the same
count = count + 1 # we increase count variable
j += 1 # we increase j position
else:
break
encoded_message = encoded_message + str(count) + ch # "" + count converted to string + character (ch)
i = j + 1
return encoded_message
text = 'Hello World'
encoded_message = encode(text)
print('The encoded message is the output ', encoded_message)
(Please note: I do not know the RLE algorithm but just looked at your code.)

Alternating lines with Nested Loops

This is the exercise I need to complete:
Using nested loops, write some code that outputs the following:
##########
**********
##########
**********
##########
Following is all the code I have so far. I assume I need to combine these two loop functions to one but I'm struggling with it. I'm early on in my first class and any help with this would be appreciated!
for a in range (0, 5, 2):
for b in range(10):
print("#", end = "")
print("")
for a in range (1, 5, 2):
for b in range(10):
print("*", end = "")
print("")
Since no input is specified, only a fixed output:
for _ in '_':
for _ in '_':
print('''##########
**********
##########
**********
##########''')
And yes, if that was my homework exercise, I'd absolutely submit this.
There are several ways to do it. First you should check how many lines you need to output. 5, so you need a loop doing something 5 times.
for i in range(5):
Now you need 2 loops to paste print the 2 line patterns (you already have them in your code)
for b in range(10):
print("#", end = "")
print("")
and
for b in range(10):
print("*", end = "")
print("")
If you need to alternate between 2 values it's mostly the best to use the Modulo Operator.
So you can just switch between the 2 loops by % 2.
for i in range(5):
if i % 2 == 0:
for b in range(10):
print("#", end = "")
print("")
else:
for b in range(10):
print("*", end = "")
print("")
I would suggest to simply base the symbol on the row index, even or odd
nb_lines = 5
line_size = 10
for i in range(nb_lines):
for _ in range(line_size):
if i % 2 == 0:
print("#", end="")
else:
print("*", end="")
print()
But no need of nested loops
nb_lines = 5
line_size = 10
for i in range(nb_lines):
if i % 2 == 0:
print("#" * line_size)
else:
print("*" * line_size)
def printStripes(row_length, number_of_rows):
for _ in '_':
print( "".join(
[ "\n" if n%(row_length+1)==row_length else
"#" if (n//(row_length+1))%2==0 else
"*"
for n in range(number_of_rows*(row_length+1))
]
),end="")
printStripes(row_length=5,number_of_rows=8)
But don't tell your teacher that you got if from stackoverflow. (Thanks Kelly, for how to deal with the nested loop constraint.)
You can use this to get the result that you want
for i in range(0,5):
print("*"*10)
print("#"*10)

How to count specific substrings using slice notation

I want to count the number of occurrences of the substring "bob" within the string s. I do this exercise for an edX Course.
s = 'azcbobobegghakl'
counter = 0
numofiterations = len(s)
position = 0
#loop that goes through the string char by char
for iteration in range(numofiterations):
if s[position] == "b": # search pos. for starting point
if s[position+1:position+2] == "ob": # check if complete
counter += 1
position +=1
print("Number of times bob occurs is: " + str(counter))
However it seems that the s[position+1:position+2] statement is not working properly. How do i adress the two chars behind a "b"?
The second slice index isn't included. It means that s[position+1:position+2] is a single character at position position + 1, and this substring cannot be equal to ob. See a related answer. You need [:position + 3]:
s = 'azcbobobegghakl'
counter = 0
numofiterations = len(s)
position = 0
#loop that goes through the string char by char
for iteration in range(numofiterations - 2):
if s[position] == "b": # search pos. for starting point
if s[position+1:position+3] == "ob": # check if complete
counter += 1
position +=1
print("Number of times bob occurs is: " + str(counter))
# 2
You could use .find with an index:
s = 'azcbobobegghakl'
needle = 'bob'
idx = -1; cnt = 0
while True:
idx = s.find(needle, idx+1)
if idx >= 0:
cnt += 1
else:
break
print("{} was found {} times.".format(needle, cnt))
# bob was found 2 times.
Eric's answer explains perfectly why your approach didn't work (slicing in Python is end-exclusive), but let me propose another option:
s = 'azcbobobegghakl'
substrings = [s[i:] for i in range(0, len(s))]
filtered_s = filter(substrings, lambda s: s.startswith("bob"))
result = len(filtered_s)
or simply
s = 'azcbobobegghakl'
result = sum(1 for ss in [s[i:] for i in range(0, len(s))] if ss.startswith("bob"))

How do I get this loop to quit once it has displayed the same letter three times?

So I have this totally screwed program. What I want to do is cut the loop off once it has displayed three of the same letters. So far what I have got is:
#Declaring letter variable
letters = str('AEIOU')
A = 0
E = 0
I = 0
O = 0
U = 0
for i in range(0, 9):
print(random.choice(letters))
if (random.choice(letters)) == ('A'):
A + 1
print(random.choice(letters))
if A > 3:
quit()
The range is arbitrary. Just for testing purposes. I also tried using a while loop but I couldn't figure out how to kill it either. It just looped infinitely:
A = 0
import random
while A < 3:
print(random.choice(letters))
if (random.choice(letters)) == ('A'):
A + 1
print(random.choice(letters))
if A > 3:
quit()
Any suggestions? Please don't hate too much...
You need to save the random character for comparison, and save the incremented counter:
import random
A = 0
while A < 3:
a = random.choice(letters)
if a == 'A':
A += 1
print(a)
If you want to keep track of all the letters, use a dictionary:
import random
letters = 'AEIOU'
d = {'A':0, 'E':0, 'I':0, 'O':0, 'U':0}
while 1:
letter = random.choice(letters)
d[letter] += 1
if d[letter] > 2:
break
You have to count the letters somehow - a dictionary is a good fit for this purpose, as TigerhawkT3 has shown.
I am using a defaultdict here, which has a default value for all entries - since I am using an int as default value, the default value is zero. This is somewhat more tricky, but saves us from initializing the array, which can be annoying if the amount of values is unknown in advance or large.
If you want to exit a loop use "break" - which breaks the current level of the loop - so for nested loops you would need mulitple breaks.
import collections
import random
letters = str('AEIOU')
printed = collections.defaultdict(int)
while True:
letter = random.choice(letters)
print(letter)
printed[letter] += 1
if printed[letter] > 2:
break
Using Counter from python collections library,
import random
from collections import Counter
letters = str('AEIOU')
counter = Counter()
limit = 3
while 1:
letter = random.choice(letters)
print(letter)
counter[letter] += 1
if counter[letter] >= limit:
break
Reference for Counter:
https://docs.python.org/2/library/collections.html#collections.Counter

Categories