Python Homework - creating a pattern that also has spaces - python

Problem: Write a program that creates a pattern like the one below. Let the user input a non-negative integer to determine the number of lines of the pattern.
The sample output would take input, then have one blank line, then each next line would have a # (space) #, with increasing amount of spaces as count continues.
Example, entering the number 4 would produce one empty line; two pounds on the second line; one pound, one space, one pound on the third line; one pound, two spaces, one pound on the last line.
lines = int(input("Enter number of lines for pattern: "))
for a in range(lines):
for b in range(a + 1):
print('#', end='')
print()
Above code gives me close to what I want, but it is pounds all across instead of spaces between the two pound signs. I have no idea how to put the spaces there, any help would be awesome.

You can format the output with a variable width:
lines = int(input("Enter number of lines for pattern: "))
for a in range(lines):
print('#%*s' % (a, '#') if a else '')
This outputs:
(blank line)
##
# #
# #

Or try:
for a in range(lines):
print('#%s#' % ((a-1)*' ') if a else '')
Example output:
Enter number of lines for pattern: 4
##
# #
# #

Related

Regex: inputs exactly 4 digits, check whether the inputted number appears in the first 10,000 characters

Anyone can please check my code?
When the user inputs exactly 4 digits, check whether the inputted number appears in the first 10,000 characters (after the decimal) of the text file(which name is "square root of 2.txt") and tell the user its position using .find() method.
Make a new file called inputted_number.txt. Modify the code so that all the valid input is saved in that file. The contents of that file should look something like this:
3210
3222
4771
I don' know how to use re.find(), is that re.search? My codes below:
#import my file
myfile = open("sqroot2_10kdigits.txt")
txt = myfile.read()
myfile.close()
# while True block use re.find
while True:
try:
number = str(input("Enter four digits: "))
int(number)
if re.findall(r'\d\d\d\d',txt)) == True:
print(f'The digits {int(number} appear in the first 10,000 characters of the square root of 2.' )
print(f'They appear starting on the {starting position}th character after the decimal.' )
else :
print(f'Sorry, the digits {int(number)} do not appear in the first 10,000 characters of the square root of 2.')
#NO.5 make a new file
with open('inputted_number.txt.', 'w') as filehandle:
filehandle.write('\n')
Anyone can check my code please!
For what you are describing you do not need a regex.
txt = '2319871325876234897034589734527861' \
'3098623409862349856243598672354897' \
'2348776623534078459996505467097201'
while True:
number = input("Enter four digits (q to quit): ")
if number.lower() == 'q':
break
elif len(number) != 4 or not number.isdigit():
print("Please enter four numbers")
continue
pos = txt.find(number)
if pos > -1:
print(
f'The digits {number} appear in the first '
'10,000 characters of the square root of 2.'
f'They appear starting on the {pos}th '
'character after the decimal.'
)
else:
print(
f'Sorry, the digits {number} do not appear '
'in the first 10,000 characters of the '
'square root of 2.'
)
Among the changes:
use str.find not a regex
no need to cast the string as either a str or an int
casting as an int will cause trouble with say 0001
added some basic validation, length and digits

Write a function called justify that takes a list of strings and a filed size then returns a single string

Write a function called justify that takes a list of strings and a filed size then returns a single string. The return string will have the original words spaced out in a string of length size. e.g.
justify([“this”, “is”, “a”, “test”],20) à “this is a test”
We are putting 11 characters in a 20 space field, so we have 9 extra spaces. There are 3 places between the words, so we have 3 spaces between each word. If the extra spaces do not divide exactly you can distribute the extra spaces as you like.
'justify([“all”, “too”, “easy”],15) à “all too easy”'
If the field size is too small to add one space between the words then ignore the field size and return the answer with one space between each word.
def justify(x,y):
amount = len(x)-1
final = "".join(x)
ohmy = len(final)
spaces = y - ohmy
real = spaces / amount
print(real)
just = []
length = int(input("length: "))
while True:
hi = input("word: ")
if hi == "end":
break
else:
just.append(hi)
justify(just,length)
This is what I have? Any help?
Seems like you need to
calculate the space taken up by all the words/strings;
find the difference between the limit and the space taken by the words;
divide that difference by the number of gaps between words;
use that result to decide where and how many spaces to put between the words;
construct a string with the words and the spaces.
add logic to check if length of words is greater than field space and react to that

Putting multiple numbers from an input into one list

