Printing a simple matrix in python using nested for loops - python

I am having trouble with my assignment.
Print out a 3x3 matrix of “-”s using for loops.
It should look like this:
- - -
- - -
- - -
This is the closest I have come but it's not working
x = "-"
for i in range(3):
for n in range(3):
for x in range(3):
print x,
You will need nested for loops to accomplish this.
I have been trying this for an hour with no luck, can someone please point me in the right direction?

for i in range(21/7):
print ' '.join(['-' for _ in range(264/88)])

In your code, x is defined to be -, so you shouldn't enumerate over it.
I edited your code to produce a working version.
Note that in the internal loop you need to put spaces between the -, while in the external loop you want to move to the next line.
Here is the code for python 3:
x = "-"
for i in range(3):
for n in range(3):
print(x, end=' ')
print('\n')
Here is the code for python 2:
x = "-"
for i in range(3):
for n in range(3):
print x,
print('\n')

Very good start!
Let's think through, what were you trying to achieve with your 3rd loop.
(Hint: you don't need a third loop).
If you talk out what you need to happen it becomes:
1) print a "- " three times. (inner loop)
2) print a new line
3) now go back and repeat steps 1) and 2) three times (outer loop)
That would only be 2 loops, not 3.
Try This:
x = "- "
for i in range(3):
for n in range(3):
print x,
print "\n"
You could even shorten this to
for i in range(3): # print the following line 3 times
for n in range(3): # print 3 dashes, separated by a space
print "- ",
print "\n" # begin a new line
BTW, print x, is proper if using Python 2, but for Python 3, it will need to be changed to print(x, end='').

construct a matrix using nested loop:
matrix = [[],[],[]]
for x in range(0,3):
for y in range(0,3):
matrix[x].append("-")
then print it:
for i in range(3):
print(matrix[i])

Related

(Python 3) avoid printing comma at the end in print(variableName,end=',')

I have a code that print x number of numbers. Firstly, I asked for the serious length. Then print all the previous numbers (from 0 to x).
My question is that:
when printing these number, I want to separate between them using comma. I used print(a,end=',') but this print a comma at the end also. E.g. print like this 1,2,3,4,5, while the last comma should not be there.
I used if statement to overcome this issue but do not know if there is an easier way to do it.
n=int(input("enter the length "))
a=0
if n>0:
for x in range(n):
if x==n-1:
print(a,end='')
else:
print(a,end=',')
a=a+1
The most Pythonic way of doing this is to use list comprehension and join:
n = int(input("enter the length "))
if (n > 0):
print(','.join([str(x) for x in range(n)]))
Output:
0,1,2
Explanation:
','.join(...) joins whatever iterable is passed in using the string (in this case ','). If you want to have spaces between your numbers, you can use ', '.join(...).
[str(x) for x in range(n)] is a list comprehension. Basically, for every x in range(n), str(x) is added to the list. This essentially translates to:
data = []
for (x in range(n))
data.append(x)
A Pythonic way to do this is to collect the values in a list and then print them all at once.
n=int(input("enter the length "))
a=0
to_print = [] # The values to print
if n>0:
for x in range(n):
to_print.append(a)
a=a+1
print(*to_print, sep=',', end='')
The last line prints the items of to_print (expanded with *) seperated by ',' and not ending with a newline.
In this specific case, the code can be shortened to:
print(*range(int(input('enter the length '))), sep=',', end='')

Difficulty in inserting newline character into Python string after conversion from list form

