How would you print a tree in python so it looks like the following:
/\
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
The height should be changeable.
def tree(n):
treeStr = ""
for i in range(0,n):
level = " "*(n-i) + "/" + " "*(2*i) + "\\"
treeStr += level.center(n+1) + "\n"
print(treeStr)
tree(10);
Related
My scraper bot working normally till I add merchant column in database. Scraper.py file scraping success merchant and recorded in database correctly but compare bot not compare after add merchant column
My original code:(compare success)
# The max_date a product can have in order to be considered "old"
limit = datetime.datetime.strptime(products[-1][1], "%Y-%m-%d %H:%M:%S.%f") + \
datetime.timedelta(minutes=OLDER_PRODUCTS_RANGE)
# Separate "old" from "new" products
for i, product in enumerate(products[::-1]):
date = datetime.datetime.strptime(
product[1], "%Y-%m-%d %H:%M:%S.%f")
index = len(products) - i - 1
if date > limit:
old_products = products[index+1:]
new_products = products[:index+1]
break
# If we have only one or even none of the lists, return
if len(new_products) == 0 or len(old_products) == 0:
c.close()
self.save_db(db)
return True
older_product = min(old_products, key=lambda x: x[5])
current_product = min(new_products, key=lambda x: x[5])
first_price = older_product[5]
current_price = current_product[5]
current_date = current_product[1]
url = current_product[6]
price_difference = first_price - current_price
percentage = price_difference / first_price
percentage_str = str("%.2f" % (percentage * 100))
# If the drop in the price was greater then the expected percentage, warn the user
if percentage >= self.percentage:
rowid = current_product[0]
product_name = current_product[4]
product_id = current_product[3]
print(
f"[Bot] [{current_date}] Price of \"{product_name}\" is {percentage_str}% off")
message = product_name + "\n\n" + \
str(first_price) + " TL >>>> " + \
str(current_price) + f" TL - {percentage_str}%" + "\n\n" + \
MAIN_URL + url + "\n\n" + \
MAIN_URL + "ara?q=" + product_id
context.bot.send_message(
chat_id=CHANNEL_ID,
text=message
)
c.execute(
"INSERT INTO deleted SELECT rowid FROM products WHERE product_id = %s AND rowid != %s;",
(product_id, rowid)
)
c.close()
self.save_db(db)
return True
My edited Code: (doesnt price compare)
# The max_date a product can have in order to be considered "old"
limit = datetime.datetime.strptime(products[-1][1], "%Y-%m-%d %H:%M:%S.%f") + \
datetime.timedelta(minutes=OLDER_PRODUCTS_RANGE)
# Separate "old" from "new" products
for i, product in enumerate(products[::-1]):
date = datetime.datetime.strptime(
product[1], "%Y-%m-%d %H:%M:%S.%f")
index = len(products) - i - 1
if date > limit:
old_products = products[index+1:]
new_products = products[:index+1]
break
# If we have only one or even none of the lists, return
if len(new_products) == 0 or len(old_products) == 0:
c.close()
self.save_db(db)
return True
older_product = min(old_products, key=lambda x: x[5])
current_product = min(new_products, key=lambda x: x[5])
first_price = older_product[5]
current_price = current_product[5]
current_date = current_product[1]
url = current_product[6]
merchant = current_product[7]
price_difference = first_price - current_price
percentage = price_difference / first_price
percentage_str = str("%.2f" % (percentage * 100))
# If the drop in the price was greater then the expected percentage, warn the user
if percentage >= self.percentage:
rowid = current_product[0]
product_name = current_product[4]
product_id = current_product[3]
print(
f"[Bot] [{current_date}] Price of \"{product_name}\" is {percentage_str}% off")
message = product_name + "\n\n" + \
+ "Satici Adi:" + merchant + "\n\n" + \
str(first_price) + " TL >>>> " + \
str(current_price) + f" TL - {percentage_str}%" + "\n\n" + \
MAIN_URL + url + "?magaza=" + merchant + "\n\n" + \
MAIN_URL + "ara?q=" + product_id
context.bot.send_message(
chat_id=CHANNEL_ID,
text=message
)
c.execute(
"INSERT INTO deleted SELECT rowid FROM products WHERE product_id = %s AND rowid != %s;",
(product_id, rowid)
)
c.close()
self.save_db(db)
return True
I use python with beautifulsoup4
Whats wrong?
I suppose the problem is you have extra + symbol here:
message = product_name + "\n\n" + \
+ "Satici Adi:" + merchant + "\n\n" + \
str(first_price) + " TL >>>> " + \
str(current_price) + f" TL - {percentage_str}%" + "\n\n" + \
MAIN_URL + url + "?magaza=" + merchant + "\n\n" + \
MAIN_URL + "ara?q=" + product_id
You should replace it by:
message = product_name + "\n\n" + \
"Satici Adi:" + merchant + "\n\n" + \
str(first_price) + " TL >>>> " + \
str(current_price) + f" TL - {percentage_str}%" + "\n\n" + \
MAIN_URL + url + "?magaza=" + merchant + "\n\n" + \
MAIN_URL + "ara?q=" + product_id
I am working with this code so I have my main code here:
from draw_image import Images
start = Images()
start.display_image()
start.delete_line()
start.display_image()
and this is my draw_image code:
class Images:
def image(jumper_image):
"""This function is to create the list"""
jumper_image = []
def display_image(jumper_image):
"""This is how the user will see the image correctly through the loop"""
jumper_image = [
" ___ ",
" /___\ ",
" \ / ",
" \ / ",
" o ",
" /|\ ",
" / \ ",
" ",
"^^^^^^^^^^^"
]
for image in jumper_image:
print(image)
return jumper_image
def delete_line(jumper_image):
""" This function is supposed to delete the first line of the jumper_image"""
jumper_image.pop(0)
It seems that the delete_line function is not recognizing the list, do you guys have any idea why this is happening? or what would be a solution for this problem?
I would recommend using a python constructor to initialize jumper_image:
class Images:
def __init__(self):
self.jumper_image = [
" ___ ",
" /___\ ",
" \ / ",
" \ / ",
" o ",
" /|\ ",
" / \ ",
" ",
"^^^^^^^^^^^"
]
def display_image(self):
"""This is how the user will see the image correctly through the loop"""
for image in self.jumper_image:
print(image)
def delete_line(self):
""" This function is supposed to delete the first line of the jumper_image"""
self.jumper_image.pop(0)
start = Images()
start.display_image()
start.delete_line()
print('After deleting first value in list\n')
start.display_image()
___
/___\
\ /
\ /
o
/|\
/ \
^^^^^^^^^^^
After deleting first value in list
/___\
\ /
\ /
o
/|\
/ \
^^^^^^^^^^^
So, I'm pretty new to python, but I'm currently coding a text-adventure game. I was wondering how I would be able to display the text at the bottom of the screen while an ASCII image is displayed on top, just like SanctuaryRPG.
Alright, so basically, you want to print an ASCII image with text. This shouldn't be too difficult.
Firstly, set the ASCII image to a variable. For example:
img = '''
__,__
.--. .-" "-. .--.
/ .. \/ .-. .-. \/ .. \
| | '| / Y \ |' | |
| \ \ \ 0 | 0 / / / |
\ '- ,\.-"`` ``"-./, -' /
`'-' /_ ^ ^ _\ '-'`
.--'| \._ _./ |'--.
/` \ \ `~` / / `\
/ '._ '---' _.' \
/ '~---~' | \
/ _. \ \
/ .'-./`/ .'~'-.|\ \
/ / `\: / `\'. \
/ | ; | '.`; /
\ \ ; \ \/ /
'. \ ; \ \ ` /
'._'. \ '. | ;/_
/__> '. \_ _ _/ , '--.
.' '. .-~~~~~-. / |--'`~~-. \
// / .---'/ .-~~-._/ / / /---..__.' /
((_(_/ / / (_(_(_(---.__ .'
| | _ `~~`
| | \'.
\ '....' |
'.,___.'
'''
Next, set the text you want to print out to another variable.
text = "Do you want to say hi to the monkey?"
Finally, print the two like this:
print(img)
print(text)
OR:
print(img + "\n\n" + text)
\n Just means a new line.
To do the same as in SanctuaryRPG with Pygame, you need to use a font where each character is the same width (e.g. Courier):
font = pygame.font.SysFont("Courier", text_height)
Split the text into lines with splitlines() (see How to split a python string on new line characters):
img_text = img.splitlines()
Render the text line by line in a loop:
for i, line in enumerate(img_text):
text_surf = font.render(line, True, (255, 255, 0))
window.blit(text_surf, (50, 20 + i * text_height))
Use the following function:
def renderTextImage(surf, font, text, x, y, color):
img_text = text.splitlines()
for i, line in enumerate(img_text):
text_surf = font.render(line, True, color)
surf.blit(text_surf, (x, y + i * text_height))
Minimal example:
repl.it/#Rabbid76/PyGame-AsciiTextImage
import pygame
img_text = r'''
__,__
.--. .-" "-. .--.
/ .. \/ .-. .-. \/ .. \
| | '| / Y \ |' | |
| \ \ \ 0 | 0 / / / |
\ '- ,\.-"`` ``"-./, -' /
`'-' /_ ^ ^ _\ '-'`
.--'| \._ _./ |'--.
/` \ \ `~` / / `\
/ '._ '---' _.' \
/ '~---~' | \
/ _. \ \
/ .'-./`/ .'~'-.|\ \
/ / `\: / `\'. \
/ | ; | '.`; /
\ \ ; \ \/ /
'. \ ; \ \ ` /
'._'. \ '. | ;/_
/__> '. \_ _ _/ , '--.
.' '. .-~~~~~-. / |--'`~~-. \
// / .---'/ .-~~-._/ / / /---..__.' /
((_(_/ / / (_(_(_(---.__ .'
| | _ `~~`
| | \'.
\ '....' |
'.,___.'
'''
def renderTextImage(surf, font, text, x, y, color):
img_text = text.splitlines()
for i, line in enumerate(img_text):
text_surf = font.render(line, True, color)
surf.blit(text_surf, (x, y + i * text_height))
pygame.init()
window = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
text_height = 16
font = pygame.font.SysFont("Courier", text_height)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(0)
renderTextImage(window, font, img_text, 50, 20, (255, 255, 0))
pygame.display.flip()
pygame.quit()
exit()
I'm trying to print the following image via python
print("""
____
.\ /
|\\ //\
/ \\// \
/ / \ \
/ / \ \
/ / \ \
/ /______^ \ \
/ ________\ \ \
/ / \ \
/\\ / \ //\
/__\\_\ /_//__\
""")
input()
output
____
.\ /
|\ // / \// / / \ / / \ / / \ \
/ /______^ \ / ________\ \ / / \ /\ / \ ///__\_\ /_//__
hope someone can help me solve this problem
Backslashes escape the newlines, change it to a raw string with r"...":
print(r"""
____
.\ /
|\\ //\
/ \\// \
/ / \ \
/ / \ \
/ / \ \
/ /______^ \ \
/ ________\ \ \
/ / \ \
/\\ / \ //\
/__\\_\ /_//__\
""")
input()
I'm working on a Python 3 script that among other things, at some point it needs to create a .JKS or .P12 keystore. I use to have a bash script that used keytool for this:
keytool -genkey -keyalg RSA -alias certAlias \
-keystore keystore.jks -storepass $keyPass \
-validity 360 -keysize 2048 \
-noprompt -dname "CN=com.myCompany, OU=ID, O=AwesomeSoft, L=SF, S=CA, C=US" \
-keypass $keyPass
mv ./keystore.jks src/main/resources/
Now i'm moving the same functionality from that bash script to python and I having some issues to figure it out and any pointer will ne more than welcome.. you may noticed that the example above is for jks, not p12... the newer version have to be able to, depending on a variable before called certType with create one or the other... or create a jks and later convert it to p12... i'm open to options..
Thanks in advance!!
Found my answer:
import os
certAlias = 'cert'
certAlg = 'RSA'
certSigAlg = 'SHA1withRSA'
certExp = '365'
certKeySize = '2048'
certKeyType = 'PKCS12' # Select PKCS12 or JKS
certKeyPass = 'password123'
fileName = 'keystore'
dname = 'CN=mySite.com'
#
if certKeyType == "PKCS12":
fileExt = 'p12'
elif certKeyType == "JKS":
fileExt = 'jks'
certFile = fileName + '.' + fileExt
keytool = 'keytool -genkey -noprompt \
-alias ' + certAlias + ' \
-keypass ' + certKeyPass + ' \
-keyalg ' + certAlg + ' \
-sigalg ' + certSigAlg + '\
-validity ' + certExp + ' \
-dname ' + dname + ' \
-keysize ' + certKeySize + ' \
-keystore ' + certFile + ' \
-storepass '+ certKeyPass +' \
-storetype ' + certKeyType
os.system(keytool)
I did this and works but I will be playing to add more logic... hope it helps anyone.