Printing a hollow triangle in alphabetical order anti-clock-wise - python

I'm currently having some difficulty with this python pattern problem, where I am not able to generate the proper output, required to this problem. If I could receive some help or feedback from you guys that'll be great! Thank you!!
def print_triangle(sentence):
if len(sentence) % 4 != 0:
return False
else:
char_list = list(sentence)
x = 0
n = int(len(sentence) / 4) + 1
for row in range(1,n+1):
for col in range(1,2*n):
if row ==n or row+col == n+1 or col-row == n-1:
print(char_list[x] ,end="")
x += 1
else:
print(end=" ")
print()
return True
if function print_triangle('abcdefghijkl') is called, it should be able to generate the following output:
a
b l
c k
defghij
Return value:True
However, this is the output that I'm getting
a
b c
d e
fghijkl
Return value:True

Algorythm:
row 0: print spaces + first letter
row 1: print 1 less spaces + next letter, print row*2-1 spaces, print last letter
row 2: - the same, just print the letter before the last letter
...
last row: print remaining letters up to (not including) those that being printed already:
def print_triangle(sentence):
n = len(sentence)
if n % 4 != 0:
return False
# special case handling ;)
elif n==4:
print(" " + sentence[0], sentence[1:], sep="\n")
return True
else:
numRows = n//4
for row in range(numRows+1): # amount of total triangle rows
# end case, print the rest thats not been printed
if row == numRows:
print(sentence[row:-row+1])
return True
# normal case: print enough spaces, then 1 letter, do not end the line
print(' '*(numRows - row)+sentence[row],end="")
# on all but the first line: print padding spaces and last letter
if row != 0:
print(' '*(2*row-1)+sentence[n-row])
else:
print("") # newline to "close" this line if on line 0
print("")
r = print_triangle(input())
print(r) # or do print("Return value: {}".format(r)) to be exact...
Output: ('abcdefghijkl')
a
b l
c k
defghij
True
Output: ('abcdefghijklmnop')
a
b p
c o
d n
efghijklm
True
Output: ('abc')
False

Related

Hollow triangle using while loops python

Trying to make a program that asks the user for a height and a character, and then outputs a hollow triangle to that height using that character. Was trying to firstly make a solid triangle, then solve it from there, but so far have only managed to make a half triangle.
Also, using only for loops and no '*' operator
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 1
count = 0
while rows <= H:
spaces = 0
while spaces <= (H - rows):
print(" ", end="")
spaces += 1
count = 0
while count < rows:
print(C, end="")
count += 1
print()
rows += 1
this results in this:
*
**
***
****
*****
my goal is this:
*
* *
* *
* *
*********
any help would be appreciated!
Slightly changed your script:
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 1
count = 0
while rows <= H:
spaces = 0
while spaces <= (H - rows):
print(" ", end="")
spaces += 1
count = 0
while count < 2*rows-1:
count += 1
if count == 1 or count == 2*rows-1 or rows == H:
print(C, end="")
else:
print(" ", end="")
print()
rows += 1
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
for i in range(H):
for j in range(H - i):
print(' ', end='')
for j in range(2 * i + 1):
if j == 0 or j == 2 * i or i == H - 1:
print(C, end='')
else:
print(' ', end='')
print()
There's already an answer, but considering that I had fun doing this little program, and that our solution are not the same :
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 0
while rows <= H:
cols = 0
if rows == H:
while cols <= H*2:
print(C, end="")
cols += 1
else:
while cols <= H*2:
if rows + cols == H or cols - rows == H:
print(C, end="")
else:
print(" ", end="")
cols += 1
print()
rows += 1
Note that I did this with for loops, and just swapped to while loops to paste it here.
The way to get a hollow triangle is to print spaces in a loop.
If you observe the output you need, you'll see that except for the top and bottom lines, every line has only 2 asterisks (*). That means you need a logic that handles spaces.
There are several ways to write the logic, such as treating each vertical halves as blocks of fixed length and just varying the position of the star or actually counting the spaces for each line. You can explore the different ways to achieve what you need at your convenience. I'll present one soln.
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if len(C) != 1:
C = "*"
rows = 1
count = 0
while rows < H:
str = ""
for i in range(H - rows):
str += " "
str += C
if rows > 1:
for i in range(2 * rows - 3):
str += " "
str += C
print(str)
rows += 1
str = ""
for i in range(2 * H - 1):
str += C
print(str)
I have made a change about checking the character. You should not allow characters of more than length 1. Otherwise, the spacing will get messed up
These exercises are meant for you to understand the logic and get comfortable with manipulating code, so do try different variations
This is probably not the most optimized solution but, remember that printing is in general slow as it has to interact with a peripheral (monitor), so try to print in bulk whenever possible. This improves the speed