I'm trying to put multiple interest rates from one input into a list. I'm assuming just putting a comma between them wont separate them into different variables in the list? Is there a way I can get them all into a list in one input or do i need to run the input multiple times and add one each time?
interest_rates_list = []
while True:
investment = input("Please enter the amount to be invested ")
periods = input("Please enter the number of periods for investment maturity ")
if int(periods) < 0:
break
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list.append(interest_rates)
If you input is something like:
4 5 12 8 42
then you can simply split it up by space and assign to values list:
values = input().split()
If your input something like 4,5,12, then you need to use split(',').
You can split the input string into several string and then convert it to float. This can be done in one line.
interest_rates = list(map(float, interest_rates.split(",")))
Here I go a step further, your next move will be to calculate some return based on interest rates, and so you will need float/integer to do so.
The python string function split can accept a delimiter character and split the input string into a list of values delimited by that character.
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list = interest_rates.split(",")
If you take the input, you can convert it to a string by using:
str(interest_rates)
Let this be variable A
So, A = str(interest_rates)
Now, to seperate each entry of the interest rates, we do:
interest_rates_list = A.split(' ')
This function literally splits the string at all spaces and returns a list of all the broken pieces.
NOTE: if you do A.split(*any string or character*) it'll split at the mentioned character. Could be ',' or ';' or ':', etc.
Now you can iter over the newly formed list and convert all the numbers stored as string to ints or floats by doing
for i in interest _rates_list:
i = float(i) #or int(i) based on your requirement

Multiple strings to align

So here is my problem, I have this program that is supposed to print multiple lines of numbers according to the number of columns and spaces the user inputs:
def main():
from string import Template # We import the Template method as seen in python glossary 7.1.4
s_num, e_num = [int(x) for x in input("Please enter a starting number and an ending number separated by a comma: ").split(',')] #We define the variables, s_num and e_num, as the respective starting point and ending point of the range that the user will input. In addition we call the int() function to make sure the input is an integer.
column, space = [int(x) for x in input("Please enter the number of numbers printed on a row and the number of spaces per item separated by a comma: ").split(',')] #We define the variables, column and space, as the respective amount of rows and amount of spaces that the user will input. In addition we call the int() function to make sure the input is an integer.
print('------------------------------') # We print a line of indents as in the sample
print('\n')
print ('Your print-out of numbers {}-{} using {} colums and {} spaces between numbers:'.format(s_num, e_num, column, space)) #We use the format method to implement the four variables created in the line and including them in the string phrase.
a = Template('$spce') # We create a variable "a" with one template "spce" that we will modify afterwards to implement in it the number of spaces that the user has inputted.
b = a.substitute(spce = ' ' * (space)) # We create a second variable b that will substitute the template "spce" with the number of spaces, by multipling the integers in the space variable by, ' ', a normal space.
counter = 1 # We create a variable called counter that will count the number of lines, in order to know when to go back to line.
for i in range(s_num,e_num + 1): # We invoke a "for" loop in the range of numbers inputted by the user. In addition we add "+1", to also take the last integer of the range.
print ('{}{}'.format(i,b),end='') # We implement the ".format" method as an alternative to print(i+b) since i and b are from different types, and finally we add " end='' " to get back to the line.
if (counter % column == 0 ): # We invoke a conditional statement, so that the program knows when to get back to the line:
print() # In that respect, if the number of lines divided by the amount of rows is nill: then the program goes back to the line.
counter = counter + 1 # We add an additional line to the counter variable, that is counting the lines, and we iterate all over again until all the numbers are printed
main()
But if i input for instance :
Please enter a starting number and an ending number separated by
a comma: 1,32
Please enter the number of numbers printed on a row and the
number of spaces per item separated by a comma: 10,4
I get :
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32
Rather than :
expected output
I tried the format methods using : {:<},{:-},etc but it works at most for two or three different inputs, rather than all of them.
Thanks in advance
To get the desired output replace
print ('{}{}'.format(i,b),end='')
with
print ('{: >2}{}'.format(i,b),end='')
This is minimal improvement. Here 2 is the amount of digits in the largest number. You should calculate it from e_num value - len(str(e_num)) and use the value to create appropriate string to be formatted and printed:
templ = '{' + ': >{}'.format(len(str(e_num))) + '}{}'
And then use it inside your for loop:
print (templ.format(i,b),end='')

Add a space in between loop outputs using .format: Python 3

I am trying to create a for loop where the user inputs a number n and the output provides the range of values from n to n+6. This needs to all be printed in one row and be right aligned with spaces in between value outputs but no space at the end or start of the output.
So far this is what I've come up with:
n=eval(input("Enter the start number: "))
for n in range(n,n+7):
print("{0:>2}".format(n),end=" ")
However, this results in the following output:
-2 -1 0 1 2 3 4 <EOL>
When the output I want needs to look similar but without the space at the end, like so:
-2 -1 0 1 2 3 4<EOL>
How can I add spaces between values without adding an additional space to the final term?
There are 3 recommendations I could make:
use end="" and insert the whitespaces manually
create a string and print after the loop:
s = ""
for n in range(n, n+7):
s+= str(n)+ " "
s = s[:-1] #remove the ending whitespace
print(s)
which I recommend: Using sys.stdout.write instead print:
print only displays the message after a linebreak was printed. So if there is a long calculation in the loop and there is end=" " you will only see the resulr at the end of all calculations. Use sys.stdout instead
for n in range(n, n+7):
if n < n+7:
sys.stdout.write(str(n)+" ")
else:
sys.stdout.write(str(n))
sys.stdour.flush() #flush output to console
Edit: I evolved a bit and this is what I'd use nowadays:
4. message = " ".join(range(n, n+7))
This puts spaces between all elements of a list. You can choose any separation character instead of a space (or multiple characters).

Categories