Python: Pattern display - python

I just started learning Python and I need help on creating this pattern:
******
*****
****
***
**
*
I currently have this code:
base = 6
for row in range (base):
for col in range (row+1):
print('*', end='')
print()
which becomes:
*
**
***
****
*****
******

What you need here is to track how many spaces you need—and you pretty much already have code for that—and how many '*'s you need. Then for each line, you need to print the appropriate number of ' 's, and the appropriate number of '*'s. Since my guess is that you want the total width to stay constant, you'll want x number of ' 's, and n-x number of '*'s, where n is the number of lines / total width you want.
So for example
n=6; print('\n'.join(' '*x+'*'*(n-x) for x in range(0,n)))
will work.
If this is a homework problem, I'd advise against turning in the above solution, however. It would be better to write it out in a standard way.

Since this might be some homework or something as specified above by #cge as well, I just hope that a difference of two years is enough and I am writing the answer to tell about something which lot many aren't well aware of in Python.
See the pattern you are trying to make is one of the most common things asked to form in any programming language and quite easy to make in Java or C++. But this same thing came to my mind while thinking of how will I make such pattern in Python because while using Python, the print() function changes the line whenever used. So there is no feature like we have in Java where print and println are two different things.
Now here's an interesting thing to know about. In Python 3, with the introduction of print as a method, some other things also came with it which also had this thing called end="\n" attached to it as default. This is the reason why when being called, the print function ends up on the next line. So all we need to do is not let the default work.
Here's how the code works:
for i in range(6):
for x in range(6):
if i!=0:
print(" ",end="")
i-=1
else:
print("*",end="")
print()
So we see that using the above additional features of the print function, we can make use of and create such patterns as you have asked.

I think you're making it too complicated
base = 6
for i in range(base, 0, -1):
print "*"*i
and you get:
******
*****
****
***
**
*
Think about how your ranges are being set up. If you want to print "******" before you print "*****" you need to let python know to print 6 before 5. Do that by counting down your range.
I've done that here:
for i in range(base, 0, -1):
It starts the range at base (which you set to 6) and counts down by -1, all the way to zero.

Related

Indexing the wrong character for an expression

My program seems to be indexing the wrong character or not at all.
I wrote a basic calculator that allows expressions to be used. It works by having the user enter the expression, then turning it into a list, and indexing the first number at position 0 and then using try/except statements to index number2 and the operator. All this is in a while loop that is finished when the user enters done at the prompt.
The program seems to work fine if I type the expression like this "1+1" but if I add spaces "1 + 1" it cannot index it or it ends up indexing the operator if I do "1+1" followed by "1 + 1".
I have asked in a group chat before and someone told me to use tokenization instead of my method, but I want to understand why my program is not running properly before moving on to something else.
Here is my code:
https://hastebin.com/umabukotab.py
Thank you!
Strings are basically lists of characters. 1+1 contains three characters, whereas 1 + 1 contains five, because of the two added spaces. Thus, when you access the third character in this longer string, you're actually accessing the middle element.
Parsing input is often not easy, and certainly parsing arithmetic expressions can get tricky quite quickly. Removing spaces from the input, as suggested by #Sethroph is a viable solution, but will only go that far. If you all of a sudden need to support stuff like 1+2+3, it will still break.
Another solution would be to split your input on the operator. For example:
input = '1 + 2'
terms = input.split('+') # ['1 ', ' 2'] note the spaces
terms = map(int, terms) # [1, 2] since int() can handle leading/trailing whitespace
output = terms[0] + terms[1]
Still, although this can handle situations like 1 + 2 + 3, it will still break when there's multiple different operators involved, or there are parentheses (but that might be something you need not worry about, depending on how complex you want your calculator to be).
IMO, a better approach would indeed be to use tokenization. Personally, I'd use parser combinators, but that may be a bit overkill. For reference, here's an example calculator whose input is parsed using parsy, a parser combinator library for Python.
You could remove the spaces before processing the string by using replace().
Try adding in:
clean_input = hold_input.replace(" ", "")
just after you create hold_input.

Input a message inside a box

I need to create a box with parameters that prints any input the user puts in. I figured that the box should be the length of the string, but I'm stuck with empty code, because I don't know where to start.
It should look like this:
I agree with Daniel Goldfarb comments. Don't look for help without trying.
If you still couldn't get how to do that, then only read my remaining comment.
Just print :
str = string entered
len(str) = string length
+-(len(str) * '-')-+
| str |
+-(len(str) * '-')-+
So hopefully you can learn, don't want to just write the code for you. Basically break it into steps. First you need to accept user input. If you don't know how to do that, try googling, "python accept user input from stdin" or here is one of the results from that search: https://www.pythonforbeginners.com/basics/getting-user-input-from-the-keyboard
Then, as you mentioned, you need the length of the string that was input. You can get that with the len function. Then do the math: It looks like you want "|" and two spaces on each side of the string, giving the length plus 6 ("| " on either side). This new length is what you should make the "+---+" strings. Use the print() function to print out each line. I really don't want to say much more than that because you should exercise your brain to figure it out. If you have a question on how to generate "+---+" of the appropriate length (appropriate number of "-" characters) you can use string concatenation and a loop, or just use the python string constructor (hint: google "construct python string of len repeat characters"). HTH.
One more thing, after looking at your code, in addition to my comment about printing the string itself within the box, I see some minor logic errors in your code (for example, why are you subtracting 2 from the width). THE POINT i want to me here is, if you ware going to break this into multiple small functions (a bit overkill here, but definitely a good idea if you are just learning as it teaches you an important skill) then YOU SHOULD TEST EACH FUNCTION individually to make sure it does what you think and expect it to do. I think you will see your logic errors that way.
Here is the solution, but I recommend to try it out by yourself, breakdown the problem into smaller pieces and start from there.
def format(word):
#It declares all the necessary variables
borders =[]
result = []
# First part of the result--> it gives the two spaces and the "wall"
result.append("| ")
# Second part of the result (the word)
for letter in word:
result.append(letter)
# Third part of the result--> Ends the format
result.append(" |")
#Transforms the list to a string
result = "".join(result)
borders.append("+")
borders.append("--"+"-"*len(word)+"--")
borders.append("+")
borders="".join(borders)
print(borders)
print(result)
print(borders)
sentence = input("Enter a word: ")
format(sentence)
I'm new to Python, and I've found this solution. Maybe is not the best solution, but it works!
test = input()
print("+-", end='')
for i in test:
print("-", end='')
print("-+")
print("| " + test + " |")
print("+-", end='')
for i in test:
print("-", end='')
print("-+")

