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)
Related
This is a program to print a matrix whose sum of each row , column or diagonal elements are equal.
I have a working code but my program gives same output each time i run it. I need a program to print different matrix output for same input.
def matrix(n):
m = [[0 for x in range(n)]for y in range(n)]
i = n // 2
j = n - 1
num = 1
while num <= (n * n):
if i == -1 and j == n:
j = n - 2
i = 0
else:
if j == n:
j = 0
if i < 0:
i = n - 1
if m[int(i)][int(j)]:
j = j - 2
i = i + 1
continue
else:
m[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1
print ("Sum of eggs in each row or column and diagonal : ",int(n*(n*n+1)/2),"\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (m[i][j]),end = '')
if j == n - 1:
print()
n=int(input("Number of rows of the matrix : "))
matrix(n)
I am unsure whether this is what you are looking for, but one solution is to add a random number to each value of the matrix, as this doesn't break the property
a matrix whose sum of each row, column or diagonal elements are equal.
Here is how you could do it:
add = random.randint(0, 50)
m = [[v+add for v in row] for row in m]
Moreover, you can rotate and add two magic squares without loosing their property. Therefore, you can rotate the magic square you have and add it to the original. This can add some nonlinearity to the results.
def rotate(m): # 90 degrees counter clockwise
return [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1, -1, -1)]
# add the matrix with its rotated version
m = list(map(lambda e: [sum(x) for x in zip(*e)], zip(m, rotate(m))))
I hope this helps!
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
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!
Take integer input from a user and then delete the elements from an array having those many consecutive ocurences from the array.
Eg the input array is "aabcca" and the input from the user is 2.
Then the answer should be "ba".
I tried it when the elements are not repeated. My code works perfectly for examples like "aaabbccc".
for j in range(t, (n+1)):
if (t == n):
if (count == k):
array = [x for x in array if x != temp]
print array
exit()
if (t == n and count == k):
array = [x for x in array if x != temp]
print array
exit()
if temp == data[j]:
count += 1
t += 1
if temp != data[j]:
if count == k:
array = [x for x in array if x != temp]
temp = data[t]
count = 1
t += 1
you can use sliding window or two pointers to solve it.
the key point is use [start, end] range to record a consecutive seq, and only add the seq whose length less than n:
def delete_consecutive(s, n):
start, end, count = 0, 0, 0
res, cur = '', ''
for end, c in enumerate(s):
if c == cur:
count += 1
else:
# only add consecutive seq less than n
if count < n:
res += s[start:end]
count = 1
start = end
cur = c
# deal with tail part
if count < n:
res += s[start:end+1]
return res
test and output:
print(delete_consecutive('aabcca', 2)) # output: ba
print(delete_consecutive('aaabbccc', 3)) # output: bb
Hope that helps you, and comment if you have further questions. : )
Here is one way to do that:
def remove_consecutive(s, n):
# Number of repeated consecutive characters
count = 0
# Previous character
prev = None
# Pieces of string of result
out = []
for i, c in enumerate(s):
# If new character
if c != prev:
# Add piece of string without repetition blocks
out.append(s[i - (count % n):i])
# Reset count
count = 0
# Increase count
count += 1
prev = c
# Add last piece
out.append(s[len(s) - (count % n):])
return ''.join(out)
print(remove_consecutive('aabcca', 2))
# ba
print(remove_consecutive('aaabbccc', 2))
# ac
print(remove_consecutive('aaabbccc', 3))
# bb
I am trying to create an arrow out of asterisk's, where the amount of columns is entered by the user. Yes, I do know how to use for loops to accomplish this:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
for x in range(1, columns):
for x in range(x):
print(" ", end="")
print("*")
for x in range(columns,0,-1):
for x in range(x):
print(" ", end="")
print("*")
#output looks like
"""
How many columns? 3
*
*
*
*
*
"""
However my question is, how would I accomplish the same outcome using only while loops?
Thanks
Edit: I was going to post what I had thus far in trying to work it out myself, but it is now of no use!
Thank you all for your efficient varying answers! Much appreciated!
Just for fun, here's a version that doesn't loop using indexing.
def print_arrow(n):
a = '*'.ljust(n + 1)
while a[-1] != '*':
print(a)
a = a[-1] + a[:-1]
a = a[1:]
while a[0] != '*':
a = a[1:] + a[0]
print(a)
# Test
print_arrow(4)
output
*
*
*
*
*
*
*
This should do:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
while x < columns:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x += 1
x = columns
while x > 0:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x -= 1
First, it's better to use functions. And easier if you know that character*number returns that character concatenated number times.
Example:
'*'*10
returns
'**********'
So your program using whiles would follow the same logic.
def print_arrow(k):
i = 0
while(i < k-1):
print(i*' ' + '*')
i +=1
while(i >= 0):
print(i*' ' + '*')
i -= 1
The first while prints the upper part, the last one uses the fact that i = k-1, so just do same in the reversed order.
Example:
print_arrow(3)
returns
*
*
*
*
*
n = int(input( ))
n1 = n//2 + 1
i = 1
while i <= n1:
space = 1
while space <= i - 1:
print(" ",end="")
space += 1
j = 1
p = "*"
while j <= i:
if j == i:
print(p,end="")
else:
print("* ",end="")
j += 1
print()
i += 1
i = n - n1
while i >= 1:
space = 1
while space <= i - 1:
print(" ",end="")
space += 1
j = 1
p = "*"
while j <= i:
if j == i:
print(p,end="")
else:
print("* ",end="")
j += 1
print()
i -= 1
Arrow pattern of asterisk
-Remember the n value here is always odd
for n = 5
output will be