I have to do a hash triangle using this function:
def line(num=int, word=str):
if word == "":
print("*" * num)
else:
print(word[0] * num)
Here is the code i have:
def line(num=int, word=str):
if word == "":
print("*" * num)
else:
print(word[0] * num)
def triangle(size):
# You should call function line here with proper parameters
while size > 0:
line(size, "#")
size -= 1
the output is this:
######
#####
####
###
##
#
but it should be this:
#
##
###
####
#####
######
how can i modify it so it prints that?
You are starting from size and going to 1 you should do the opposite:
i = 0
while i <= size:
i += 1
...
Also for i in range(1, size + 1) would be more pythonic ;)
Slightly adjusted your code
def line(num=int, word=str):
if word == "":
print("*" * num)
else:
print(word[0] * num)
def triangle(size):
# You should call function line here with proper parameters
charPerLine = 1
while charPerLine <= size:
line(charPerLine, "#")
charPerLine += 1
triangle(5)
Related
I'm trying to recreate this shape (image below) using Python but I have some difficulties with the spaces.
This is the code that I have so far.
def shape(n):
for i in range(0,n):
for j in range(0,i+1):
print("*",end="")
print("")
for i in range(n,0,-1):
for j in range(0,i-1):
print("","*",end="")
print("")
shape(10)
I would appreciate it if you could help me.
def star(width = 10):
left_start = 0
right_start = 0
size = width
while right_start != size:
right_start += 1
print("*" * (right_start - left_start))
while left_start != right_start:
left_start += 1
print(" " * left_start + "*" * (right_start - left_start))
Hope this helps!
It seems that my decoration sometimes appears just outside the triangle... How can I fix this?
import random
n = int(input('enter n: '))
x = 1
for i in range(n):
if i == 0:
count = 0
else:
count = random.randint(0, x)
print(' ' * (n - i), '*' * count, end = '')
if i == 0:
print('&', end = '')
else:
print('o', end = '')
print('*' * (x - count - 1))
x += 2
What do I get for value n = 10:
&
***o
*o***
o******
******o**
*********o*
*************o
*****o*********
*************o***
******************o
The random number you generate may return x as randint includes the second value in the set of possible values. So pass x - 1 to randint:
count = random.randint(0, x - 1)
It is also a pity that you have a check for i == 0 in your loop. In that case, why not deal with that first case outside of the loop, and start the loop at 1? It will make your code a bit more elegant.
def tree(n):
from random import sample
body = ["&"] + ["".join(sample("o" + "*" * (k:=x*2+1), k=k)) for x in range(1, n)]
spaces = [" " * (x-2) for x in range(n, 1, -1)]
return "\n".join("".join(tpl) for tpl in zip(spaces, body))
print(tree(10))
Output:
&
o**
****o
o******
*******o*
********o**
*******o*****
**************o
o****************
I love christmas tress! This is my take on the question :-)
import random
n = int(input('Enter tree height: '))
print(" " * (n-1) + "&")
for i in range(2, n+1):
decoration = random.randint(1, (i-1)*2 -1)
print(" " * (n - i) + "*" * decoration + "o" + "*" * ((i-1)*2 - decoration))
Enter tree height: 12
&
*o*
**o**
*o*****
*o*******
********o**
*******o*****
***********o***
********o********
****************o**
***o*****************
*********o*************
I want to make a pattern as shown below:
I write this program which is given below. But I couldn't take ODD numbers. Could anybody please explain what the mistake is and what the solution is? Thanks.
*
def printPartten(n, k):
if (n < 0): # Base condition
return;
# Recursive call
printPartten(n - 1, k + 1);
for i in range(0, k): # it makes spaces
print(" ", end="");
for i in range(0, n): # for print *
print("* ", end = "");
print("\n", end=""); # for next line
def printPatternReverse(n, k):
if (n < 0): # Base condition
return;
for i in range(0, k): # it makes spaces
print(" ", end = "")
for i in range(0, n): # for print *
print("#", end = " ")
print("\n", end = "") # for next line
# Recursive calls
printPatternReverse(n - 1, k + 1);
# Call to printPartten function
n = int(input("Please enter the desire value for N: "))
printPartten(n, 0);
print("\n",end="")
printPatternReverse(n,0)
print("Thank You!!!")
*
My Output like this:
You example shows that it skips the even rows, so you could add a check for even rows using a modulus:
if (k % 2 == 0):
Applied to your code:
def printPartten(n, k):
if (n < 0): # Base condition
return;
# Recursive call
printPartten(n - 1, k + 1);
if (k % 2 == 0):
for i in range(0, k): # it makes spaces
print(" ", end="");
for i in range(0, n): # for print *
print("* ", end = "");
if (k > 0):
print("\n", end=""); # for next line
def printPatternReverse(n, k):
if (n < 0): # Base condition
return;
if (k % 2 == 0):
for i in range(0, k): # it makes spaces
print(" ", end = "")
for i in range(0, n): # for print *
print("#", end = " ")
print("\n", end=""); # for next line
# Recursive calls
printPatternReverse(n - 1, k + 1);
# Call to printPartten function
n = int(input("Please enter the desire value for N: "))
printPartten(n, 0);
print("\n",end="")
printPatternReverse(n,0)
print("Thank You!!!")
Output:
Please enter the desire value for N: 9
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
# # # # # # # # #
# # # # # # #
# # # # #
# # #
#
Thank You!!!
I've made a program that can print out a random row of characters for a dungeon-crawler like game and I'm wondering if I can make it to have the # symbol print once and only once.
I have tried making it check the list of previously printed strings and making sure that if it has been printed it won't print again but that doesn't seem to be working and I'm kinda new to this. Any suggestions?
import random
import time
randomnumber = random.randint(6,16)
block = []
printed = []
health = 10
blocks = "\x1b[1;37;48m#"
x_axis = 1
y_axis = 1
randumplace = random.randint(0, len(block))
multiplier = random.randrange(6,35)
def build(blocks):
for i in range (multiplier):
block.append(blocks)
i = random.randrange(1,75)
if i == 4:
blocks = "\x1b[1;31;48mM"
elif i == 15:
blocks = "\x1b[1;36;48m~"
elif i == 25:
blocks = "\x1b[1;36;48m~"
elif i == 22:
blocks = "\x1b[1;33;48m$"
elif i == 1:
blocks = "\x1b[1;37;48m#"
elif i == 10 and "#" not in printed:
blocks = "#"
else:
blocks = "\x1b[1;37;48m."
fip = build(blocks)
counter = 1
print("# "+"# # # # # #" + " #" * (multiplier - 6))
while counter != randomnumber:
printed.append(block)
del block[:]
build(blocks)
print (*block)
counter += 1
print ("" + "# " * (multiplier +1))
It should print out 5 - 15 lines of strings like "# . . . . M . . $ . . # . . ."
but it instead prints multiple # symbols like
"# . . . . # M . . . # . . # . . ."
I also want to make sure that other lines don't also print the # symbol, and that's the reason for the "printed" list.
A much easier approach is to create a matrix in memory, e.g.
maze = [[' '] * random_width for i in range(random_height)]
then you fill the maze as you like and only when it's complete you print it.
First of all, collapse your choice of blocks into a simple look-up table:
rand_limit = 75
block = ["\x1b[1;37;48m."] * rand_limit
block[01] = "\x1b[1;37;48m#"
block[04] = "\x1b[1;31;48mM"
block[15] = "\x1b[1;36;48m~"
block[22] = "\x1b[1;33;48m$"
block[25] = "\x1b[1;36;48m~"
Now you can do your entire maze as a nested list comprehension, substituting the block symbols for the random numbers:
maze_rows = random.randrange(6, 35)
maze_cols = random.randrange(5, 16)
maze = [ [block[random.randrange(1, rand_limit)]
for col in range(maze_cols)]
for row in range(maze_rows) ]
Finally, pick a random row and column for your unique symbol:
maze[random.randrange(maze_rows][random.randrange(maze_cols]] = '#'
If you don't want to overwrite an existing symbol, then loop until you hit a blank spot.
I just moved the printed.append() function up into the build function.
Try this:
import random
import time
randomnumber = random.randint(6,16)
block = []
printed = []
health = 10
blocks = "\x1b[1;37;48m#"
x_axis = 1
y_axis = 1
randumplace = random.randint(0, len(block))
multiplier = random.randrange(6,35)
def build(blocks):
for i in range (multiplier):
block.append(blocks)
i = random.randrange(1,75)
if i == 4:
blocks = "\x1b[1;31;48mM"
elif i == 15:
blocks = "\x1b[1;36;48m~"
elif i == 25:
blocks = "\x1b[1;36;48m~"
elif i == 22:
blocks = "\x1b[1;33;48m$"
elif i == 1:
blocks = "\x1b[1;37;48m#"
elif i == 10 and "#" not in printed:
blocks = "#"
printed.append("#")
else:
blocks = "\x1b[1;37;48m."
fip = build(blocks)
counter = 1
print("# "+"# # # # # #" + " #" * (multiplier - 6))
while counter != randomnumber:
del block[:]
build(blocks)
print (*block)
counter += 1
print ("" + "# " * (multiplier +1))
I have a homemade text encryption script which outputs a "List index out of range" error when I input "Hey dude, how are you doing?" as a text to encrypt and "KFC" as an encryption key.
I get this more precisely:
Traceback (most recent call last):
File "/Users/BCPianist/Google Drive/Project-Cryptonite/NCrypt.py", line 75, in <module>
main(userIn, a)
File "/Users/BCPianist/Google Drive/Project-Cryptonite/NCrypt.py", line 47, in main
currentscrtrank += 1 + scrtlst[scrtrankcounter]
IndexError: list index out of range
I have two files used in this script (the main script and a function library). I just can't figure where this error is coming from...
Here is my main script:
import random
from cryptolib import *
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
print("Content-Type: text/plain;charset=utf-8") # Definit le code d'ecriture
print() # Insere une ligne d'espacement.
def main(userin, numberedsecretkey): # Fonction principale (le gros de l'encryption)
"""
This is my main.
>>> main("Allo", "Hey")
10842839726
"""
comments = True # Definit si les commentaires lors de l'impression sont actif ou non (False les desactive)
total = convdecimal(userin) # Time to deal with the encryption key:
scrtkeytotal = convdecimal(numberedsecretkey)
# converting numbered message to list
msglst = [int(elem) for elem in str(total)]
if comments == True:
printdebug("The initial numbered message is:%s " % msglst)
# converting numbered key to list
scrtlst = [int(thingy) for thingy in str(scrtkeytotal)]
if not comments != True:
printdebug("The initial encryption key is:%s" % scrtlst)
# Attempting Encryption
scrtrankcounter = 0
currentscrtrank = scrtlst[scrtrankcounter]
while currentscrtrank < len(msglst):
randomgen = random.randint(0, 9)
msglst.insert(currentscrtrank, randomgen)
if comments:
printdebug(str(randomgen) + " was inserted at rank: " + str(
scrtrankcounter) + ", therefore, at index position: " + str(currentscrtrank) + ".")
printdebug("List now appears as: " + str(msglst))
scrtrankcounter += 1
if scrtrankcounter > len(scrtlst):
scrtrankcounter = 0
currentscrtrank += 1 + scrtlst[scrtrankcounter]
return listtoint(msglst)
def convdecimal(userin):
rank = len(userin)
total = 0
for character in userin:
rank -= 1 # decreasing the letter rank by one
letter = ord(character)
if letter < 32:
pass
elif letter == 27:
pass
else:
rankmult = 255 ** rank # Making a multiplier
lettervalue = letter * rankmult # Multiplying the letter by this multiplier
total += lettervalue # Adding the letter's value to the total
return total
if __name__ == "__main__":
userIn = input("Enter the word/Sentence you want to encrypt:")
a = input("Enter a password with which you would like to encrypt your message:")
print(userIn)
main(userIn, a)
And here is my function library file:
import os
DEBUG = True
def printdebug(log: object) -> object:
if DEBUG:
print(log)
def loading(sec=10):
start = 1
input("Press Enter to continue")
printdebug("loading...")
while start <= sec:
printdebug("...")
start += 1
def codepause():
os.system("Pause")
input("press enter to continue")
def listtoint(msglst):
# Conversion from list to int
"""
>>> listtoint([1,2,3,4,5,6,7,8,9,0])
1234567890
"""
ncryptedkey = 0
base = 10
for d in msglst:
ncryptedkey = base * ncryptedkey + d
# printDebugJob:
printdebug("The encrypted message is:" + str(ncryptedkey))
return ncryptedkey
def convdecimal(userin):
rank = len(userin)
total = 0
for character in userin:
rank -= 1 # decreasing the letter rank by one
letter = ord(character)
if letter < 32:
pass
elif letter == 27:
pass
else:
rankmult = 255 ** rank # Making a multiplier
lettervalue = letter * rankmult # Multiplying the letter by this multiplier
total += lettervalue # Adding the letter's value to the total
def letterprint(nb):
nb = chr(nb)
print(nb, end='')
Thanks Already!
I've not tested this, but it looks like you need to swap the greater than sign for greater than or equals, as it's probably going 1 index too high.
if scrtrankcounter >= len(scrtlst):
scrtrankcounter = 0
currentscrtrank += 1 + scrtlst[scrtrankcounter]
For example, if scrtlst has a length of 5, the highest index is 4, so it'll give an error if you try scrtlst[5].