Setting number of decimals for print via user input

I'm dabbling around in Python and wrote a short program which returns the square root of a number provided by the user. The output, respectively the print line, looks like this:
print 'The square root of %d is %.2f' % (x, math.sqrt(x))
with x as the user input.
My question: how could i adjust the results number of decimals via user input?
Thanks a lot!
First get input for how many decimal places you want it by:
y = int(raw_input("How many decimal places? "))
Then you'll probably want to use str.format to make your print statement easier:
print 'The square root of {} is {:.{dec}f}'.format(x, math.sqrt(x), dec=y)
I might be (I probably am) wrong here, but I'm not sure if you can do what you're trying to achieve with the % operator. % tends to be looked at as a deprecated operator anyway, especially with the majority of people transitioning to Python 3. But, since you're using Python 2, thankfully str.format is in Python 2.7.

Repeating an input

I'm new to Python and have been working through some tutorials to try to get to grips with different aspects of programming.
I'm stuck on an exercise that is most likely very simple however I am unable to find the solution.
How do I create a program that reads one line of input and prints out the same line two times?
For example if the input was Echo it would print:
Echo
Echo
Any help with this would be hugely appreciated. I think I'm making a simple logic error but don't yet have the skills in place to recognise what it is.
The other answers seem logical enough, but what if you wanted to print it let's say a 1000 times or a million times? Are you really going to be typing print(variable) a million types? Here is a faster way:
j=input("Enter anything.")
for i in range(2):
print(j)
Here, I can change the value of range to whatever I want, and J will be printed that many times.
What happens here, is that the variable i loops upwards (an increment) to the number 2, so to explain it to a beginner, i travels t=from number to number. Where I put print(j) for every number i loops through until it gets to 2, J will be printed.
It sounds like you've been doing the input and output in one go:
print(input())
That works for doing a single echo of the input, but makes it a bit harder to repeat the same thing twice. An easy workaround would be to save the inputted text to a variable, which you can print twice:
text = input()
print(text)
print(text)
If you needed to do the input and doubled output with a single statement, you could use string formatting to duplicate the text with a newline in the middle:
print("{0}\n{0}".format(input()))
way complex right?(:D)
inp = input("Input something would ya? ")
print(inp)
print(inp)

Running Time: Does Print Count as a Step?

Suppose I have a function and I want to analyze the run-time of the exact number of steps:
def function(L):
print ("Hello")
i = 0 # 1 step
while i < len(L): # 3 steps
print (L[i] + 1)
i += 2 # 2 steps
print ("Goodbye")
I was wondering if print statements count as a step?
"Step" isn't a well-defined term in this context -- as pswaminathan points out, usually what we care about isn't a precise numerical value but the mathematical behavior in a broader sense: as the problem size gets bigger (in this case, if you increase the size of the input L) does the execution time stay the same? Grow linearly? Quadratically? Exponentially?
Explicitly counting steps can be a part of that analysis -- it can be a good way to get an intuitive handle on an algorithm. But we don't have a consistent way of determining what counts as a "step" and what doesn't. You could be looking at lines of code -- but in Python, for example, a list comprehension can express a long, complicated loop in a single line. Or you could be counting CPU instructions, but in a higher-level language full of abstractions that's hopelessly difficult. So you pick a heuristic -- in straightforward code like your example, "every execution of a single line of code is a step" is a decent rule. And in that case, you'd certainly count the print statements. If you wanted to get in a little deeper, you could look at the bytecode as tobias_k suggests, to get a sense for what the instructions look like behind Python's syntax.
But there's no single agreed-upon rule. You mention it's for homework; in that case, only your instructor knows what definition they want you to use. That said, the simple answer to your question is most likely "yes, the print statements count."
If your task is to count the exact number of steps, then yes, print would count as a step. But note also that your second print is at least three steps long: list access, addition, and print.
In fact, print (and other 'atomic' statements) might actually be worth many "steps", depending on how you interpret step, e.g., CPU cycles, etc. This may be overkill for your assignment, but to be accurate, it might be worth having a look at the generated byte code. Try this:
import dis
print dis.dis(function)
This will give you the full list of more-or-less atomic steps in your function, e.g., loading a function, passing arguments to that function, popping elements from the stack, etc. According to this, even your first print is worth three steps (in Python 2.6):
2 0 LOAD_CONST 1 ('Hello')
3 PRINT_ITEM
4 PRINT_NEWLINE
How to interpret this: The first number (2) is the line number (i.e., all the following instructions are for that line alone); the central numbers (0) are jump labels (used by, e.g., if-statements and loops), followed by the actual instructions (LOAD_CONST); the right column holds the arguments for those instructions ('Hello'). For more details, see this answer.

Categories