How can i remove the break from find_frequent(s) code since our teacher told us we can't use it on the test and I'm trying to practice not using it?

I wrote this code, and I'm struggling to replace using break since it says in the homework that we are not allowed to use continue/break statements in our loops.
The code's goal is:
finds the character that appears most frequently in the input parameter string and returns it. For Example, if the string is "Canada day" the function returns the string "a"
If there are two characters or more with the same frequency, the function should return the first of many values with the same frequency.
def find_frequent(s):
"""
-------------------------------------------------------
description
Use:
-------------------------------------------------------
Parameters:
name - description (type)
Returns:
name - description (type)
------------------------------------------------------
"""
L = []
count = 0
char = 0
i = 0
words = True
while i < 1 and words:
x = s[i]
for j in range(len(L)):
if x == L[j]:
words = False
L[j + 1] = L[j + 1] + 1
else:
L.append(x)
L.append(1)
for i in range(1, len(L), 2):
if L[i] > count:
count = L[i]
char = L[i - 1]
return char
the output should look like this
`Enter a string: Hello Hi`
output should be
`Most frequent characters: H`
I'm getting this output
Enter a string: canada
Most frequent character: c
You can replace the break statement in a for loop with a while loop.
print("using for loop + break")
for i in range(0, 5):
print(i)
if i == 3:
break
print("using while")
i = 0
keep_searching = True
while i < 5 and keep_searching:
print(i)
if i == 3:
keep_searching = False
i += 1
The output is:
using for loop + break
0
1
2
3
using while
0
1
2
3
I think you can figure it out from here, but if you need help with finding the most frequent character (a different issue from the break), take a look here and here.
No need for a break if you don't use a loop in the first place :-)
def find_frequent(s):
return max(s, key=s.count)
(I'm actually serious... forbidding break sounds to me like your teacher didn't want you to write it with such nested loops.)
Or if you want to teach your teacher a lesson (the lesson being that they shouldn't forbid stuff), you could fake the break:
for i in range(0, len(s), 1):
x = s[i]
it = iter(range(len(L))) # make it an iterator
for j in it:
if x == L[j]:
L[j + 1] = L[j + 1] + 1
*it, # exhaust the iterator
it = None # make it false
if it: # instead of `else`
L.append(x)
L.append(1)

Prints letter pattern with certain amount of rows

I need help fixing my code, see below for problem.
I have to write a function that prints out the L shape made up of *'s. Also, the parameter M is an integer between 1 and 80 and is the rows of the shape. The output needs to be N rows, the last of which should comprise N letters of L.
My user input should be the desired rows but its just printing the range, and even that looks a little off. Please assist, if you can... this is what I have so far:
M = int(input())
def solution(M):
result =""
if M > 80:
for row in range(1, 80):
for column in range(1, 80):
if (column == 1 or (row == 1 and column != 0 and column < 1)):
result = result + "*"
else:
result = result + "\n"
print(result)
solution(M)
This is just printing * for each row, unless the row = M in which case it is printing "*" * M and exiting if the value is >= 80 or <= 1 (since you said between 1-80):
import sys
print("Please enter an integer between 1-80:")
M = int(input())
def solution(N):
if N >= 80 or N <= 1:
sys.exit("Please run again using an integer between 1-80")
result = ""
for row in range(1, N+1):
if row < N:
result = "*"
print(result)
elif row == N:
result = "*" * N
print(result)
solution(M)
Then when you run:
[dkennetz#nodecn001 tmp]$ python3 fun.py
Please enter an integer between 1-80:
4
*
*
*
****
M = int(input())
def solution(M):
result_str=""
for row in range(0,M+1):
for column in range(0,M+1):
if (column == 1 or (row == M and column != 0 and column < M)):
result_str=result_str+"*"
else:
result_str=result_str+" "
result_str=result_str+"\n"
print(result_str)
solution(M)
https://ideone.com/UoGj2n
https://www.w3resource.com/python-exercises/python-conditional-exercise-21.php
You can try with this solution. I hope that it's clear enough:
SYMBOL = '*'
def solution(M, N):
result = []
# validations
if M > 80:
M = 80
if N > 80:
N = 80
for row in range(1, M + 1):
if row < M:
result.append(SYMBOL)
else:
# last row
result.append(''.join([SYMBOL for column in range(1, N + 1)]))
return result
# generate rows
result = solution(10, 5) # TODO: use values from input() instead
# print result
for row in result:
print(row)

Connection and Disconnection (AtCoder Grand Contest 039_A)

I am trying to solve this task. Source
A string S is given. Let T be the concatenation of K copies of S. We can repeatedly perform the following operation: Choose a character in T and replace it with a different character. Find the minimum number of operations required to satisfy the following condition: Any two adjacent characters in T are different.
Input is given from Standard Input in the following format:
S
K
Print the minimum number of operations required.
Below is the code that I've written.
I've separated the problem into 5 cases.
i) S is a single letter.
ii) S is two letters and they are the same.
iii) S is two letters and they are different.
iv) S is more than two letters and the first and last letters are different.
v) S is more than two letters and the first and last letters are the same.
S = input()
K = int(input())
L = len(S)
sum = 0
x = 1
if L == 1: # i)
print(K//2)
elif L == 2 and S[0] == S[1]: # ii)
print(K)
elif L == 2: # iii)
print(0)
elif S[0] != S[-1]: # iv)
for i in range(0, L-1):
if S[i] == S[i+1]:
x += 1
else:
sum += (x // 2)*K
x = 1
sum += (x // 2)*K
print(sum)
else: # v)
for i in range(0, L-1):
if S[i] == S[i+1]:
x += 1
else:
sum += (x // 2)
break
y = x
x = 1
for i in range(y, L-1):
if S[i] == S[i+1]:
x += 1
else:
sum += (x // 2)*K
x = 1
sum += (x // 2)
sum += ((x+y) // 2) * (K-1)
print(sum)
My code fails 2 out of 15 test cases. I have no idea what part of my work is causing the issue. Can somebody point out which part of the code is problematic? Thank you!

Errors trying to find only the number in a string?

Supposed to take in a string for example "Maroon 5" and then return only the number in the statement. In this case it's "5" but I just get no output. Thank you!
def findNumbers(str):
found1 = False
found2 = False
i = 0
while not found1 and i<len(str):
if str[i] in "0123456789":
found1 = True
else:
i = i + 1
if found1:
j = 0
while not found2 and j<len(str):
if str[j] in "0123456789":
found2 = False
else:
j = j + 1
else:
return 0
istr = str[i:j]
n = (istr)
return n
print (findNumbers("Maroon 5"))
You have two important errors in your code. One is that once you've found a digit, you jump back to the start of the string:
j = 0
Instead, you want to continue from there:
j = i
The other, bigger problem is that you have an infinite loop. The second loop may continue indefinitely if str[j] is a digit, since setting found2 to False does not end the loop. The code should be
while not found2 and j<len(str):
if str[j] not in "0123456789":
found2 = True
else:
j = j + 1
you can do it like this:
def findNumbers(str):
for i in range(0,len(str)):
if (str[i].isdigit()):
print str[i]
findNumbers("Maroon 5")
It should print the number 5
You can try this way: This will return a list of tuples with the numbers and their indexes
def findNumbers(string):
num = '1234567890'
return ([(string[x], x) for x in range(len(string)) if string[x] in num])

Categories

Resources