The code I'm working on takes an input, and is meant to return a "staircase" of hashes and spaces. For instance, if the input was 5, the result should be:
#
##
###
####
#####
I've turned the input into a list of spaces and hashes, and then converted that to a string form, in order to insert \n in every space corresponding to the length of the input (e.g. every 5 characters above). However, my code prints the result in one line. Where am I going wrong??
x = input()
list = []
a = x-1
while a > -1:
for i in range(0, a):
list.append(" ")
for i in range(0, (x-a)):
list.append("#")
a = a - 1
continue
z = str("".join(list))
t = 0
while t<x:
z = z[t:] + "\n" + z[:t]
t = t + x
continue
print str(z)
Start with pseudocode, carefully laying out in clear English what you want the program to do.
Get a number from the user.
Go through each number from 1 until the user's number, inclusive.
On each line, print a certain number of spaces, starting from one fewer than the user's number and going down to zero, inclusive.
On each line, also print a certain number of hash symbols, starting from one and going up to the user's number, inclusive.
Now you can turn that into Python.
First, get a number from the user. It looks like you're using Python 2, so you could use input() or try the safer raw_input() and cast that to int().
num = input()
Going through each number from one until the user's number, inclusive, means a for loop over a range. On Python 2, using xrange() is better practice.
for i in xrange(1, num+1):
This next part will combine steps 3 and 4, using string multiplication and concatenation. For the spaces, we need a number equal to the max number of lines minus the current line number. For the hash symbols, we just need the current line number. You can multiply a string to repeat it, such as 'hi' * 2 for 'hihi'. Finally, the newline is taken care of automatically as the default end character in a Python 2 print statement.
print ' ' * (num-i) + '#' * i
Put it all together and it looks like this:
num = input()
for i in xrange(1, num+1):
print ' ' * (num-i) + '#' * i
As you discovered, achieving the same effect with an intricate structure of counters, nested loops, list operations, and slicing is more difficult to debug. The problems don't stop when you get it working properly, either - such code is difficult to maintain as well, which is a pain if you ever want to modify the program. Take a look at the official Python tutorial for some great examples of clear, concise Python code.
Try this
x = input()
list1 = []
a = x-1
while a > -1:
for i in range(0, a):
list1.append(" ")
for i in range(0, (x-a)):
list1.append("#")
a = a - 1
list1.append("\n")
continue
z = str("".join(list1))
print z

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.

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

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

How do I make 'i' number of functions in python?

I'm trying to do a for loop with [i] number of similar functions in Python:
i = int(raw_input())
for i in range (0, i):
myfunction[i] = str(raw_input())
And I'm getting an error that it isn't defined. So I'm defining it.... How do I define [i] number of similar functions?
larsmans answer can also be implemented this way:
def make_function(x):
def function(y):
return x + y
return function
functions = [make_function(i) for i in xrange(5)]
# prints [4, 5, 6, 7, 8]
print [f(4) for f in functions]
Updated
From the edit and all the comments it seems that you want to ask the user for a number N and then ask for N strings and have them put into a list.
i = int(raw_input('How many? '))
strings = [raw_input('Enter: ') for j in xrange(i)]
print strings
When run:
How many? 3
Enter: a
Enter: b
Enter: c
['a', 'b', 'c']
If the list comprehension seems unreadable to you, here's how you do it without it, with some comments:
i = int(raw_input('How many? '))
# create an empty list
strings = []
# run the indented block i times
for j in xrange(i):
# ask the user for a string and append it to the list
strings.append(raw_input('Enter: '))
print strings
You can't set list items by index, try:
myfunction = []
for i in range(0, 5):
myfunction.append(whatever)
I'm not sure what you want here, but from all that you said, it appears to me to be simply this:
def myfunction(j):
for i in range(j):
variable.append(raw_input('Input something: '))
I still think this may not be what you want. Correct me if I am wrong, and please be a little clear.
myfunction[i] is the i'th element of the list myfunction, which you have not already defined; hence the error.
If you want a sequence of functions, you can try something like this:
def myfunction(i,x):
if i==0:
return sin(x)
elif i==1:
return cos(x)
elif i==2:
return x**2
else:
print 'Index outside range'
return
If you need similar functions that have something to do with i, it gets simpler, like this example:
def myfunction(i,x):
return x**i

Categories

Resources