The idea is to create a triangle, surrounded in *'s while the $ signs, spaces and height of the triangle are all user inputs.
For example, with height = 9, $=5 and spaces = 2, this should produce the following output:
*
*$*
*$$$*
*$ $$*
*$$$ $$*
*$$$ $$$$*
*$ $$$$$ $*
*$$$$ $$$$$ *
*****************
I tried a couple of different approaches, like stringing the $'s and spaces together and printing by their index, or counting how many times each was printed and not overlapping.
However, I couldn't manage to find anything that worked :(
Any help is appreciated :) just a first semester at CS
My code:
height = int(input('Enter height: '))
numSigns = int(input('Enter number of $: '))
numSpaces = int(input('Enter number of spaces: '))
signCounter = 0
spaceCounter = 0
sign = '$'
row = (sign*numSigns + ' '* numSpaces)*height
count1 = 0
count2 = 0
x =1
for i in range(height):
for j in range(height - i - 1):
print(" ", end = '')
print('*',end = '')
if i == 0:
print()
p = x
x = x + i - 1
for a in range(p,x):
print(row[a], end = '')
if i != 0:
print('*')
Actual output:
Enter height: 9
Enter number of $: 5
Enter number of spaces: 2
*
**
*$*
*$$*
*$$ *
* $$$*
*$$ $*
*$$$$ *
*$$$$$ *
Let's see over what logic it works. You will find logic at last.
1st.
How to create left-side star pattern like this :
*
*
*
*
First thing is how many spaces on the left of each star is equal to TOTAL_HEIGHT_OF_PATTERN - CURRENT_HEIGHT_STATUS. for given example let's take 2nd-line so:
TOTAL_HEIGHT_OF_PATTERN = 4
CURRENT_HEIGHT_STATUS = 2
NUMBER_OF_SPACE_ON_LEFT = TOTAL_HEIGHT_OF_PATTERN - CURRENT_HEIGHT_STATUS = 2
2nd.
How to create `$` and `space` pattern like this in between:
*
*$*
*$$$*
* $$$*
*$$$$$ *
*$$$$$ $$*
*$$$$$ $ $*
*$$$ $$$$$$*
How many spaces at given height, for above system it is found.
spaces:0 for height # 1, 2, 3
spaces:1 for height # 4, 5, 6
spaces:2 for height # 7, 8
we can see a pattern found such that at every height (CURRENT_HEIGHT_STATUS-1)//3 no of space will found.
For NO_OF_DOLLORS we can see it equal to 2*(CURRENT_HEIGHT_STATUS-NO_OF_SPACES)-3 finally by using shuffling operation we can shuffle dollor and spaces
Check out this code:
from random import shuffle
height = int(input('Height : '))
doller = int(input('Dollor : '))
spaces = int(input('Spaces : '))
for i in range(1,height+1):
no_spaces = (i-1)//3
str_ = ['$' for i in range(2*(i-no_spaces)-3)]+[' ']*no_spaces
shuffle(str_)
if i == 1:
print(' '*(height-i) + '*')
elif i != height and i != 1:
print(' '*(height-i) + '*' + ''.join(str_) + '*')
else:
print('*'*(2*height-1))
OUTPUT :
Height : 9
Dollor : 2
Spaces : 5
*
*$*
*$$$*
*$$ $*
*$$ $$$*
*$$$$$$ $*
* $$$$$$$*
*$$ $$$$$$$ *
*****************
Instead of completely using loop let's divide them in procedural code. Logic is similar to my previous solution. For making particular enclose-string we can use make_str function who logic revolves around the remaining number of $
height = int(input('Height : '))
doller = int(input('Dollor : '))
spaces = int(input('Spaces : '))
def make_str(rem, len_str):
x = 0
s = ''
for _ in range(len_str):
if rem >0:
s += '$'
rem -= 1
else:
s += ' '
x += 1
if x == spaces:
x = 0
rem = 5
return (rem, s)
rem_dollor = doller
for i in range(1,height+1):
num = 2*(i)-3
rem_dollor, str_ = make_str(rem_dollor, num)
if i == 1:
print(' '*(height-i) + '*')
elif i != height and i != 1:
print(' '*(height-i) + '*' + str_ + '*')
else:
print('*'*(2*height-1))
**OUTPUT: **
Height : 9
Dollor : 4
Spaces : 3
*
*$*
*$$$*
* $$*
*$$$ $*
*$$$$ $$*
*$$$ $$$$$*
* $$$$$ $$*
*****************
Related
This code prints out a hollow rectangle with a given width and height using stars(*), but instead of printing each segment at a time I need to modify it or create a code that will create a single string that when printed produces the same output as the code above.
def print_rectangle(width, height):
for p in range(1):
print("*" * width)
for i in range(height - 2):
for i in range((width + 1) - width):
print("*", end='')
for n in range(width - 2):
print(" ", end='')
for j in range((width + 1) - width):
print("*", end='')
print("")
print("*" * width)
You need to create a variable, that saves the substrings, than print out the whole string, like this:
def print_rectangle(width, height):
tmp_str = ""
for p in range(1):
tmp_str = "*"*width+'\n'
for i in range(height-2):
for i in range((width+1)-width):
tmp_str += "*"
for n in range(width-2):
tmp_str += " "
for j in range((width+1)-width):
tmp_str += "*"
tmp_str += '\n'
tmp_str += "*"*width+'\n'
print(tmp_str)
print_rectangle(4, 5) #or any other numbers
The question has already been answered of how to correct your own code to make the rectangle, so here is a totally different way to accomplish the same thing:
def rectangle(width: int, height: int) -> str:
top_bottom = "*" * width
middle = "\n*" + (" " * (width - 2)) + "*"
rect = top_bottom
for _ in range(height - 2):
rect += middle
if height > 1:
rect += "\n" + top_bottom
return rect
print(rectangle(10, 5))
Output:
**********
* *
* *
* *
**********
You could build the lines into a list then join them for a single print operation. Here's an example:
width = 5
height = 6
t = ['*' * width + '\n']
m = '*' + ' ' * (width-2) + '*\n'
t.extend(m * (height - 2))
print(''.join(t+[t[0]]), end='')
Output:
*****
* *
* *
* *
* *
*****
I need my program to generate as many playing fields as the entered number of players playing the game. Currently it only generates 1 field. Cant wrap my head around this one.
s = int(input("Sisesta mängijate arv: "))
b = int(input("Sisesta väjaku suurus: "))
b = b + 1
bb = b
c = int(input("Sisesta korrutustabeli suurus: "))
for s in range (1 , s+1):
numberolemas = ['0']
t.write(str(s) + ". väljak \n\n")
print(str(s) + ". väljak \n")
for bb in range (1 , bb):
for b in range (1 , b):
import random
number = random.randint(1, c) * random.randint(1, c)
olemas = True
while olemas:
number = random.randint(1, c) * random.randint(1, c)
if number not in numberolemas:
olemas = False
t.write(str(number))
print(str(number), end = ' ')
if number <= 9:
t.write(" ")
print(" ", end = '')
elif number >= 100:
t.write(" ")
print(" ", end = '')
else: t.write(" ") and print(" ", end = '')
numberolemas.append(number)
b = b + 1
t.write("\n\n")
print(" ")
bb = bb + 1
print(" ")
t.close() ```
Let's say the user inputs an integer h where h >= 0.
SAMPLE INPUT:
1
SAMPLE OUTPUT:
*
SAMPLE INPUT:
3
SAMPLE OUTPUT:
*
***
*****
This is my code. However, I can't seem to properly align the asterisks to make a proper triangle.
n = int(input())
def triangle(n):
a = n
b = 0
c = 1
for i in range(0, n):
for j in range(0, a):
print(end=" ")
a = a - 1
for k in range (0, i):
print("*"*(c+b), end=" ")
print("\r")
b = b + 1
c = c + 1
print(triangle(n))
Here is a slightly different approach where you utilize the fact that for each row, the number of stars will be, 2 * row - 1:
def print_triangle(height: int) -> None:
base = 2 * height - 1
for row in range(1, height + 1):
num_stars = 2 * row - 1
num_left_spaces = (base - num_stars) // 2
for _ in range(num_left_spaces):
print(" ", end="")
for _ in range(num_stars):
print("*", end="")
print()
def get_int_input(prompt: str) -> int:
while True:
try:
return int(input(prompt))
except ValueError:
print("Error: Enter an integer, try again...")
n = get_int_input("Enter the height of the triangle: ")
print_triangle(n)
Example Usage 1:
Enter the height of the triangle: 1
*
Example Usage 2:
Enter the height of the triangle: 3
*
***
*****
Example Usage 3:
Enter the height of the triangle: 5
*
***
*****
*******
*********
def triangle(n):
k = 2 * n - 2
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i + 1):
print("* ", end="")
print("\r")
n = int(input("Enter value:"))
triangle(n)
visit below link for more info
https://www.geeksforgeeks.org/programs-printing-pyramid-patterns-python/
n = int(input())
def triangle(n):
for i in range(0, n):
space_count = n-i-1
asterisk_count = n-space_count+i
print("{0}{1}".format(
" " * space_count,
"*" * asterisk_count)
)
triangle(n)
Sample Output:
10
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
After copying the code above, run the following:
echo '#!/usr/bin/env python\n\n'"$(pbpaste)" > /tmp/triangulo.py && \
chmod +x /tmp/triangulo.py && \
for i in {0..20}; do; \
/tmp/triangulo.py <<< $i; \
done;
Whilst attempting CS50's PSET6, I was trying to create a double-half pyramid of a size specified by the user.
The pyramid is fine but there's a random new line after the user input and before the pyramid starts. How can I fix it? Any help is appreciated :D
The code is as follows
def main():
hashHeight = height()
create(hashHeight)
# get height
def height():
h = int(input("Height: "))
if h >= 1 and h <= 8:
return h
else:
height()
#print hash
def create(x):
for i in range(x + 1):
print(" " * (x - i) + "#" * i + " " + "#" * i)
main()
def main():
hashHeight = height()
create(hashHeight)
# get height
def height():
h = int(input("Height: "))
if h >= 1 and h <= 8:
return h
else:
height()
#print hash
def create(x):
for i in range(1, x + 1):
print(" " * (x - i) + "#" * i + " " + "#" * i)
main()
I am trying to get this python script to create a new file and continue generating word combinations once a certain file size is reached.
f=open('wordlist', 'w')
def xselections(items, n):
if n==0: yield []
else:
for i in xrange(len(items)):
for ss in xselections(items, n-1):
yield [items[i]]+ss
# Numbers = 48 - 57
# Capital = 65 - 90
# Lower = 97 - 122
numb = range(48,58)
cap = range(65,91)
low = range(97,123)
choice = 0
while int(choice) not in range(1,8):
choice = raw_input('''
1) Numbers
2) Capital Letters
3) Lowercase Letters
4) Numbers + Capital Letters
5) Numbers + Lowercase Letters
6) Numbers + Capital Letters + Lowercase Letters
7) Capital Letters + Lowercase Letters
: ''')
choice = int(choice)
poss = []
if choice == 1:
poss += numb
elif choice == 2:
poss += cap
elif choice == 3:
poss += low
elif choice == 4:
poss += numb
poss += cap
elif choice == 5:
poss += numb
poss += low
elif choice == 6:
poss += numb
poss += cap
poss += low
elif choice == 7:
poss += cap
poss += low
bigList = []
for i in poss:
bigList.append(str(chr(i)))
MIN = raw_input("What is the min size of the word? ")
MIN = int(MIN)
MAX = raw_input("What is the max size of the word? ")
MAX = int(MAX)
for i in range(MIN,MAX+1):
for s in xselections(bigList,i): f.write(''.join(s) + '\n')
You can encapsulate the file rotation behavior in a class. When you are writing some data, the write method will first check if the write would exceed the file size limit; then it calls the rotate method which closes the current file and opens a new one, incrementing the sequence number on the filename:
import os
class LimitWriter(object):
def __init__(self, basepath, bytelimit):
self._basepath = basepath
self._bytelimit = bytelimit
self._sequence = 0
self._output = None
self._bytes = 0
self._rotate()
def _rotate(self):
if self._output:
self._output.close()
path = '%s.%06d' % (self._basepath, self._sequence)
self._output = open(path, 'wb')
self._bytes = 0
self._sequence += 1
def write(self, data):
size = len(data)
if (self._bytes + size) > self._bytelimit:
self._rotate()
self._bytes += size
self._output.write(data)
out = LimitWriter('wordlist', 1024 * 1024 * 1)
for i in range(MIN,MAX+1):
for s in xselections(bigList,i):
out.write(''.join(s) + '\n')
Would output a series of files which are smaller than 1MB:
1.0M wordlist.000000
1.0M wordlist.000001
252K wordlist.000002
Update - A few more tips on using some of the built-in power of Python to help make your code a bit shorter and easier to follow. I've included comments explaining each part.
Here are the docs on the modules I use below: itertools, string.
import itertools
import os
from string import digits, lowercase, uppercase
# PUT LimitWriter CLASS DEFINITION HERE
LIMIT = 1024 * 1024 * 1
choice = 0
while int(choice) not in range(1,8):
choice = raw_input('''
1) Numbers
2) Capital Letters
3) Lowercase Letters
4) Numbers + Capital Letters
5) Numbers + Lowercase Letters
6) Numbers + Capital Letters + Lowercase Letters
7) Capital Letters + Lowercase Letters
: ''')
MIN = int(raw_input("What is the min size of the word? "))
MAX = int(raw_input("What is the max size of the word? "))
# replace your ranges and large if/else with this
choices = {
1: digits,
2: uppercase,
3: lowercase,
4: uppercase + lowercase,
5: digits + lowercase,
6: digits + uppercase + lowercase,
7: uppercase + lowercase
}
# pick one of the sets with the user's choice
chars = choices[int(choice)]
out = LimitWriter('wordlist', LIMIT)
# generate all permutations of the characters from min to max
for length in range(MIN, MAX+1):
for tmp in itertools.permutations(chars, length):
out.write(''.join(tmp) + '\n')
Here's the final working code. Change the variable mbXY inside function generate_wordlist to establish the size cap of each file provided it gets bigger than this size. This file has been updated to run under Python 3.2
import itertools
import subprocess
import os
from string import digits, ascii_lowercase, ascii_uppercase, punctuation
if os.name == 'nt':
def clear_console():
subprocess.call("cls", shell=True)
return
else:
def clear_console():
subprocess.call("clear", shell=True)
return
def generate_phone_numbers(area_code):
f = open('phones.txt', 'w')
for i in range(2010000, 9999999):
f.write(area_code + str(i) + '\n')
def generate_wordlist(lst_chars, min_digit, max_digit, lst_name):
mb1 = 1024000
mb10 = 1024000 * 10
mb100 = 1024000 * 100
mb250 = 1024000 * 250
mb500 = 1024000 * 500
gb1 = 1024000 * 1000
file_size_limit = mb10
out = file_writer(lst_name, file_size_limit)
for curr_length in range(min_digit, max_digit + 1):
for curr_digit in itertools.product(lst_chars, repeat=curr_length):
out.write(''.join(curr_digit) + '\n')
class file_writer(object):
def __init__(self, basepath, bytelimit):
self._basepath = basepath
self._bytelimit = bytelimit
self._sequence = 0
self._output = None
self._bytes = 0
self._rotate()
def _rotate(self):
if self._output:
self._output.close()
path = '%s.%06d' % (self._basepath, self._sequence)
self._output = open(path, 'wb')
self._bytes = 0
self._sequence += 1
def write(self, data):
size = len(data)
if (self._bytes + size) > self._bytelimit:
self._rotate()
self._bytes += size
self._output.write(bytes(data, "utf-8"))
choice = 0
while int(choice) not in range(1,6):
clear_console()
print ('')
print (' wgen - Menu')
choice = input('''
1. Phone numbers.
2. Numbers.
3. Numbers + Lowercase.
4. Numbers + Lowercase + Uppercase.
5. Numbers + Lowercase + Uppercase + Punctuation.
Enter Option: ''')
print ('')
choice = int(choice)
if choice == 1:
area_code = input('''
Please enter Area Code: ''')
area_code = str(area_code)
area_code = area_code.strip()
if len(area_code) == 3:
print ('')
print (' Generating phone numbers for area code ' + area_code + '.')
print (' Please wait...')
generate_phone_numbers(area_code)
if choice == 2:
min_digit = input(' Minimum digit? ')
min_digit = int(min_digit)
print ('')
max_digit = input(' Maximum digit? ')
max_digit = int(max_digit)
lst_chars = digits
lst_name = 'num'
print ('')
print (' Generating numbers between ' + str(min_digit) + ' and ' + str(max_digit) + ' digits.')
print (' Please wait...')
generate_wordlist(lst_chars, min_digit, max_digit, lst_name)
if choice == 3:
min_digit = input(' Minimum digit? ')
min_digit = int(min_digit)
print ('')
max_digit = input(' Maximum digit? ')
max_digit = int(max_digit)
lst_chars = digits + ascii_lowercase
lst_name = 'num_low'
print ('')
print (' Generating numbers & lowercase between ' + str(min_digit) + ' and ' + str(max_digit) + ' digits.')
print (' Please wait...')
generate_wordlist(lst_chars, min_digit, max_digit, lst_name)
if choice == 4:
min_digit = input(' Minimum digit? ')
min_digit = int(min_digit)
print ('')
max_digit = input(' Maximum digit? ')
max_digit = int(max_digit)
lst_chars = digits + ascii_lowercase + ascii_uppercase
lst_name = 'num_low_upp'
print ('')
print (' Generating numbers, lowercase & uppercase between ' + str(min_digit) + ' and ' + str(max_digit) + ' digits.')
print (' Please wait...')
generate_wordlist(lst_chars, min_digit, max_digit, lst_name)
if choice == 5:
min_digit = input(' Minimum digit? ')
min_digit = int(min_digit)
print ('')
max_digit = input(' Maximum digit? ')
max_digit = int(max_digit)
lst_chars = digits + ascii_lowercase + ascii_uppercase + punctuation
lst_name = 'num_low_upp_pun'
print ('')
print (' Generating numbers, lowercase, uppercase & punctuation between ' + str(min_digit) + ' and ' + str(max_digit) + ' digits.')
print (' Please wait...')
generate_wordlist(lst_chars, min_digit, max_digit, lst_name)