Quantcast

Jump to content


Photo

Need some Python help


  • Please log in to reply
10 replies to this topic

#1 Abrar

Abrar
  • 157 posts

Posted 22 August 2010 - 03:23 PM


def print_digits(n):
    """
      >>> print_digits(13789)
      9 8 7 3 1
      >>> print_digits(39874613)
      3 1 6 4 7 8 9 3
      >>> print_digits(213141)
      1 4 1 3 1 2
    """

Write a body for print_digits so that it passes the given doctests.


Alright so I was just wondering as to how one would go about to solving this problem. I have no idea how I could split apart the integer that way, or even how to write it out in reverse. The only method that comes into mind that is similar is concatenation, and that is with strings. And it also does the opposite of what I'm trying to do with the integer.


I'm aware that I will most likely need to use a while loop to do this. But do I need a counter as well?

Thanks to anyone that can help out.

Edited by AbrarCat, 22 August 2010 - 03:31 PM.


#2 Waser Lave

Waser Lave

  • 25516 posts


Users Awards

Posted 22 August 2010 - 03:36 PM

def print_digits(n):

	print " ".join(reversed(list(str(n))))


#3 Abrar

Abrar
  • 157 posts

Posted 22 August 2010 - 04:00 PM

Ugh, but I didn't read about any of that stuff in my book. Is there perhaps a longer and less effective way to write that code? Also, you turned the integers into strings; I wouldn't be able to perform calculations on the individual digits. There is suppose to be an answer similar to the one required for this question:


Write a function sum_of_squares_of_digits that computes the sum of the squares of the digits of an integer passed to it. For example,sum_of_squares_of_digits(987) should return 194, since 9**2 + 8**2 + 7**2 == 81 + 64 + 49 == 194.



def sum_of_squares_of_digits(n):
    """
      >>> sum_of_squares_of_digits(1)
      1
      >>> sum_of_squares_of_digits(9)
      81
      >>> sum_of_squares_of_digits(11)
      2
      >>> sum_of_squares_of_digits(121)
      6
      >>> sum_of_squares_of_digits(987)
      194
    """


#4 Hydrogen

Hydrogen
  • Neocodex Co-Founder

  • 22213 posts


Users Awards

Posted 22 August 2010 - 04:06 PM

Converting to a string is an easy way to break up the digits of the number. You could always convert each individual digit back into an integer :p.

#5 Abrar

Abrar
  • 157 posts

Posted 22 August 2010 - 04:14 PM

Converting to a string is an easy way to break up the digits of the number. You could always convert each individual digit back into an integer :p.


Interesting. In my current book it hasn't gone over strings yet. This question was assigned before the topic of strings was covered.

#6 Waser Lave

Waser Lave

  • 25516 posts


Users Awards

Posted 22 August 2010 - 04:16 PM

def print_digits(n):
	digits = list(str(n))
	digits.reverse()
	
	digitStr = ""
	
	for digit in digits:
		digitStr += str(digit) + " "
	
	print digitStr

Obtuse enough for you?

#7 Abrar

Abrar
  • 157 posts

Posted 23 August 2010 - 06:00 PM

def print_digits(n):
	digits = list(str(n))
	digits.reverse()
	
	digitStr = ""
	
	for digit in digits:
		digitStr += str(digit) + " "
	
	print digitStr

Obtuse enough for you?


Yup, just about dumbed down enough. And today I went into the chapter about strings and learned about all of the things inside the string module. So it makes a lot more sense now.
Still weird how I was assigned that question before strings were explained.

#8 Hydrogen

Hydrogen
  • Neocodex Co-Founder

  • 22213 posts


Users Awards

Posted 23 August 2010 - 08:32 PM

Yup, just about dumbed down enough. And today I went into the chapter about strings and learned about all of the things inside the string module. So it makes a lot more sense now.
Still weird how I was assigned that question before strings were explained.

You don't have to do it through strings... you could just divide by 10000, then 1000, then 100, and so on to get the individual digits that you're looking for.

#9 Waser Lave

Waser Lave

  • 25516 posts


Users Awards

Posted 24 August 2010 - 02:49 AM

You don't have to do it through strings... you could just divide by 10000, then 1000, then 100, and so on to get the individual digits that you're looking for.


It's not very pythony that way though. :p

#10 Hydrogen

Hydrogen
  • Neocodex Co-Founder

  • 22213 posts


Users Awards

Posted 24 August 2010 - 11:29 AM

It's not very pythony that way though. :p

No, it isn't :p. Though I think the string conversion does it that way anyway :p. I'm not sure though. They could be doing something more clever... :p

#11 Abrar

Abrar
  • 157 posts

Posted 25 August 2010 - 03:26 PM

