Have a program request the user to enter a letter. Use nested loops to produce a pyramid pattern like this:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
ABCDCBA
ABCBA
ABA
A
The pattern should extend to the character entered. For example, the preceding pattern would result from an input value of E or e.
Here's what I've done so far and it almost gives the pattern with minor defects in the lower right hand part of the diamond.
L=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
letter=raw_input('Enter letter:')
g=letter.upper()
if g in L:
f=L.index(g)
a=f+1
for k in range(a,0,-1):
b=L[:a-k+1]
d=L[:a-k]
L3=[x for x in d]
e=L3[::-1]
print ' '*k + '%s'%''.join(b) + '%s'%''.join(e)
for k in range(a):
d=L[:a-1-k]
b=L[:a-k-1]
L3=[x for x in b]
e=L3[::-1]
print ' '*(k+2) + '%s'%''.join(d) + '%s'%''.join(e)
what I'm getting is something like this
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
ABCDDCBA
ABCCBA
ABBA
AA
There might be different ways to do this efficiently, but here is a simple, easy to understand solution (basic loops)
letter = raw_input('Enter Input: ')
if (len(letter) == 1):
if (letter.isalpha()):
# Retrieve the positon of the input letter
pos = ord(letter.upper()) - 64
# Prints upper part of the diamond
for i in range(1, pos + 1):
# Prints leading spaces for upper pyramid
for j in range(pos - i, 0, -1):
print(" "),
# Print numbers
# 2 for loops to print ascending and descending letters in a single row
for j in range(0, i):
print(chr(65+j)),
for j in range(i-1 , 0, -1):
print(chr(64+j)),
print
# Prints lower part of the diamond, This is just the reverse of the upper one
for i in range(pos -1 , 0, -1):
# Print leading space for lower pyramid
for j in range(pos - i, 0, -1):
print(" "),
for j in range(0, i):
print(chr(65+j)),
for j in range(i-1 , 0, -1):
print(chr(64+j)),
print
else:
print 'input a letter from the alphabet only'
else:
print 'enter one letter only'
Do half the pyramid, then reverse the array and print without the last (now first) element.
Related
Using just indexing and loops, how do you swap the positions of adjacent characters in a string, while making an exception for spaces?
I/P: HELLO WORLD
O/P: EHLLO OWLRD
This is the code I wrote:
s1=''
for j in range(0,len(s)-1,2):
if(skip==1):
print()
skip=0
elif(s[j].isspace()==False and s[j+1].isspace()==False):
s1=s1+s[j+1]+s[j]
elif(s[j].isspace()==False and s[j+1].isspace()==True):
s1=s1+s[j]+" "
elif(s[j].isspace()==True and s[j+1].isspace()==False and s[j+2].isspace()==False):
s1=s1+" "+s[j+2]+s[j+1]
skip=1
elif(s[j].isspace()==True and s[j+1].isspace()==False and s[j+2].isspace()==True):
s1=s1+" "+s[j+1]
print("new string is",s1)
What exactly am I doing wrong here?
inp = "HELLO WORLD"
expected = "EHLLO OWLRD"
for i in range(0, len(inp), 2): # iterate in steps of two
# check to make sure that we are not at end of string and charaters are not spaces
if i+1 < len(inp) and inp[i] != " " and inp[i+1] != " ":
# now do the string replacing
temp1 = inp[i]
temp2 = inp[i + 1]
inp = inp[:i] + temp2 + temp1 + inp[i+2:]
# output to indicate the new string is what we expect
print(inp)
print(expected)
print(inp == expected)
Another solution:
s = "HELLO WORLD"
out = []
for w in map(list, s.split(" ")):
for i in range(1, len(w), 2):
w[i], w[i - 1] = w[i - 1], w[i]
out.append("".join(w))
print(" ".join(out))
Prints:
EHLLO OWLRD
I have a 2d list [1,2,3,4],[4,3,3,1],[3,2,1,1],[2,2,2,1] and I want to print it out to match the following format.
0123
XXXXXXXX
0*1234*0
1*4331*1
2*3211*2
3*2221*3
XXXXXXXX
0123
It should not be hard coded and the length of the list = n so this list n=4 but if list n=5 there would be 5 digits per row and the number on the sides would go 0,1,2,3,4.
So far all I have is:
for row in board:
for column in row:
print(column, end="")
print("")
Which only outputs the list as:
1234
4331
3211
2221
please help me add all the special stuff.
so I find a solution for what you want to do however I think it can be improved a lot (not program quite a lot in python), but I'll leave it here anyways :)
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
for x in range(len(board)+4):
print("X", end="")
print()
for num,row in enumerate(board):
print(f"{num}*", end="")
for column in row:
print(column, end="")
print(f"*{num}", end="")
print("")
for x in range(len(board)+4):
print("X", end="")
print()
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
Well for the first line you pretty much print 2 spaces, followed by all the digits between 0 and the number of columns in your board. You can use the "range" function for this. Then you must print the correct amount of 'X'. The correct amount is number of columns + 4, I think you can see why.
You should keep a counter starting from 0. For each row you print, you must print the string value of the counter, followed by an asterisk(*), followed by your row, followed by an asterisk(*) and finally followed by the same counter value. You must increment the counter by one for each row.
The last 2 rows are the same as top 2.
I do not want to share my code because this is such a simple problem, I think solving it on your own will help you in the long run.
Probably an unpopular opinion, but I think these kinds of problems are really fun.
This solution formats the contents correctly, even if you change the number of rows, and even the number of items in each row.
def draw_board(board):
# determining the number of elements in a row,
# this is used for printing the X's
# and printing the spaced ranges (i.e. " 0123 ")
n = len(board[0])
# calculating the total width of the board,
# + 4 is because of the "0*...*0" situation
width = n + 4
# calculating margin of the spaced ranges
# (i.e. calculating how much space on each side)
margin = int(n / 2)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
# printing the XXXX
print("X" * width)
# printing the row index number,
# with the *,
# along with the numbers in the row,
# followed by the * and the row number
for row in range(len(board)):
print(str(row) + "*" + "".join(str(elem) for elem in board[row]) + "*" + str(row))
# printing the XXXX
print("X" * width)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
b = [
[1,2,3,4],
[4,3,3,1],
[3,2,1,1],
[2,2,2,1]
]
draw_board(b)
# OUTPUT:
# 0123
# XXXXXXXX
# 0*1234*0
# 1*4331*1
# 2*3211*2
# 3*2221*3
# XXXXXXXX
# 0123
Edited to remove my own tests and to reflect given problem.
I want to print a string in reverse and build it by printing letter by letter.
E.g - Word is: string
Ideal output is:
g
gn
gni
gnir
gnirt
gnirts
I want the user to be able to enter any word not just "String"
Code I have tried:
text = input('Enter a string: ')
reversed_text = ''
last_index = len(text) - 1
for i in range(last_index, -1, -5):
for i in range(last_index, -1, -1):
for i in range(last_index, -1, -1):
reversed_text += text[i]
print(reversed_text)
s=input("Word: ")
r=''
for char in reversed(s):
r+=char
print(r)
print ("Reversed word is %s " % (r))
This is the code I used, it works thank you for the answers
s='string'
r=''
for char in reversed(s):
r+=char
print(r)
This code does what you're asking.
A simple way of doing this with user input should be something on these lines:
newstring = ""
enterString = (str(input("Enter a string to be reversed:")))
count = 0
for i in reversed(enterString):
newstring += i
count += 1
print ("Reversed string %s is this: %s" % (count, newstring))
Output with count of how many times till it gets the last character:
Enter a string to be reversed:hello
Reversed string 1 is this: o
Reversed string 2 is this: ol
Reversed string 3 is this: oll
Reversed string 4 is this: olle
Reversed string 5 is this: olleh
This solution uses extended slice to reverse the word segments and separate each with a space. Other answers have separated the reversed word segments with a newline. Just replace ' '.join with '\n'.join if you require this behavior.
word = 'string'
reversed = '\n'.join(word[-1:i:-1] for i in range(-2, -2 - len(word), -1))
print(reversed)
edit: Separated reversed word segments with newline to reflect updated question.
I'm trying to complete challenge on HackerRank ( Day 6 : Let's review!) and I only did to print the even numbers on the same line, but I can't print the odd indexes that would be needed to complete the challenge.
This is my code:
word_check = input()
for index, char in enumerate (word_check):
if (index % 2 == 0):
print( char ,end ="" )
This is the most specific task:
Given a string, S , of length N that is indexed from 0 to N -1 , print its even-indexed and odd-indexed characters as space-separated strings on a single line.
Thanks!!!
RavDev
You can use slice notation for indexing the original string:
word_check[::2] + " " + word_check[1::2]
[::2] means "start at the beginning and skip every second element until we reach the end" and [1::2] means "start at the second element and skip every second element until we reach the end". Leaving out either start or stop arguments of the slice implies beginning or end of the sequence respectively. Leaving out the step argument implies a step size of 1.
Slice notation is a better approach, but if you want to use for loop and stick to your approach, you can do in this way:
even =''
odd=''
for index, char in enumerate (word_check):
if (index % 2 == 0):
even += char
else: odd += char
print (even, odd)
I am currently trying to solve the same problem. To get your answers on the same line, initiate two strings: one for even and one for odd. If the character's index is even, add it to the even string and vice versa. Here is my working code so far:
def indexes(word,letter):
result = list()
for i,x in enumerate(word):
if x == letter:
result.append(i)
return result
T = int(input())
if T <= 10 and T>= 1:
for i in range(T):
evenstring = ""
oddstring = ""
lastchar = False
S = input()
if len(S) >= 2 and len(S) <= 10000:
for index, char in enumerate (S):
if (index % 2 == 0):
evenstring += char
else: oddstring += char
if len(indexes(S, char)) > 1:
evenstring.replace(evenstring[evenstring.rfind(char)], '')
oddstring.replace(oddstring[oddstring.rfind(char)], '')
print(evenstring, oddstring)
Your next problem now is trying to remove any reoccurrences of duplicate letters from your final answer (they show up in other test cases)
Write a Python script that asks the user to enter two DNA
sequences with the same length. If the two sequences have
different lengths then output "Invalid input, the length must
be the same!" If inputs are valid, then compute how many dna bases at the
same position are equal in these two sequences and output the
answer "x positions of these two sequences have the same
character". x is the actual number, depending on the user's
input.
Below is what I have so far.
g=input('Enter DNA Sequence: ')
h=input('Enter Second DNA Sequence: ')
i=0
count=0
if len(g)!=len(h):
print('Invalid')
else:
while i<=len(g):
if g[i]==h[i]:
count+=1
i+=1
print(count)
Do this in your while loop instead (choose better variable names in your actual code):
for i, j in zip(g, h):
if i == j:
count += 1
OR replace the loop entirely with
count = sum(1 for i, j in zip(g, h) if i == j)
This will fix your index error. In general, you shouldn't be indexing lists in python, but looping over them. If you really want to index them, the i <= len(g) was the problem... it should be changed to i < len(g).
If you wanted to be really tricky, you could use the fact that True == 1 and False == 0:
count = sum(int(i == j) for i, j in zip(g, h))
The issue here is your loop condition. Your code gives you an IndexError; this means that you tried to access a character of a string, but there is no character at that index. What it means here is that i is greater than the len(g) - 1.
Consider this code:
while i<=len(g):
print(i)
i+=1
For g = "abc", it prints
0
1
2
3
Those are four numbers, not three! Since you start from 0, you must omit the last number, 3. You can adjust your condition as such:
while i < len(g):
# do things
But in Python, you should avoid using while loops when a for-loop will do. Here, you can use a for-loop to iterate through a sequence, and zip to combine two sequences into one.
for i, j in zip(g, h):
# i is the character of g, and j is the character of h
if i != j:
count += 1
You'll notice that you avoid the possibility of index errors and don't have to type so many [i]s.
i<=len(g) - replace this with i<len(g), because index counting starts from 0, not 1. This is the error you are facing. But in addition, your code is not very pretty...
First way to simplify it, keeping your structure:
for i in range(len(g)):
if g[i]==h[i]:
count+=1
Even better, you can actually make it a one-liner:
sum(g[i]==h[i] for i in range(len(g)))
Here the fact that True is evaluated to 1 in Python is used.
g = raw_input('Enter DNA Sequence: ')
h = raw_input('Enter Second DNA Sequence: ')
c = 0
count = 0
if len(g) != len(h):
print('Invalid')
else:
for i in g:
if g[c] != h[c]:
print "string does not match at : " + str(c)
count = count + 1
c = c + 1
print(count)
if(len(g)==len(h)):
print sum([1 for a,b in zip(g,h) if a==b])
Edit: Fixed the unclosed parens. Thanks for the comments, will definitely look at the generator solution and learn a bit - thanks!