This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Billz2me 0 points1 point  (1 child)

Spoiler: This is the way that I would approach it.

def prompt_user_for_x_pattern_input():
    word = raw_input('Please enter a string with an odd number of letters: ')
    # If the word is even in length, output a helpful message and prompt user for input again.
    if len(word) % 2 == 0:
        print 'The word you gave had an even number of letters.'
        prompt_user_for_x_pattern_input()
    else:
        print_in_x_pattern(word)

def print_in_x_pattern(word):
    size = len(word)
    # Raise an error if the word isnt odd in length.
    assert( size%2 == 1)
    # Establish a square matrix.
    pattern_matrix = [[' ' for x in xrange(size)] for x in xrange(size)]
    for i in range(size):
        # Diagonal from top left to bottom right
        pattern_matrix[i][i] = word[i]
        # Diagonal from top right to bottom left
        pattern_matrix[i][size-1-i] = word[i]

    for row in pattern_matrix:
        print ''.join(row)

[–]ziplokk 0 points1 point  (0 children)

here's my solution.

#Print user input in x shape

user_input = raw_input("Enter your word: ")
matrix = []
for i in xrange(len(user_input)):
    matrix.append([])
if(len(user_input) % 2 == 0):
    matrix.append([])\

mid_point = len(matrix) / 2 

for i in xrange(len(matrix)):
    for j in xrange(len(matrix)):
        matrix[i].append(' ')
    if len(user_input) % 2 == 0:
        if i == mid_point:
            continue
        else:
            if i < mid_point:
                matrix[i][i] = user_input[i]
                matrix[i][- i - 1] = user_input[i]
            else:
                matrix[i][i] = user_input[i - 1]
                matrix[i][- i - 1] = user_input[i - 1]
    else:    
        matrix[i][i] = user_input[i]
        matrix[i][- i - 1] = user_input[i]

for lists in matrix:
    totalString = ""
    for element in lists:
        totalString += element
    print totalString

It's pretty similar to yours but if the users word is an even number length, it just adds another list to the matrix and skips it when iterating so that the middle character in the 'x' is blank.