Man, I just find strings very confusing in Python.
But uhh, I made a new program which is pretty much a pong game. Well, the idea of making it pong wasn't my own. The book I'm reading instructed me to create a pong game.

But anyways, here's what I got [final product]:



from gasp import *

PLAYER1_WINS = 0
PLAYER2_WINS = 1
QUIT = -1


def hit(bx, by, r, px, py, h): #calculates if ball hits paddle
    if abs(py - by) < h and abs(px - bx) <= r:
        return True


def play_round(): 
    ball_x = 400       		#creates the  pong ball's properties
    ball_y = 300       		
    ball = Circle((ball_x, ball_y), 10, filled=True)
    dx = 4             		#creates the original ball movement direction
    dy = random_between(-5, 5)

    paddle_width = 15          #overall paddle properties
    paddle_height = 55
    
    paddle_x = 20              #player 1's paddle properties
    paddle_y = 300
    paddle = Box((paddle_x, paddle_y), paddle_width, paddle_height, filled = True, color = color.BLUE)

    paddle2_x = 780            #player 2's paddle properties
    paddle2_y = 300
    paddle2 = Box((paddle2_x, paddle2_y), paddle_width, paddle_height, filled = True, color = color.BLUE)

    while True:
        if ball_y >= 590 or ball_y <= 10: #bounce ball off of top and bottom walls
            dy *= -1
        ball_x += dx
        ball_y += dy

        #moves the ball with the updated x and y coordinates from previous 2 lines
        move_to(ball, (ball_x, ball_y))
        
        #user input section to move paddles; will not advance past the screen limit
        if key_pressed('a') and paddle_y <= 580:  
            paddle_y += 5
        elif key_pressed('s') and paddle_y >= 20:
            paddle_y -= 5
            
        if key_pressed('j') and paddle2_y <= 580:
            paddle2_y += 5
        elif key_pressed('k') and paddle2_y >= 20:
            paddle2_y -= 5
        
        if key_pressed('escape'): #have no idea if this will work until someone tests it <img src='http://www.neocodex.us/forum/public/style_emoticons/<#EMO_DIR#>/sad.gif' class='bbc_emoticon' alt=':(' />
            return QUIT

        #move paddles according to new values from user input
        move_to(paddle, (paddle_x, paddle_y))
        move_to(paddle2, (paddle2_x, paddle2_y))
        
        #hit function used to hit pong ball back 
        if hit(ball_x, ball_y, paddle_width, paddle_x, paddle_y, paddle_height):
            dx *= -1
        elif hit(ball_x, ball_y, paddle_width, paddle2_x, paddle2_y, paddle_height):
            dx *= -1

        '''once pong ball advances screen horizontally,
   		program will return 1[player 2] or 0[player 1] according to
   		which side the ball had advanced on
        '''
        if ball_x >= 810:
            remove_from_screen(ball)
            remove_from_screen(paddle)
            remove_from_screen(paddle2)
            return PLAYER1_WINS    
        elif ball_x <= -10:
            remove_from_screen(ball)
            remove_from_screen(paddle)
            remove_from_screen(paddle2)
            return PLAYER2_WINS

        update_when('next_tick')


def play_game():
    player1_score = 0
    player2_score = 0

    while True:
        #show player scores at top
        pmsg = Text("Player 1: %d Points" % player1_score, (10, 570), size=24)
        cmsg = Text("Player 2: %d Points" % player2_score, (640, 570), size=24)
        sleep(3)
        remove_from_screen(pmsg)
        remove_from_screen(cmsg)

        result = play_round() #initiate single round of pong

        if result == PLAYER1_WINS:
            player1_score += 1
        elif result == PLAYER2_WINS:
            player2_score += 1
        else:
            return QUIT

        if player1_score == 5:
            return PLAYER1_WINS
        elif player2_score == 5:
            return PLAYER2_WINS


begin_graphics(800, 600, title="Catch", background=color.WHITE) #initiate Gasp
set_speed(120) #frame rate speed

result = play_game() #initiate game of pong 

if result == PLAYER1_WINS:
    Text("Player 1 Wins!", (340, 290), size=32)
elif result == PLAYER2_WINS:
    Text("Player 2 Wins!", (340, 290), size=32)

sleep(4)

end_graphics() #currently doesnt work ;(, stupid PC Gasp issues...


And well most things in the code seem to be OK and the game functions with no bugs [as far as I've seen]. But for some odd reason user input is just not allowed. The coding is fine but when I press any of the paddle movement keys they just wont work. Does anyone have the Gasp module so they could test this out? Since I usually have problems in general with Gasp [I cant close it without my computer freezing >.<].

Thanks. Sorry.

Edit: Holy crap I never realized how incredibly long that was O_o
Well then, I'll add in an extra sorry beside that thanks. :$

Edited by AbrarCat, 25 August 2010 - 03:27 PM.



2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users