Having some difficulty with this problem. The program should get a number from the user. It will be the amount of triangles. The first triangle should have two rows. Each new triangle will have one extra row than the last triangle.
This is what I have:
numTri = input('Please umber of triangles: ')
numTri = eval(numTri)
numRow = 2
x = 0
while j<numTri:
y = '*'
z = 0
while z<numRow:
print y
y = y + *
z += 1
x += 1
numRow += 1
Getting an invalid syntax error on the print line. Not sure if I'm doing anything else wrong. Anyone have any idea?
Assuming you are using Python 3, there is a lot of errors in your code. Let us see them:
Major problems
The j variable
You use a j variable, in the loop condition, which is not set neither used anywhere. This will result in an error:
while j<numTri:
I believe you want to use the x variable:
while x<numTri:
print() is a function
In Python 3, you should put the parameters of a print() function between parenthesis, which is not the case:
print y
Too easy to solve:
print(y)
Note that the parenthesis are optional in Python 2.
'*' char without quotes:
You try to append the '*' char to the string from y but does not enclose the char with quotes:
y = y + *
The interpreter will see this asterisk as the multiplication operator, which will yield an error. Just enclose it with quotes (single or double, it does not matter):
y = y + '*'
Indentation problem
A specially pernicious problem in your code is that, after the second while loop, your code does not return to the same indentation level of the loop. I replaced the spaces below with open boxes so we can count them:
␣␣␣while z<numRow:
␣␣␣␣␣␣␣␣␣print y
␣␣␣␣␣␣␣␣␣y = y + *
␣␣␣␣␣␣␣␣␣z += 1
␣␣␣␣x += 1
␣␣␣␣numRow += 1
Alas, there is one more space in the two last lines when compared with the while line. You should remove those spurious spaces.
A resulting code will be:
numTri = input('Please umber of triangles: ')
numTri = eval(numTri)
numRow = 2
x = 0
while x<numTri:
y = '*'
z = 0
while z<numRow:
print(y)
y = y + '*'
z += 1
x += 1
numRow += 1
Minor problems
There are also some other details in your code which would be considered bad practices. Those will not matter a lot to you yet, since you are really novice, but we can explore some of them.
Avoiding eval()
eval() is a powerful yet risky function, so we avoid using it. It is specially easy to do in your case, since int() will convert the read string to an integer without problems:
numTri = input('Please umber of triangles: ')
numTri = int(numTri)
Non-standard indentation
Sometimes, you indent what is inside your loops with four spaces:
␣␣␣y = '*'
␣␣␣z = 0
␣␣␣while z<numRow:
then with six spaces
␣␣␣␣␣␣print(y)
␣␣␣␣␣␣y = y + '*'
␣␣␣␣␣␣z += 1
and even with four spaces, which results in an error:
␣␣␣␣x += 1
␣␣␣␣numRow += 1
The best thing to do is to always use the same indentation size. PEP 8 (a set of recommendations for all Python programmers) recommends to use four spaces for each indentation:
␣␣␣␣y = '*'
␣␣␣␣z = 0
␣␣␣␣while z<numRow:
␣␣␣␣print(y)
␣␣␣␣y = y + '*'
␣␣␣␣z += 1
␣␣␣␣x += 1
␣␣␣␣numRow += 1
while instead of for
This one is hard stuff for novices, but it may be helpful to point nonetheless. Your code would be much better if you used for loops with the range() function:
for x in range(0, numTri+1):
y = '*'
for z in range(0, numRow+1):
print(y)
y = y + '*'
numRow += 1
However, as you are a student, I believe you will learn about this feature some time in the future, so take it easy :)
The resulting code:
numTri = input('Please umber of triangles: ')
numTri = int(numTri)
numRow = 2
for x in range(0, numTri+1):
y = '*'
for z in range(0, numRow+1):
print(y)
y = y + '*'
numRow += 1
j is never defined before you reach the while loop. Maybe you meant while x < numTri: instead?
Also, the
x = 0
while x < numTri:
# do something
x += 1
construct is not very Pythonic; try
for x in range(numTri):
# do something
instead.
But I think the syntax error (and thus answering your question) is because you are using Python 3 where print needs round brackets. So :
print ( y )
And if you just want the highest grade for your programming task:
print('\n'.join('*'*y for x in range(int(input('Please umber of triangles: '))) for y in range(1,x+3)))
numTri = int(raw_input('Please umber of triangles: '))
or on python 3.x
numTri = int(input('Please umber of triangles: '))
Related
I have been trying to write code for the activity selection problem. I am not using the greedy algorithm method but I just wrote this code on my own. My cod is able to find the max number of activities possible, but in my code, I am having a problem with the input. Here's my code:
i = int(input("How many activities are there? Please enter as an integer. "))
list_of_lists = [[[]], [], []]
def check(space):
x = space.split(" ")
for b in range(2):
x[b] = int(x[b])
if (x[0] >= x[1]):
space = input("Incorrect start and end times. Please enter a start time which is less than the end time. ")
check(space)
return space
return space
#ab = space
#return ab
for a in range(1, i + 1):
arr = input("Please enter the start time and end time. There should be a space between the two integers. ")
abc = check(arr)
print(abc)
list_of_lists[a].append(list(map(int, abc.split(' '))))
list_of_lists[0].append(list(map(int, abc.split(' '))))
print(list_of_lists)
count = [0] * i
inn = 0
for ii in range(1, i + 1):
for jj in range(1, i + 1):
if (ii != jj):
if (list_of_lists[ii][0][0] <= list_of_lists[0][jj][0]):
a = list_of_lists[ii][0][1]
b = list_of_lists[0][jj][0]
else:
a = list_of_lists[0][jj][1]
b = list_of_lists[ii][0][0]
if (a <= b):
count[inn] += 1
else:
count[inn] += 1
inn += 1
count.sort()
print(count[i - 1])
So there is a problem with the check function. It is working perfectly when I have the correct type of input. But say, if someone inputs the wrong type of input, then there is a problem. Let me describe with an example.
If I input 2 4 to arr = ..., then it is working properly. If I input 6 5 to arr = ... and then if I input 2 4 to space = input(..., it is working properly. However, if say I input 6 5 to arr = ..., then I input 5 4 to space = input(..., and then I input 2 4 to space = input(..., then it is not working properly. check function is returning 5 4. I know the problem is with the return but I really do not know how to solve this issue so that it works in the right way.
based on that code, I wish to output my result by ending each digit with a dot.
input:
x = 0
while x<=5:
print(x)
x += 1
expected output:
1.
2.
3.
4.
5.
Make sure you start at x = 1 and add a full stop to the string. Concatenating more letters or symbols to variables can be done with f-strings:
# Start at 1
x = 1
while x <= 5:
print(f'{x}.')
x += 1
Alternatively, you could turn this into a one liner function:
>>> def ordered(start, stop):
... return '\n'.join(f'{x}.' for x in range(start, stop+1))
...
>>> print(ordered(1, 5))
1.
2.
3.
4.
5.
Type casting can be used
x = 0
while x<=5:
print(str(x)+".")
x += 1
Just so you know, you can use the ` key to embed code :)
I believe what you want is:
x = 0
while x <= 5:
print(str(x) + '.')
x += 1
Let's break down the print statement:
We add the dot to x. We can't just add a string to an integer, so we first have to use the str() function to turn the numeric value of x into a string value: str(x) + '.'
This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed last year.
I am creating a translator in python . This translator is going to change a normal text to a text with some special things :
At the first of each word we add "S"
At the End of each word we add "Di"
We reverse each word
example :
Hello Everyone --> SHello SEveryone --> SHelloDi SEveryoneDi --> iDolleHS iDenoyrevES
I did first two parts easily; but third part is a little tricky
my code :
n = input("Enter Text : ")
y = n.split()
z = 0
for i in y:
x = str("S" + i)
y[z] = x
z = z + 1
z = 0
for i in y:
x = str(i + "Di")
y[z] = x
z = z + 1
print(y)
z = 1
for i in y:
globals()["x%s" % z] = []
for j in i:
pass
In pass part I wanna to do something like this x{i}.append(j)
and then we reverse it.
How do I do this?
You can reverse it using ::-1, it means from start to beginning in reverse order:
For example:
print("abcd"[::-1]) # will prin dcba
So the code for every word can look like this:
result = "S"+word+"Di"
result = result[::-1]
Now you just have to put that in a loop and do it for every word.
I have already seen a couple of programs for this. Just wanted to know what's wrong with this logic. It keeps on returning 'str' object does not support item assignment. I looked this up but still couldn't find a reason this occurs.I'm just a newbie so apologies in advance if I'm just overthinking things.
x = dec
a = 5
n = 1
remainder = str()
binary = str()
while a != 1:
a = x // 2
b = x % 2
x = a
z = str(b)
remainder = str(remainder + z)
if a == 1:
b = 1
z = str(b)
remainder = str(remainder + z)
print(remainder)
asd = len(remainder)
for y in range(1, asd + 1):
binary[y:y + 1] = remainder[-y:-y - 1]
print("It's binary form is ", binary)
The problem is here:
for y in range(1, asd + 1):
binary[y:y + 1] = remainder[-y:-y - 1]
# ^^^^^^^^^^^^^ error
What do you expect this to do? Python strings are immutable: you cannot assign to a string slice. You can only use the value (right-hand side of an assignment, for example), or replace the variable's entire value.
I suspect that you're trying to reverse the string. Do it like this:
rev = remainder[::-1] # Whole string, but in reverse order
Now I'm using while loops to try and do this because I'm not too good at using for loops. As the title reads, I'm trying to print out a table which has the line number next to the length of each line.
Error: When I hit run all I get is the above print out (line and number of words with dashes below). I do not get a series of printouts of y and z
Note: I'm probably making this way harder than it needs to be
Code:
list1 = ['Lets go outside','pizza time','show me the money']
list2 = []
print('line number of words')
print('---- ---------------')
x = 0
len_l1 = len(list1)
while len_l1 > 0:
split_lis1 = list1[0+x].split(' ')
list2.append(split_lis1)
len_l1 -= 1
x += 1
while len_l1 > 0:
q = 1
y = len(list1) - len(list1) + q(x)
z = len(list2[0+x])
print(y, z)
len_l1 -= 1
x += 1
what I want the print out to look like:
line number of words
---- ---------------
0 3
1 2
2 4
Thanks.
Yes, you might have overcomplicated the solution as there are out of the box Python methods that help you easily solve problems like this. For iteration with indexes, use enumerate, in the example below we set the index to start at 1. We can also use some simple string formatting defined in fmt to ensure consistent spacings.
li = ['Lets go outside','pizza time','show me the money']
print('line number of words')
print('---- ---------------')
fmt = ('{} {}')
for idx, sentence in enumerate(li,1):
no_of_words = len(sentence.split())
print(fmt.format(idx, no_of_words))
Then simple use split to split the whitespaces and get the total number of words and let enumerate manage the whole thing for you.
>>
line number of words
---- ---------------
1 3
2 2
3 4
list1 = ['Lets go outside','pizza time','show me the money']
print('line number of words')
print('---- ---------------')
for i in range(0, len(list1)):
length = len(list1[i].split(" "))
print(i + 1, " ", length)
Check out python docs for range and for details.