Python for-loop to print a triangle - python

This code was given to me by my professor, and prints a triangle of *s:
def printTriangle(size):
for i in range(0,size):
for j in range(0,i+1):
print "*",
print
This is my failed attempt to code an inverse of the triangle:
def printInvertedTriangle(size):
for i in range(size,0):
for j in range(size,i-1):
print "*",
print
I have tried this many different ways, but this is how I think it should be, and it only gives me blank space before the program ends.
My understanding is that this is how his works:
for i in range(start,finish):
for j in range(start,step):
print "*",
print
Can anyone explain to me why the first block my professor gave me works, and why mine prints blank space? I thought I understood his loop; so what was I doing wrong in mine? What should it look like? I want something based off of his for loop. His goes against what I've been reading in Python tutorials in that he has only (start,step), whereas the tutorials say it goes (start,stop,step).
I got started in programming with JS, and thought that some simple Python loops would be a walk in the park...
Thanks a lot for any and all help!! #noob

def printInvertedTriangle(size):
**for i in range(size,0):**
for j in range(size,i-1):
print "*",
print
Your error of having white space shown I believe is as a result of line two. Since this index is counting how many times to step through lines, this needs to still run through x amount of iterations by ranging from (0,size).
In the second for loop, as the lines increase from 1 to 2 to 3 ...etc use variable i and the max (size) to build the reverse triangle.
Try this:
def printReverseTriangle(size):
for i in range(0,size):
for j in range(i,size):
print "*",
print

The reason your script outputs nothing is your range doesn't work.
As we can see in the interpreter:
>>> range(10,0)
[]
It outputs an empty list.
One way to accomplish what you want is to use the reversed() builtin to reverse the list.
for i in reversed(range(0,size)):
for j in range(0,i+1):
To help you in the future, try to use the interpreter more to check the output of things.
You can open any python module in interactive mode, which runs the program and then lets you use the interpreter afterward.
python -i script.py

Here is a program that I had to make for my weekend assignment. It gives a pretty decent reverse triangle as well.
def reverse_triangle(n):
r=n/2+1
for i in range(r-1,0,-1):
print" "*(r-i)," *"*i
def main():
n=input('Enter the size=')
reverse_triangle(n)
main()
Note: In this bit " *"*i I put the space before the asterisk because my PC's version of Python 2.7 does not print the pattern symmetrically if the space is not added. You can try it with the space or without it and check if it works for you.

Related

unable to get 'while True' conditions to work

I'm trying to make a code that can generate valid credit card numbers. So far I've created the random number generator that adds a specific prefix in front of it (in this case, I'm using Visa's prefix '4' and generating an additional 15 random integers behind it). The problem I think I'm having is I am unable to get my 'while True' conditions to work.
As it stands, when I run the program, it prints a seemingly arbitrary amount of 16 digit numbers that do start with '4', but don't follow the algorithm I have set up in my 'while True' conditions. Some of the numbers this code prints is valid when copied and pasted here:
https://www.dcode.fr/luhn-algorithm
The majority do not, however.
I have used the portion of the code that confirms the Luhn's algorithm works with success on another project, but for some reason I can't get it to work here. Any guidance is greatly appreciated as I'm very new to Python.
This is what I have done so far...
import random
def s():
prefix = '4'
return (prefix + str(random.randint(100000000000000,999999999999999)))
while True:
print(s())
q_16= (2*int(s()[14]),2*int(s()[12]),2*int(s()[10]),2*int(s()[8]),2*int(s()[6]),2*int(s()[4]),2*int(s()[2]),2*int(s()[0]))
p= int("".join(map(str, q_16)))
p2= list(map(int, str(p)))
p3= sum(p2)+int(s()[15])+int(s()[13])+int(s()[11])+int(s()[9])+int(s()[7])+int(s()[5])+int(s()[3])+int(s()[1])
if p3 % 10 == 0:
break

Trying to understand Python loop using underscore and input

