Empty pyramid in python 3 - python

I want to print an empty pyramid in python 3 and my teacher suggested me this code but i am confused about the list(array) and i want an alternative of this code. Is there any alternative method to print an empty pyramid. This code is also available on available on stackoverflow but i want to solve it by using simple if else.
#Function Definition
def Empty_triangle(n): # Here value of n is 5
for i in list(range(n-1))+[0]:
line = ""
leadingSpaces = n-2-i
line += " "*leadingSpaces
line += "*"
if i != 0:
middleSpaces = 2*i-1
line += " "*middleSpaces
line += "*"
print(line)
# Function Call
n = 5
Empty_triangle(n)
Example of code which i want
if (row==0 and row==5 and col!=0):
output should like this using ifelse
Can it be done with simple if else

In the code your teacher suggested, the "list" seems redundant. When n=5, the "range(n-1)" command already gives you the numeric list [0, 1, 2, 3, 4]. Since it's already a list, you don't need to put "list()" around it. Then the "+[0]" just adds 0 to the end to give you [0, 1, 2, 3, 4, 0]. Also, I'm not sure if you want that extra star at the bottom center.
There are lots of alternative ways to do it, but here's an alternative version I made:
def triangle2(n):
for row in range(n):
line = [ ' ' for i in range(n+row+1)]
line[n-row] = '*'
line[n+row] = '*'
print ''.join(line)
triangle2(5)
For each row, it creates a list of spaces that's just big enough for that row, then it replaces the spaces with the locations of where the stars should be. Finally it joins all of the spaces and stars into a string, and prints it.
An even shorter way is to essentially take half of each row, then mirror it to make the second half:
def triangle3(n):
for row in range(n):
line = [ ' ' for i in range(n-row) ] + ['*'] + [ ' ' for i in range(row)]
print(''.join(line[:-1] + line[::-1]))
Or skipping lists and joins and just using concatenated strings:
def triangle4(n):
for row in range(n):
first_half = ' '*(n-row) + '*' + ' '*row
second_half = first_half[::-1][1:]
print(first_half + second_half)
The "[::-1]" part is a little trick to reverse a string or list.

# Python 3.x code to demonstrate star pattern
# Function to demonstrate printing pattern triangle
def triangle(n):
# number of spaces
k = 2*n - 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k = k - 1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
# Driver Code
n = 5
triangle(n)
careful with indent.
previously whole code wasn't displayed.

Related

Python program to give me numbers on the left with their sum on the right while having interchanged symbols in each line up to n (n=6)

Here's the picture of the program/ how it should work, it should display 1*1 then 12$3 < 3 is the sum of 1+2.. we only got to for loop.
I have tried a lot of solutions and this is what i got to at the end, for some reason i can't copy and paste it here without the code deleting whatever i had here..
also the output currently is:
please help and thanks a lot
I would implement this idea this way:
def func(n: int):
for i in range(1, n + 1):
nsum = 0 # Sum of numbers in nested loop.
last = 0 # Last number added to 'nsum'.
string = '' # Final string which is then printed.
for j in range(1, i + 1):
nsum += j # Add to total sum.
string += str(j) # Add to final string.
last = j # Set last number to current.
# Decide if either asterisk (*) or dollar ($) should be included
# in final message, after it append total sum.
string += ('*' if last % 2 else '$') + str(nsum)
print(string)
func(6)

Identifying the recursion conditions for Python String

