New to python (and programming) need some advice on arranging things diagonally - python

I'm finishing up an assignment for my 1035 computer science lab and the last thing I need to do is arrange inputted numbers in a diagonal line.
I've tried things like:
print (\tnum2)
and like this:
print ('\t'num2)
but I can't figure out how to do it. I've looked through my programming book, but have been unable to find an explanation on how to do it.

strings in python can be concatenated using the + sign. For example
print(' ' + str(a))
will give the following output for a=1
1
Notice the single blank space before 1. The function str(a) returns the integer a in string format. This is because print statement can only print strings, not integers.
Also
print(' ' * i)
prints i blank spaces. If i = 10, then 10 blank spaces will be printed.
So, the solution to the question can be:
a = [1,2,3,4,5,6,7,8,9,10]
for i in range(len(a)):
print((' ' * i) + str(a[i]))

Here's a simple example that prints items in a list on a diagonal line:
>>> l = [1,2,3,4,5]
>>> for i in range(len(l)):
... print("\t" * i + str(l[i]))
...
1
2
3
4
5

You can also do it using .format
nome = input("nome:")
a = " "
b = len(nome)
for i in range(b):
print ("{0} {1}".format(a * i, nome[i]))
print ("\n next \n")
c=b
for i in range(b):
print ("{0} {1}".format(a * c, nome[i]))
c = c-1
this give diagonal increasing or decreasing

Related

Unexplained syntax/EOF errors

