I'm a beginner and trying to learn Python by myself. I've been working on coding some basic shape exercises, so far I have the following code to make a diagonal.
size = input('Please enter the size: ')
chr = raw_input('Please enter the drawing character: ')
row = 1
while row <= size:
col = 1
while col < row:
print ' ',
col = col + 1
print chr
row = row + 1
print ''
I get this output :
X
X
X
X
I would love some help on how to make this into a triangle like this....
X X X X
X X X
X X
X
Any explanations on how to make the loop necessary for the characters to show up to make the triangle shaped output would be appreciated.
You can do:
>>> for i in xrange(4):
... print ' ' * i + 'X ' * (4 - i)
...
X X X X
X X X
X X
X
The value of i goes from 0 to 3 (by using xrange) and it prints the string ' ' (two spaces) i number of times and it prints 'X ' in total (4 - i) number of times. This means it'll print the inverted triangle as desired.
The simplest fix is just to print the character print chr, instead of space print ' ',.
To invert the result vertically a simple change in the condition, from while col < row: to while col < (size - row + 1): will suffice. And finally, to invert it horizontally, add a loop that prints spaces:
size = input('Please enter the size: ')
chr = raw_input('Please enter the drawing character: ')
row = 1
while row <= size:
col = 1
while col < row:
print ' ',
col = col + 1
col = 1
while col < (size - row + 1):
print chr,
col = col + 1
print chr
row = row + 1
print ''
And finally, you can simplify this a bit:
size = input('Please enter the size: ')
chr = raw_input('Please enter the drawing character: ')
row = 1
while row <= size:
col = 1
while col < size:
if col < row:
print ' ',
else:
print chr,
col = col + 1
print chr
row = row + 1
print ''
Result:
Please enter the size: 4
Please enter the drawing character: x
x x x x
x x x
x x
x
And of course you can make this really simple looking at Simeon Visser's answer.
I wrote some code earlier that does shapes, its a bit more detailed than what you might need, but here it is:
>>> def make_triangle(size, siblings=1, step=1, char='*'):
return '\n'.join([' '.join(line) for line in [[char * (i-(step*sib)) + ' ' * (((size-(step*sib))-(i-(step*sib)))) for sib in xrange(siblings)] for i in xrange(1, size+1)]])
Making some triangles:
>>> print make_triangle(4, char='X') # standing
X
XX
XXX
XXXX
>>> print make_triangle(4, char='X')[::-1] # hanging (reversed)
XXXX
XXX
XX
X
Some of the extra features:
>>> print make_triangle(6,3,2)
*
**
*** *
**** **
***** *** *
****** **** **
Related
Is it possible to select a specific question marks from a loop and replace it with random.choice(letters) when chosen?
For example:
0 1 2
0 ? ? ?
1 ? ? ?
2 ? ? ?
User inputs 11 for example:
0 1 2
0 ? ? ?
1 ? M ?
2 ? ? ?
This is what i have done to show the board, but I have no clue how to select each question marks when the user input e.g (01 (0row 1column))
def create_game_board(rows, cols):
board = dict()
# save dimensions inside the dict itself
board['cols'] = cols
board['rows'] = rows
for y in range(rows):
for x in range(cols):
# add random letter to board at (x,y)
# x,y makes a tuple which can be a key in a dict
# changed to use string.ascii_uppercase so that you don't forget any letter
board[x, y] = random.choice(string.ascii_uppercase)
# change last element to # when both dimensions are odd
if (rows * cols) % 2 == 1:
board[rows-1, cols-1] = "?"
return board
def display_board(board):
# get dimensions
cols, rows = board['cols'], board['rows']
# print header
print(' '*30+" ".join([' '] + [str(x) for x in range(cols)]))
for y in range(rows):
# print rows
# print(' '.join([str(y)] + [board[x, y] for x in range(cols)])) # to display the actual letter at this location
print(' '*30+" ".join([str(y)] + ['#' if board[x, y] == '?' else '?' for x in range(cols)])) # using your display function
print() # separator empty line
board = create_game_board(rows[0], columns[0])
display_board(board)
def choice():
print('Hello ' + player[0]+"!")
cellnumber = input("Which cell do you want to open? (rowcolumn)")
print(cellnumber)
choice()
First, I suggest simplifying the majority of your code with the itertools module. To change get the user input (assuming it is valid), use a list comprehension to convert each character to an integer, destructure the list into col and row, then change board[col, row] to random.choice(string.ascii_uppercase). Like this:
import itertools
import random
import string
def create_board(cols, rows):
board = {k: '?' for k in itertools.product(range(cols), range(rows))}
board['dims'] = (cols, rows)
return board
def display_board(board):
cols, rows = [int(x) for x in board['dims']]
print(' ', *(str(x) for x in range(cols)))
for row in range(rows):
print(row, *(board[col, row] for col in range(cols)))
board = create_board(3, 3)
while True:
display_board(board)
row, col = [int(ch) for ch in input('Which cell do you want to open? (rowcolumn) ')]
board[col, row] = random.choice(string.ascii_uppercase)
I also added an infinite loop to keep the program going, but you can change this to fit the constraints of your program.
You can try to update the choice function to:
def choice(board):
print('Hello ' + player[0]+"!")
cellnumber = input("Which cell do you want to open? (rowcolumn)")
row = int(cellnumber[0])
col = int(cellnumber[1])
board[row, col] = random.choice(string.ascii_uppercase)
display_board(board)
answer = input('Enter a number: ')
x = 10**(len(answer) - 1)
print(answer, end = ' = ')
for i in answer:
if '0' in i:
x = x//10
continue
else:
print('(' + i + ' * ' + str(x) + ')' , end = '')
x = x//10
print(' + ', end = '')
so i have this problem, when i enter any number, everything is great but at the end there is an extra ' + ' that i do not want. Now normally this wouldnt be an issue with lists and .remove function, however i am not allowed to use these for this problem. I cannot come up with any sort of solution that does not involve functions
I tried matching the length but it didnt work because of '0'
you can insert an extra condition in the else block:
else:
print('(' + i + ' * ' + str(x) + ')' , end = '')
x = x//10
if x:
print(' + ', end = '')
this will help not to insert the last plus when it is not needed
The error is that there is an extra '+' at the end of the output. This can be fixed by adding an 'if' statement to the end of the code that checks if the last character in the output is a '+' and, if so, removes it.
Well Valery's answer is the best just add one more condition in case the answer was a 10 multiple
if x and int(answer)%10 != 0:
This kind of problem is best solved using the str.join() method.
answer = input("Enter a number: ")
x = 10**(len(answer) - 1)
terms = []
for i in answer:
if i == "0":
x = x//10
continue
else:
terms.append(f"({i} * {x})")
x = x//10
print(f"{answer} =", " + ".join(terms))
Sample interaction:
Enter a number: 1025
1025 = (1 * 1000) + (2 * 10) + (5 * 1)
Notes
We build up the terms by appending them into the list terms
At the end of the for loop, given 1025 as the input, the terms looks like this
['(1 * 1000)', '(2 * 10)', '(5 * 1)']
Update
Here is a patch of your original solution:
answer = input('Enter a number: ')
x = 10**(len(answer) - 1)
print(answer, end = ' = ')
for i in answer:
if '0' in i:
x = x//10
continue
else:
print('(' + i + ' * ' + str(x) + ')' , end = '')
x = x//10
if x == 0:
print()
else:
print(' + ', end = '')
The difference is in the last 4 lines where x (poor name, by the way), reaches 0, we know that we should not add any more plus signs.
answer = input('Enter a number: ')
#finds length of answer
length = 0
for n in answer:
length += 1
loop_counter = 0
##
zero_counter = 0
multiple_of_ten = 10
#finds if answer is multiple of 10 and if so by what magnitude
while True:
if int(answer) % multiple_of_ten == 0:
#counts the zeroes aka multiple of 10
zero_counter += 1
multiple_of_ten = multiple_of_ten*10
else:
break
#finds the multiple of 10 needed for print output
x = 10**(length - 1)
print(answer, end = ' = ')
for i in answer:
# if its a 0 it will skip
if '0' in i:
x = x//10
#still divises x by 10 for the next loop
pass
else:
print('(' + i + ' * ' + str(x) + ')' , end = '')
x = x//10
#if position in loop and zeroes remaining plus one is equal to
#the length of the integer provided, it means all the reamining
#digits are 0
if loop_counter + zero_counter + 1 == length:
break
else:
#adds ' + ' between strings
print(' + ', end = '')
# keeps track of position in loop
loop_counter += 1
ended up implementing a counter to see how many zeroes there are, and a counter to see where we are in the for loop and stop the loop when its the same as amount of zeroes remaining
I tested this code and it worked fine
if x and int(answer)%10 != 0:
Enter a number: 25
25 = (2 * 10) + (5 * 1)
Enter a number: 1000
1000 = (1 * 1000)
Enter a number: 117
117 = (1 * 100) + (1 * 10) + (7 * 1)
Attached is my code so far which generates a grid based on user inputted values. It will then allow the user to input their values and generates a grid based on rows and columns.
import numpy as np
R = int(input("Enter the number of rows: "))
C = int(input("Enter the number of columns: "))
x = R*C
game = [[row * C + col + 1 for col in range(C)] for row in range(R)]
def print_board():
line_a = "+--------" * C + "+"
line_b = "| " * C + "|"
line_c = "| {:<2} " * C + "|"
print(line_a)
for row in game:
print(line_b)
print(line_c.format(*row))
print(line_b)
print(line_a)
print("You have", x, "entries. \n")
print("Enter the entries in a single line (separated by space):")
# User input of entries in a
# single line separated by space
entries = list(map(int, input().split()))
# For printing the matrix
matrix = np.array(entries).reshape(R, C)
#print(matrix)
res = str(matrix)[1:-1]
print(' ' + res)
with open("yourGrid.txt", "w+") as f:
data = f.read()
f.write(str(' ' + res))
I am working on a basic shapes program in Python and can't seem to work out my code. I need to keep it simple using while loops and the variables given, nested loops are usable.
Here is my code for a square:
def drawSquare(size, drawingChar):
print('Square: ')
row = 1
while row <= size:
# Output a single row
drawRow(size, drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
It is supposed to print like:
x
x
x
x
based on a size and character entered by the user.
drawRow is another function similar to drawSquare:
def drawRow(size, drawingChar):
col = 1
while col <= size:
print(drawingChar, end=' ')
col = col + 1
It would make more sense with a for loop:
def drawSquare(size, drawingChar):
for i in range(size):
print(" "*i + drawingChar)
Example:
drawSquare(4, "p")
Output:
p
p
p
p
Please show your work for drawDiagonal (or anything) when asking a question.
Diagonal is probably the easier case here:
def drawDiagonal(size, drawingChar):
for y in range(size):
s = ' '* y + drawingChar
print(s)
drawDiagonal(4,"X")
X
X
X
X
(Maybe pick a fixed font)
The solution I came up with is:
def drawDiagonal(size, drawingChar):
print('Diagonal: ')
row = 1
while row <= size:
# Output a single row
drawRow(row - 1, ' ')
print(drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
Note: drawRow is defined separately (above, in question)
& drawDiagonal was called separately as well:
drawDiagonal(userSize, userChar)
where
userSize = input('Size: ')
userChar = input('Character: ')
I have a problem I can't seem to get right.
I have 2 numbers, A & B. I need to make a list of A rows with B columns, and have them print out 'R0CO', 'R0C1', etc.
Code:
import sys
A= int(sys.argv[1])
B= int(sys.argv[2])
newlist = []
row = A
col = B
for x in range (0, row):
newlist.append(['R0C' + str(x)])
for y in range(0, col):
newlist[x].append('R1C' + str(y))
print(newlist)
This is not working. The following is the output I get and the expected output:
Program Output
Program Failed for Input: 2 3
Expected Output:
[['R0C0', 'R0C1', 'R0C2'], ['R1C0', 'R1C1', 'R1C2']]
Your Program Output:
[['R0C0', 'R1C0', 'R1C1', 'R1C2'], ['R0C1', 'R1C0', 'R1C1', 'R1C2']]
Your output was incorrect. Try again
You are first adding R0Cx and then R1Cxy. You need to add RxCy. So try:
newlist = []
row = A
col = B
for x in range (0, row):
newlist.append([])
for y in range(0, col):
newlist[x].append('R' + str(x) + 'C' + str(y))
print(newlist)
You have to fill columns in a row while still in that row:
rows = []
row = 2
col = 3
for x in range(0, row):
columns = []
for y in range(0, col):
columns.append('R' + str(x) + 'C' + str(y))
rows.append(columns)
print(rows)
will print:
[['R0C0', 'R0C1', 'R0C2'], ['R1C0', 'R1C1', 'R1C2']]
Try changing your range commands as shown:
for x in range (row):
for y in range(col):
In fact, you have a second issue that you are not modifying the text properly:
newlist = []
row = A
col = B
for x in range (row):
sublist = []
for y in range(col):
sublist.append('R{}C{}'.format(x, y))
newlist.append(sublist)