I have this string 0123456789 and I want to use recursion to create a method that returns
'09182736455463728190'
So basically the above says that first I get the first num from the left and then the first from the right, and add them to the string, then I get the second from the left and the second from the right, etc.
When I reach the middle, I start adding to the final string the values of the initial string, but now int the opposite order. So 546372, etc. So Starting from the edges I add first the most left and then the most right element.
Starting from the middle and moving to the edges, I favour the right side element first.
I cannot come up with the recursion relationship
Here it is. The base case is when the final string length is twice the original string length. This signals the end of recursion and returns the final string. The recursive step consists of advancing the start index forward and the end index backward on the original string:
def transform_sequence(original, final = '', start_index = 0, end_index = -1):
#base case:
if len(final) == 2* len(original):
return final
#recursion
final += original[start_index] + original[end_index]
return transform_sequence(original, final, start_index + 1, end_index - 1)
print(transform_sequence('0123456789'))
#output: 09182736455463728190
If you want to use recursion to handle this, you'd better try to solve it from top-down like this
def rec(nums):
if len(nums) == 0:
return ''
elif len(nums) == 1:
return nums * 2
else:
first = nums[0]
last = nums[-1]
return ''.join([first, last, rec(nums[1:-1]), last, first])
if __name__ == '__main__':
nums = '0123456789'
print(rec(nums)) # 09182736455463728190
nums = '012'
print(rec(nums)) # 021120
nums = '0'
print(rec(nums)) # 00
Fun problem and great way to learn about recursion. We can use inductive reasoning to ensure our program is valid for all input strings -
if the input s is empty, return the empty result
(inductive) s is not empty. get the first and last characters, a and b, and prepend/append them to the result of the sub-problem, s[1:-1]
We can easily encode this in python -
def first_and_last(s):
return (s[0], s[-1])
def puzzle(s):
if not s:
return "" # 1
else:
(a,b) = first_and_last(s) # 2
return a + b + puzzle(s[1:-1]) + b + a
We can see it working below -
print(puzzle("0123456789"))
print(puzzle("12345"))
09182736455463728190
152433334251
When then puzzle input is an odd length, notice how the middle character is repeated four times. When we reach the sub-problem puzzle("3"), a=3 and b=3, and the result of a + b + puzzle("") + b + a is 3333.
If you wish to handle this situation differently, we could modify puzzle
def puzzle(s):
if len(s) < 2: # <- if input is empty or singleton string
return s # <- return s
else:
(a,b) = first_and_last(s)
return a + b + puzzle(s[1:-1]) + b + a
print(puzzle("0123456789"))
print(puzzle("12345"))
09182736455463728190
152434251 # <-
The nice answer from Menglong Li presents another option for dealing with puzzle inputs of an odd length. I encourage you to see it :D
I'd take a different approach to this problem and assume the argument is a sequence rather than a str. This simplifies our logic, allowing us to pass str to the initial call, but the recursive calls can pass list:
def puzzle(sequence):
if len(sequence) > 1:
first, *middle, last = sequence
return first + last + puzzle(middle) + last + first
return sequence[0] if sequence else ""
if __name__ == '__main__':
print(puzzle("0123456789"))
print(puzzle("12345"))
print(puzzle("012"))
print(puzzle("0"))
OUTPUT
> python3 test.py
09182736455463728190
152434251
02120
0
>
If you approach this as processing the first character (placing it at the beginning and end) and recursing with the inverted remainder of the string then your exit condition will be an empty string:
def mirror(S):
return "" if not S else S[0]+mirror(S[:0:-1])+S[0]
print(mirror("0123456789")) # 09182736455463728190
If you want to avoid generating new (inverted) strings on every recursion, you could also implement it using an index that you carry along and map to alternating start/end relative positions:
def mirror(S,i=0):
j = (i+1)//2 * (-1)**i
return S[j]+mirror(S,i+1)+S[j] if i<len(S) else ""

How can I use for loops to figure out how to solve this?

enter image description here5
I have to use a for loop to code this. I have tried many times but it never works.
enter code here
num_of_times = 5
for x in range(1, num_of_times, 5):
for y in range(5, i+5):
print(y, end= '')
print('')
You can try this:
lst = []
for i in range(1, 5):
lst.append(i * 5)
print(*lst)
You basically want to print multiple of 5. That could be achieved with two nested for loops:
max = 5
for i in range(max):
line = ''
for j in range(i+1):
line += str(5 * (j+1)) + ' '
print(line)
The first loop goes from 0 to max-1 and stores the index in i ; the second loop goes from 0 to i+1 and stores the index in j.
Then, the result of 5 * (j+1) is added to a variable called line printed at the end of the j-loop.
Feel free to follow the loops and the value of each variable at every step with a paper and a pen, that should help you.
Here you go
for i in range(1,6):
for j in range (1, i+1):
print(j*5, end = ' ')
print('')

How to print a pyramid in Python?