I keep getting syntax errors in my print command (that's why the bracket is on the one at the bottom) and I also get an End of File error (unexpected end of file while parsing) if I try to run the code.
I put a bracket on the print statement, and I have tried re-typing the code with no success.
print ("input a number")
a = (str(input(''))
if 9 in (a)
(b = a.count('9')
if 8 in (a)
(c = a.count('8')
if 7 in (a)
(d = a.count('7')
if 6 in (a)
(e = a.count('6')
if 5 in (a)
(f = a.count('5')
if 4 in (a)
(g = a.count('4')
if 3 in (a)
(h = a.count('3')
if 2 in (a)
(i = a.count('2')
if 1 in (a)
(j = a.count('1')
if 0 in (a)
(k = a.count('0')
(print("the highest number you can make is", 9*b, 8*c, 7*d, 6*e, 5*f, 4*g, 3*h, 2*i, 1*j, 0*k)
File "/home/ubuntu/workspace/SuPeRsIzE.py", line 26
^
SyntaxError: unexpected EOF while parsing
Notice the code is only 25 lines long - I haven't even opened it to 26 lines
---------------------------------------------------------------------------
File "/home/ubuntu/workspace/SuPeRsIzE.py", line 25
print("the highest number you can make is", 9*b, 8*c, 7*d, 6*e, 5*f, 4*g, 3*h, 2*i, 1*j, 0*k)
^
SyntaxError: invalid syntax
This is what I get if I remove the bracket from the print statement.
So, the syntax error is actually because you're not ending your if statements with : and also you have a bunch of open brackets on each line in the if blocks. You may want to look at a tutorial for basic Python syntax.
The reason the syntax error doesn't happen immediately is because of how Python works. If we remove the linebreaks:
if 9 in (a)(b = a.count('9') if 8 in (a)(c = a.count('8') ...
What this does is it tries to test if 9 is in the right expression, which is a function call. It tries to call a as a function with the keyword argument b equal to a.count('9') if <expr> else <expr>, which is Python's ternary expression syntax. At the very end, it says "unexpected EOF" because it's expecting more close brackets because you open a lot of brackets that shouldn't even be there in the first place. If you put them all in, it says "invalid syntax" because it wants else statements to complete the ternary expressions.
This code is very confusing but addressing the syntax errors:
All of your if lines need to end with :
if 4 in (a) # missing : at the end
should be
if 4 in a:
Every if body starts with ( but isn't closed
(b = a.count('9')
should be
b = a.count('9')
You will be printing variables that you never assigned to, unless every if check is independently true. so I would recommend at least removing all the if checks and making it flat
b = a.count('9')
c = a.count('8')
d = a.count('7')
e = a.count('6')
f = a.count('5')
g = a.count('4')
h = a.count('3')
i = a.count('2')
j = a.count('1')
k = a.count('0')
print("the highest number you can make is", 9*b, 8*c, 7*d, 6*e, 5*f, 4*g, 3*h, 2*i, 1*j, 0*k)
but I don't think this will produce the correct answer, though it's hard to see what your goal is.
These aren't errors, but you don't need the extra () around input and print. input() also supports taking a string to display
a = input('input a number: ')
# ...
print('the highest number...')
Update for comment explaining that the goal is to rearrange.
The simplest way is using the python sorted and then joining the result back to a single string
a = input('input a number: ')
highest = ''.join(sorted(a, reverse=True))
print('The highest number you can make is', highest)
However, if you want to keep your existing approach with all the variables, you need only replace the ints in your print with str by quoting them, and using sep='' to remove the spaces in between
print("the highest number you can make is ",
'9'*b, '8'*c, '7'*d, '6'*e, '5'*f, '4'*g,
'3'*h, '2'*i, '1'*j, '0'*k,
sep='')
A more imperative, but less repetitive approach would be to build up a result string as you went
a = input('input a number: ')
result = ''
for i in range(10, -1, -1):
count = a.count(str(i))
result += count * str(i)
print("the highest number you can make is", result)
b = a.count('9')
c = a.count('8')
d = a.count('7')
e = a.count('6')
f = a.count('5')
g = a.count('4')
h = a.count('3')
i = a.count('2')
j = a.count('1')
k = a.count('0')
´
print("the highest number you can make is", ´9´*b, ´8´*c, ´7´*d, ´6´*e, ´5´*f, ´4´*g, ´3´*h, ´2´*i, ´1´*j, ´0´*k)
this seems to work fine - thanks for the help everybody but this works for my purposes

Multiline printing in a "for" loop

I'm trying to print a multiline string in a "for" loop. The problem is I'd like to have the output printed all on the same lines. Example:
for i in range(5):
print('''
{a}
|
{b}
'''.format(a=i,b=i+1))
The output looks like:
0
|
1
1
|
2
2
|
3
3
|
4
4
|
5
Instead I'd like it to be:
0 1 2 3 4
| | | | |
1 2 3 4 5
​But I can't get how to do it. Thanks for the help.
Try with list concaternation:
x = 5
print (" ".join(str(i) for i in range(x)))
print ('| '*x)
print (" ".join(str(i) for i in range(1,x+1)))
import sys
myRange = range(5)
for i in myRange:
sys.stdout.write(str(i))
print()
for i in myRange:
sys.stdout.write('|')
print()
for i in myRange:
sys.stdout.write(str(i+1))
print()
You need sys.stdout.write to write without \n. And this code will not work if you have range more than 9 (10+ has 2+ chars, so you need special rules for spaces before |).
Just to throw in a fun (but bad, don't do this) answer:
for i in range(5):
print('{}\033[1B\033[1D|\033[1B\033[1D{}\033[2A'.format(i, i+1), end='')
print('\033[2B')
This uses terminal control codes to print column by column rather than row by row. Not useful here but something that's good to know about for when you want to do weirder terminal manipulation.
You can only print one line at a time. So first you'll have to print the line with all the a elements, then the line with all the bars, and finally the line with all the b elements.
This can be made easier by first preparing every line before printing it:
line_1 = ""
line_2 = ""
line_3 = ""
for i in range(5):
line_1 += str(i)
line_2 += "|"
line_3 += str(i+1)
print(line_1)
print(line_2)
print(line_3)
There are of course many ways with the same basic idea. I picked the one that is (IMHO) easiest to understand for a beginner.
I didn't take spacing into account and once you do, it gets beneficial to use lists:
line_1_elements = []
line_2_elements = []
line_3_elements = []
for i in range(5):
line_1_elements.append(str(i))
line_2_elements.append("|")
line_3_elements.append(str(i+1))
print(" ".join(line_1_elements))
print(" ".join(line_2_elements))
print(" ".join(line_3_elements))
Similar to Tim's solution, just using map instead of the genrators, which I think is even more readable in this case:
print(" ".join(map(str, range(i))))
print("| " * i)
print(" ".join(map(str, range(1, i+1))))
or alternatively, less readable and trickier, a heavily zip-based approach:
def multi(obj):
print("\n".join(" ".join(item) for item in obj))
r = range(6)
multi(zip(*("{}|{}".format(a, b) for a, b in zip(r, r[1:]))))
What's your goal here? If, for example, you print up to n>9, your formatting will be messed up because of double digit numbers.
Regardless, I'd do it like this. You only want to iterate once, and this is pretty flexible, so you can easily change your formatting.
lines = ['', '', '']
for i in range (5):
lines[0] += '%d ' % i
lines[1] += '| '
lines[2] += '%d ' % (i+1)
for line in lines:
print line

Python programming - beginner

so i have to create a code in which it reads every third letter and it creates a space in between each letter, my code creates the spaces but it also has a space after the last letter, this is my code:
msg = input("Message? ")
length = len(msg)
for i in range (0, length, 3):
x = msg[i]
print(x, end=" ")
My output was:
Message?
I enter:
cxohawalkldflghemwnsegfaeap
I get back
c h a l l e n g e
when the output isn't meant to have the last " " after the e.
I have read by adding print(" ".join(x)) should give me the output i need but when i put it in it just gives me a error. Please and Thank you
In Python, strings are one kind of data structures called sequences. Sequences support slicing, which is a simple and fancy way of doing things like "from nth", "to nth" and "every nth". The syntax is sequence[from_index:to_index:stride]. One does not even a for loop for doing that.ago
We can get every 3th character easily by omitting from_index and to_index, and have stride of 3:
>>> msg = input("Message? ")
cxohawalkldflghemwnsegfaeap
>>> every_3th = msg[::3]
>>> every_3th
'challenge'
Now, we just need to insert spaces after each letter. separator.join(iterable) will join elements from iterable together in order with the given separator in between. A string is an iterable, whose elements are the individiual characters.
Thus we can do:
>>> answer = ' '.join(every_3th)
>>> answer
'c h a l l e n g e'
For the final code we can omit intermediate variables and have still a quite readable two-liner:
>>> msg = input('Message? ')
>>> print(' '.join(msg[::3]))
Try
>>> print " ".join([msg[i] for i in range(0, len(msg), 3)])
'c h a l l e n g e'

python asterisk triangle without using y* "*"

I'm trying to create a iso triangle (one that starts in the middle).
I have a code but the problem is that I'm not allowed to use Y* "*" 5 in my code.
(The y is a variable there)
Also I may only use one print statement at the end of my code.
Can you please help me out.
f = int(raw_input("enter"))
for i in range(f):
print " " * (f-i-1) + "*" * (2*i+1)
creats this triangle
*
***
*****
*******
*********
***********
However, you are not allowed to use the *-operator on string and int. So for example ''***'' * 3 is not allowed, but 3 * 4 is
This just creates a continuous string and then prints it at the end
f = int(raw_input("Enter height: "))
s = ''
for i in xrange(f):
for j in xrange(f-i-1):
s += ' '
for j in xrange(2*i+1):
s += '*'
s += '\n'
print s
This is a solution which i think is very easy to understand. You can make the parameter of range() variable, to make it more dynamic.
from __future__ import print_function
for i in range(1,12,2):
count=(11-i)/2
for j in xrange(count):
print(" ",end='')
for j in xrange(i):
print("*",end='')
for j in xrange(count):
print(" ",end='')
print(end="\n")
I think the best solution is using the center() string method:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
star += "**" if X>0 else ""
full_string += star.center(2*f-1) + "\n"
print full_string[:-1]
The str.center() documentation:
https://docs.python.org/2/library/string.html#string.center
EDIT: If you can't use the print statement within the for loop, you could concatenate the string during the loop and print it at the end:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
# the first row should take only one star
star += "**" if X>0 else ""
star2 = star.center(2*f-1)
full_string += star2 + "\n"
# slice the string to delete the last "\n"
print full_string[:-1]
I noticed that using a for loop add a newline character. If you want to avoid this, you can slice the string before printing.
There is no problem with this code, i just checked it and it worked fine. If you would post the error message we might be able to help a bit more.

How to concatenate strings in list python

This prints the list correctly, but it prints it 7 times. I need to print my list only 2 times. I think the list is printing 7 times because there are 7 strings in the list.
Is there a way to only make it print my "custom" list a certain number of times? Because I want to use all these words, but on different lines, and vary each time they are used.
lyrics = ['Ring', 'Gering', 'ding', 'dingeringeding!', 'Wa', 'pa', 'pow!']
for y in lyrics:
print (lyrics[0] +' ' + (lyrics[2] + ' ') * 3 + lyrics[3])
use range, you have seven elements in your list so you iterate seven times with for y in lyrics:
for _ in range(2): # two iterations, prints two times
print (lyrics[0] +' ' + (lyrics[2] + ' ') * 3 + lyrics[3])
It is probably nicer to use str.format:
for _ in range(2): # two iterations, prints two times
print ("{} {} {}".format(lyrics[0] ,lyrics[2] * 3, lyrics[3] )
Which if you don't mind an extra newline can simply be multiplied:
In [36]: print ("{} {} {}\n".format(lyrics[0] ,lyrics[2] * 3, lyrics[3] )* 2)
Ring dingdingding dingeringeding!
Ring dingdingding dingeringeding!

Categories

Resources