I'm beginner in Python.
I am having difficulty resolving my problem:
Using nested for loops, print a right triangle of the character T on
the screen where the triangle is one character wide at its narrowest point and seven characters wide at its widest point:
T
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
and
T
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
Any idea?
I won't write a code for you but I can give you some hints:
nested loops means a loop inside another loop, in this case one loop is for iterating through consecutive lines, the second is to print characters in each line
the second example needs the same as the first, but you also need to check index of the inner loop and decide whether print space or 'T' character
I hope you already have got the answer :)
Pattern # 1
def triangle(n):
for i in range(1, n +1):
print ('T' * i).rjust(n, ' ')
triangle(7)
##Results >>>
T
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
Pattern # 2
def triangle1(n):
for i in range(1, n +1):
print ('T' * i)
triangle1(7)
# Results >>>>
T
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
Pattern generation by using only for loops
Here I have tried to generate the with the help of only for loops and will very generalized way. Purposefully I have not used any readily available functions so you can always optimize it further.
Pattern # 1
def triangle(n):
# Iterate through number of columns
for i in range(1, n +1):
s = ""
# Iterate through number of rows
for j in list(range(i)):
s += "T"
print s
triangle(7)
Pattern # 2
def triangle1(n):
# Iterate through number of columns
for i in range(1, n +1):
s = ""
# Iterate through number of rows
for j in list(range(i)):
blank = ""
# Generate 'blank spaces'
for k in (range(n - i)):
blank += " "
# Generate 'T'
s += "T"
print blank + s
triangle1(7)
Related
Very new to programming, very new to Python, I take different tasks online. The goal is to accomplish a lot without relying on external libraries.
One task I couldn't do today is this one:
Given a street name and a user provided number, create a table of user_provided_number columns and output the name of the street. Then, in the same table create the same output but reverse the street address. The space between the street addresses should be replaced with a "|". If the street name is too short to complete the row, render "?" for each remaining space.
Scenario Example:
Street address: Mystreet road, user provided number: 6
Expected output:
M y s t r e
e t | r o a
d | d a o r
| t e e r t
s y M ? ? ?
So far I managed to do the following:
strAddress = input("What's your street address?")
givenNumber = input("What's your favourite number from 1 to 10?")
reverseAddress = strAddress[::-1]
splitAddress = list(strAddress)
for row in range(0,int(len(strAddress)/givenNumber)):
for element in range(0,givenNumber):
print (splitAddress[element], end=' ')
print()
Why is this "array"(?) printing the same elements on each row? Assuming that the user provided "4" as their number, from the code I wrote I expected an output like that:
M y s t
r e e t
r o a
d
however the output is:
M y s t
M y s t
M y s t
First of all you should convert your givenNumber into int() since input() always returns string. Also you could convert your whole strAddress into itself and reversed version of itself to make accessing it easier. splitAddress wont be needed here since you can access string length and elements the same way as list in this example. In your first loop you're iterating over len(strAddress)/givenNumber which isn't enough since we need to print our Address two times (with reversed version) and we need to fill extending characters with ? so we need to round it up, without using math library we could do this like I've shown. Lastly splitAddress[element] here you access element'th index of your Address which will be number 0 - 6 on every iteration so we need take into account row to print more elements.
strAddress = input("What's your street address?")
givenNumber = int(input("What's your favourite number from 1 to 10?"))
strAddress += '|' + strAddress[::-1]
strAddress = strAddress.replace(' ', '|')
lines_to_print = len(strAddress)//givenNumber + (len(strAddress)%givenNumber>0)
for row in range(lines_to_print):
for element in range(givenNumber):
if row*givenNumber + element < len(strAddress):
print(strAddress[row*givenNumber + element], end=' ')
else:
print('? ', end='')
print()
Output for Mystreet road and 6
M y s t r e
e t | r o a
d | d a o r
| t e e r t
s y M ? ? ?
Your issue is that the nested loop starts back at 0 every time and ends at the same place every time. With your current code, the first loop is just declaring how many times to do the second loop, it doesn't have any input on the second loop. To fix this you could do for element in range(givenNumber*(row-1),givenNumber*(row)).
You never progress through the street address. row takes on values 0, 1, 2; but you never use those values to move along the address string. Look at what you print:
for element in range(0,givenNumber):
print (splitAddress[element], end=' ')
This prints the same four characters, regardless of the row value. Instead, you need to truly split the address into rows and print those. Alternately, you can compute the correct indices for each row: givenNumber*row + element.
Another solution would be to just build your string (replace characters, reverse it, ...) and then print this string character by character for each defined row. In order to calculate the number of filling characters for the last row, you could make use of the modulo operator with negative numbers.
Say your final string (chars) is 27 characters long and the given cell number (givenNumber) is 7. This would result in -27 % 7 = 1. So in this case one filling character would need to be added. chars += charFill * numCharFill will then just add the filling character x times at the end.
With an index you can then go through your string step by step and configure the output as required.
# strAddress = input("What's your street address?")
# givenNumber = int(input("What's your favourite number from 1 to 10?"))
strAddress = "Mystreet road"
givenNumber = 6
charFill = "?" # char to fill last row
chars = strAddress.replace(" ","|") # replace spaces in strAddress
chars += "|" + chars[::-1] # add reverse chars
numCharFill = -len(chars)%givenNumber # modulo of negative number
chars += charFill * numCharFill # add fill character x times
index = 0
for char in chars:
if index > 0 and not index%givenNumber:
print()
print(chars[index], end=' ')
index = index + 1
Try:
strAddress = input("What's your street address?\n")
givenNumber = int(input("What's your favourite number from 1 to 10?\n"))
charGroupSize = len(strAddress)/givenNumber
charGroups = [strAddress[i:i+givenNumber] for i in range(0, len(strAddress), givenNumber)]
for group in charGroups:
for char in group:
print (char, end=' ')
print()
Output:
What's your street address?
Mystreet road
What's your favourite number from 1 to 10?
4
M y s t
r e e t
r o a
d
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'
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.
I'm writting a program to that counts the number of times each letter appears in a text.
I'm trying to convert that into a graph, by print out the bar graph line by line. Slowly adding the space above the letter when the countdown reaches the # of times it appears.
import string
n=input("Enter Text, I wish you luck:")
list1=[] #Empty List
list2=list(" "*26) #26 space list
for a in string.ascii_uppercase:#from a-z
n1=n.count(a) #counts letters
list1.append(n1) #appends numbers
m=max(list1) #finds most occuring letter
c=m+1
while c!=0:
c=c-1
if c==0:
print(string.ascii_uppercase)
break
for x in list1: #suppose to check every term in list1
if x >c: #x is greater than countdowner
k=list1.index(x) #find term number
list2[k]="*" #replace blank with "*"
elif x==c:
#if x is equal to countdowner
k=list1.index(x) #find term number
list2[k]="*" #replaces that term place in list2
print(''.join(list2))
The code only accepts uppercase letters, and right now it only add letters to the countdown list one at a time. So when count reaches one appearance, and 3 letters appear once, it will only print a * on top of one of those letter.
Sample input: HELLO STACKOVERFLOW
*
* *
* * *
ABCDEFGHIJKLMNOPQRSTUVWXYZ
The problem is that k=list1.index(x) can only find the first occurrence of x in list1. So you could put a loop here, using the extended form of index():
list1.index(x, start, end)
which only looks for an index that lies in the range(start, end)
The loop would have to contain a try: ... except block to handle the ValueError exception.
But there's another way to handle this.
#! /usr/bin/env python
from string import ascii_uppercase
def bargraph(data):
data = data.upper()
print(data)
print(''.join(sorted(list(data))))
#Count number of occurences of each letter in data
counts = [data.count(a) for a in ascii_uppercase]
#A single row of the bar graph, initially full of spaces
row = list(" " * 26)
for c in range(max(counts), 0, -1):
for k in range(26):
if counts[k] == c:
row[k] = "*"
print(''.join(row))
print(ascii_uppercase)
def main():
#data = input("Enter Text, I wish you luck:")
data = "This is a test string for the bar graph function"
bargraph(data)
if __name__ == '__main__':
main()
My version of your program converts the string to upper case, prints it, and then sorts it and prints it again to make it easier to check that the bar printing section is doing what it's supposed to do.
It uses a list comprehension to build the list of character counts. It can be made even shorter by using a list comprehension to construct row.
def bargraph(data):
data = data.upper()
print(data)
print(''.join(sorted(list(data))))
#Count number of occurences of each letter in data
counts = [data.count(a) for a in ascii_uppercase]
for c in range(max(counts), 0, -1):
print(''.join(["*" if counts[k] >= c else " " for k in range(26)]))
print(ascii_uppercase)
output for both versions :)
THIS IS A TEST STRING FOR THE BAR GRAPH FUNCTION
AAABCEEFFGGHHHIIIINNNOOPRRRRSSSSTTTTTTU
*
*
* ***
* ** * ***
* ***** ** ***
*** ***** *** ****
ABCDEFGHIJKLMNOPQRSTUVWXYZ
edit
I should mention that there's a more efficient way to count the occurrences of each letter. The current method has to scan through the data string 26 times, once for each letter. That's a bit inefficient, especially if there's a lot of data to process. So it's better to just scan through the data once, and accumulate the counts. One way to do that is to use a dict.
#! /usr/bin/env python
from string import ascii_uppercase
def bargraph(data):
data = data.upper()
print(data)
print(''.join(sorted(list(data))))
#Count number of occurences of each letter in data
counts = dict(zip(ascii_uppercase, 26*(0,)))
for c in data:
if c.isupper():
counts[c] += 1
highcount = max(counts.values())
for c in range(highcount, 0, -1):
print(''.join([" *"[counts[k] >= c] for k in ascii_uppercase]))
print(ascii_uppercase)
def main():
#data = input("Enter Text, I wish you luck:")
data = "This is a test string for the bar graph function"
bargraph(data)
if __name__ == '__main__':
main()
I've also used a little trick to make the row printing step even more compact.
counts[k] >= c will either be False or True.
But Python lets us use boolean values as if they were int values, with False == 0 and True == 1.
Thus " *"[counts[k] >= c] results in " " if counts[k] >= c is False, and "*" if it's True.
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