One more tip - if anyone is learning Python on HackerRank, knowing this is critical for starting out.
I'm trying to understand this code:
stamps = set()
for _ in range(int(input())):
print('underscore is', _)
stamps.add(raw_input().strip())
print(stamps)
Output:
>>>2
underscore is 0
>>>first
set(['first'])
underscore is 1
>>>second
set(['second', 'first'])
I put 2 as the first raw input. How does the function know that I'm only looping twice? This is throwing me off because it isn't the typical...for i in xrange(0,2) structure.
At first my thinking was the underscore repeats the last command in shell. So I added print statements in the code to see the value of underscore...but the values just show the 0 and 1, like the typical loop structure.
I read through this post already and I still can't understand which of those 3 usages of underscore is being used.
What is the purpose of the single underscore "_" variable in Python?
I'm just starting to learn Python so easy explanations would be much appreciated!
ncoghlan's answer lists 3 conventional uses for _ in Python:
To hold the result of the last executed statement in an interactive
interpreter session. This precedent was set by the standard CPython
interpreter, and other interpreters have followed suit
For translation lookup in i18n (imported from the corresponding C
conventions, I believe), as in code like:
raise forms.ValidationError(_("Please enter a correct username"))
As a general purpose "throwaway" variable name to indicate that part
of a function result is being deliberately ignored, as in code like:
label, has_label, _ = text.partition(':')
Your question is which one of these is being used in the example in your code. The answer would be that is a throwaway variable (case 3), but its contents are printed here for debugging purposes.
It is however not a general Python convention to use _ as a loop variable if its value is used in any way. Thus you regularly might see:
for _ in range(10):
print("Hello world")
where _ immediately signals the reader that the value is not important and that the loop is just repeated 10 times.
However in a code such as
for i in range(10):
do_something(i)
where the value of the loop variable is used, it is the convention to use a variable name such as i or j instead of _.
For anyone that is trying to understand how underscore and input works in a loop - after spending quite sometime debugging and printing - here's the code that made me understand what was going on.
for _ in range(int(raw_input())):
print raw_input()
User input:
2
Dog
Cat
Output:
# no output despite entering 2, but 2 is set as range - loops 2 times
Dog
Cat
Bonus - notice how there's an int() conversion for the first line in the for loop?
The first input is 2, so int() converts that just fine. You can tell the first line of code is being ignored now because putting the second input, 'Dog', through int() would yield an error. Can't words into integer numbers.
The underscore is like a normal variable in your program.
Your code
stamps = set()
for _ in range(int(raw_input())):
print 'underscore is', _
stamps.add(raw_input().strip())
print stamps
is exactly equivalent to this:
how_many_loops = int(raw_input()) # asked only once.
stamps = set()
for i in range(how_many_loops):
print 'loop count is', i
stamps.add(raw_input().strip())
print stamps
Because whatever you put in range() has to be calculated before the loop starts, so the first int(raw_input()) is asked only once. If you use something like for i in range(very_expensive_list) it will take a bunch of time then start the loop.

Isn't this supposed to run for single time range(3,3,2) python

I am trying to write a prime number program in python. But when user inputs 3. My program is not working. Further checking with print statements i found its not going in for loop.
I'm going to assume in your program you have range(3,i,2), where i is the input. When your user inputs 3, there will be no range since you're going from 3 to 3.
A good way to fix this is at the beginning of the function. Before you get your range, return [2,3] if the input is 3 (I assume you are doing something similar for 2)

indent python file (with pydev) in eclipse