How to make a pyramid?
I need to make a function, that prints a full pyramid.
For example
(13 is the base width of the pyramid and 1 is the width of the top row.)
pyramid(13, 1)
Result:
.
.....
.........
.............
The step should be 4, so each row differs from the last row by 4 dots.
Edit:
This is what I have so far, but I only got the half of the pyramid and the base isn't what it's supposed to be.
def pyramid(a, b):
x = range(b, a+1, 4)
for i in x:
print(" "*(a-i) + "."*(i))
pyramid(17,1)
Try this :
def pyramid(a, b):
for i in range(b,a+1,4) :
print(str( " " *int((a-i)/2) )+ "."*(i)+ str( " " *int((a-i)/2) ))
Output:
pyramid(17,1)
.
.....
.........
.............
.................
Here is my contribution, using - character instead of blank space, for a better visualization:
def pyramide(base, top, step=4):
dot = "."
for i in range(top, base+1, step):
print((dot*i).center(base, "-"))
pyramide(13,1)
Output
------.------
----.....----
--.........--
.............
# Function to demonstrate printing pattern triangle
def triangle(n):
# number of spaces
k = 2*n - 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k = k - 1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
# Driver Code
n = 5
triangle(n)

Why can't I initialize a variable to the indices of two other variables working on a string?

The wording of my question was not polite to the search feature on the site, so I apologize should someone feel this is a duplicate question, but I must ask anyway.
Working in Python 3.6.1, my goal is to find a substring of letters in a string that are in alphabetical order and if that substring of letters is the longest substring of letters in alphabetical order (aa would be considered alphabetical order), then print out the string. I have not gotten entirely close to the solution but I'm making progress; however, this came up and I'm confounded by it being completely new to Python. My question is, why is this valid:
s = 'hijkkpdgijklmnopqqrs'
n = len(s)
i = 0
a = 0
for i in range(n-2):
if s[i] <= s[i+1]:
a = s[i+1]
i = s[i+2]
a = i + a
print(a)
And yet this is not:
s = 'hijkkpdgijklmnopqqrs'
n = len(s)
i = 0
a = 0
b = ''
for i in range(n-2):
if s[i] <= s[i+1]:
b = a + i
a = s[i+1]
i = s[i+2]
a = a + i
print(b)
When the latter code is run, I receive the error:
Traceback (most recent call last):
File "C:\Users\spect\Desktop\newjackcity.py", line 14, in <module>
b = a + i
TypeError: must be str, not int
What I am ultimately trying to do is to 'index in' to the string s, compare the zeroth element to the zeroth+1 element and if s[I] < s[I+1], I want to concatenate the two into my variable a for later printing. Because when I do this, a only prints out two letters in the string. I thought, well initialize the variable first so that a and i can be incremented, then added into a for comparison purposes, and b for printing.
I see now that I'm only going through n-2 iterations (in order to compare the second to last letter to n-1 so the logic is flawed, but I still don't understand the error of why all of a sudden binding a+i to a variable b will produce a str/int error? In my view saying s[i]; etc. is pulling out the elements as a string and this to me is proven in the fact if I run the first set of code, I get the output:
sr
>>>
In both for loops, you use i as the loop variable, so it starts as an int.
In the first version, you reassign i to a string, then add.
for i in range(n-2):
# here i is an int, something between 0 and n-2
if s[i] <= s[i+1]:
a = s[i+1] # a is a string...
i = s[i+2] # now you change i to a string
a = i + a # string + string: OK!
In the second version you try to add i first:
for i in range(n-2):
# here i is an int, something between 0 and n-2
if s[i] <= s[i+1]:
b = a + i # string + int, can't do it...
a = s[i+1]
i = s[i+2]
a = a + i
You will have an easier time debugging your code if you pick more meaningful names.
edit: here is my cleaned up version of your code:
s = 'hijkkpdgijklmnopqqrs'
# i = 0 isn't needed, range starts at 0
# the first character is always 'alphabetical'
alph_substr = s[0]
# range(1,n) is [1,2, ..., n-1]
for i in range(1, len(s)):
if s[i-1] <= s[i]:
alph_substr = alph_substr + s[i]
else:
# we have to start over, since we're not alphabetical anymore
print(alph_substr)
alph_substr = s[i]
print(alph_substr)

Categories

Resources