I'm a newbie in eclipse. I want to indent all the lines of my code and formatting the open file by pressing a shortcut or something like that...
I know the CTRL+SHIFT+F (as it actually doesn't work in pydev!!)
I've been searching for hours with no success. Is there any way to do that in eclipse. kind of like CTRL+K,D in visual studio, which formats and indents all the source code lines automatically?
If you want to change from 2 space to 4 space indentation (for instance), use "Source->Convert space to tab" with 2 spaces, then "Soruce->Convert tab to space" with 4 spaces.
I ... don't think this question makes sense. Indentation is syntax in Python. It doesn't make sense to have your IDE auto-indent your code. If it's not indented properly already, it doesn't work, and the IDE can't know where your indentation blocks begin and end. Take, for example:
# Valid Code
for i in range(10):
b = i
for j in range(b):
c = j
# Also Valid Code.
for i in range(10):
b = i
for j in range(b):
c = j
There's no possible way that the IDE can know which of those is the correct version, or what your intent is. If you're going to write Python code, you're going to have to learn to manage the indentation. There's no way to avoid it, and expecting the IDE to magically clean it up and still get the desired result out of it is pretty much impossible.
Further example:
# Valid Code.
outputData = []
for i in range(100):
outputData.append(str(i))
print ''.join(outputData)
# Again, also valid code, wildly different behavior.
outputData = []
for i in range(100):
outputData.append(str(i))
print ''.join(outputData)
The first will produce a list of strings, then print the joined result to the console 1 time. The second will still produce a list of strings, but prints the cumulative joined result for each iteration of the loop - 100 print statements. The two are both 100% syntactically correct. There's no problem with them. Either of them could be what the developer wanted. An IDE can't "know" which is correct. It could, very easily incorrectly change the first version to the second version. Because the Language uses Indentation as Syntax, there is no way to configure an IDE to perform this kind of formatting for you.
Although auto-indentation is not a feature of PyDev because of the language design you should be able to indent with a simple tab. Just select the lines you want to indent and press Tab. If you want to unindent lines you have to press Shift+Tab.
Thats all.
It is much easier:
Select multiple lines
Press Tab to indent (move right), Shift + Tab to unindent (move left) all selected
lines.
Indentation is syntactically significant; consider the difference between
for i in range(5):
print i
print "done"
and
for i in range(5):
print i
print "done"
However, it certainly makes sense for the IDE to be able to normalize the existing indentation (e.g. apply a consistent number of spaces/tabs at each level).
Currently PyDev does not support such a feature; Pydev author Fabioz at one point expressed interest in adding it in the future and indicated that for now you can use the supplied reindent.py script to do it.
Obviously this is only for Pydev, but I've worked out that you can get the very useful functions "Shift Right" and "Shift Left" (mapped by default to CTRL + ALT + . and CTRL + ALT + ,) to become useful by changing their keybindings to "Pydev Editor Scope" from "Pydev View". This effectively indents/dedents all lines that you've selected as much as you'd like
I think that what you're looking for is some kind of shortcut in Eclipse/PyDev so that the selected code can be idented all at once. Just like when you create a new "if" or a "for" loop above a block of code and then need to rearrange the identation. The IDLE Editor has the "Ctrl + ]" shortcut that works exactly that way. It seems that the PyDev in Eclipse doesnt have something like that as far as I know.
One can also select the lines, right click, then shift right / shift left
It seems source formatting is still not available in PyDev.
For one off instances I found this web app does the job nicely.
http://pythoniter.appspot.com/
Like earlier said python requires to indent your code, so for other things like: space between variables passed as arguments to methods, etc., one can use ctrl+shift+f to format the code. This what is used for java, I tried for pydev and does some formatting.

Weird program behaviour in Python

When running the following code, which is an easy problem, the Python interpreter works weirdly:
n = input()
for i in range(n):
testcase = raw_input()
#print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
The problem consists in taking n strings and deleting a single character from them.
For example, given the string "4 PYTHON", the program should output "PYTON".
The code runs ok, but if I take out the comment mark, the statement print i makes the interpreter give an unexpected EOF while parsing. Any idea on why this happens?
EDIT: I'm working under Python 2.5, 32 bits in Windows.
Are you sure that the problem is the print i statement? The code works as
expected when I uncomment that statement and run it. However, if I forget to
enter a value for the first input() call, and just enter "4 PYTHON" right off
the bat, then I get:
"SyntaxError: unexpected EOF while parsing"
This happens because input() is not simply storing the text you enter, but also
running eval() on it. And "4 PYTHON" isn't valid python code.
I am yet another who has no trouble with or without the commented print statement. The input function on the first line is no problem as long as I give it something Python can evaluate. So the most likely explanation is that when you are getting that error, you have typed something that isn't a valid Python expression.
Do you always get that error? Can you post a transcript of your interactive session, complete with stack trace?
This worked for me too, give it a try...
n = raw_input()
n = int(n)
for i in range(n):
testcase = raw_input()
print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
Note the n = int(n)
PS: You can continue to use n = input() on the first line; i prefer raw_input.

Categories

Resources