labNo
float64
1
10
taskNo
float64
0
4
questioner
stringclasses
2 values
question
stringlengths
9
201
code
stringlengths
18
30.3k
startLine
float64
0
192
endLine
float64
0
196
questionType
stringclasses
4 values
answer
stringlengths
2
905
src
stringclasses
3 values
code_processed
stringlengths
12
28.3k
id
stringlengths
2
5
raw_code
stringlengths
20
30.3k
raw_comment
stringlengths
10
242
comment
stringlengths
9
207
q_code
stringlengths
66
30.3k
2
0
TA
Please explain what the flag is for Tasks 1 and 2.
from cs1robots import * load_world('worlds/harvest3.wld') def move(n=1): for i in range(n): h.move() def left(): h.turn_left() def right(): for i in range(3): left() h = Robot(beepers=36) h.set_trace('blue') move() def oneStep(): if h.on_beeper(): h.pick_beeper() move() def oneLine(flag): for i in range(5): oneStep() if h.on_beeper(): h.pick_beeper() if flag % 2 == 0: left() move() left() else: right() move() right() for i in range(6): oneLine(i)
20
35
variable
Yes, in 1,2, the flag is a variable indicating whether the current line is an even number or an odd number, and is used to determine whether the current line ends and rotates left or right.
cs1qa
null
null
null
null
null
Question: Please explain what the flag is for Tasks 1 and 2. Code: from cs1robots import * load_world('worlds/harvest3.wld') def move(n=1): for i in range(n): h.move() def left(): h.turn_left() def right(): for i in range(3): left() h = Robot(beepers=36) h.set_trace('blue') move() def oneStep(): if h.on_beeper(): h.pick_beeper() move() def oneLine(flag): for i in range(5): oneStep() if h.on_beeper(): h.pick_beeper() if flag % 2 == 0: left() move() left() else: right() move() right() for i in range(6): oneLine(i)
2
0
TA
Could you briefly explain what the move_and_pick function does?
from cs1robots import * load_world('worlds/harvest3.wld') hubo = Robot() hubo.set_trace('blue') def move_and_pick() : hubo.move() if hubo.on_beeper() : hubo.pick_beeper() def turn_right(): hubo.turn_left() hubo.turn_left() hubo.turn_left() for i in range (2): while hubo.front_is_clear(): move_and_pick() for i in range (2): hubo.turn_left() move_and_pick() for i in range (4): move_and_pick() for i in range (2): turn_right() move_and_pick() while hubo.front_is_clear(): move_and_pick() for i in range (2): hubo.turn_left() move_and_pick() for i in range (4): move_and_pick()
5
8
variable
It is a function that moves one space and picks up if there is a beeper in the moved position.
cs1qa
null
null
null
null
null
Question: Could you briefly explain what the move_and_pick function does? Code: from cs1robots import * load_world('worlds/harvest3.wld') hubo = Robot() hubo.set_trace('blue') def move_and_pick() : hubo.move() if hubo.on_beeper() : hubo.pick_beeper() def turn_right(): hubo.turn_left() hubo.turn_left() hubo.turn_left() for i in range (2): while hubo.front_is_clear(): move_and_pick() for i in range (2): hubo.turn_left() move_and_pick() for i in range (4): move_and_pick() for i in range (2): turn_right() move_and_pick() while hubo.front_is_clear(): move_and_pick() for i in range (2): hubo.turn_left() move_and_pick() for i in range (4): move_and_pick()
6
2
TA
check function Please explain
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ # 3-2-1. shuffle the card list random.shuffle(cards) ################################################################ def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if i in correct_list: # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### if num1 in correct_list or num2 in correct_list: return False elif num1 == num2: return False elif not 0 <= num1 <=23 or not 0 <= num2 <=23: return False else: return True def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### correct_list.append(num1) correct_list.append(num2) if cards[num1][1] == cards[num2][1]: print_cards() return True else: print_cards() correct_list.pop() correct_list.pop() print_cards() return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") for i in range(24): correct_list.append(i) print_cards() for i in range(24): correct_list.remove(i) print_cards() ############################################################################### while len(correct_list) <=23: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") tries = tries + 1 ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
81
101
variable
After adding the two drawn cards to the correct list, if they are the same, print true and send out true, and if the two cards are different, remove them from the correct list and send false
cs1qa
null
null
null
null
null
Question: check function Please explain Code: from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ # 3-2-1. shuffle the card list random.shuffle(cards) ################################################################ def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if i in correct_list: # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### if num1 in correct_list or num2 in correct_list: return False elif num1 == num2: return False elif not 0 <= num1 <=23 or not 0 <= num2 <=23: return False else: return True def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### correct_list.append(num1) correct_list.append(num2) if cards[num1][1] == cards[num2][1]: print_cards() return True else: print_cards() correct_list.pop() correct_list.pop() print_cards() return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") for i in range(24): correct_list.append(i) print_cards() for i in range(24): correct_list.remove(i) print_cards() ############################################################################### while len(correct_list) <=23: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") tries = tries + 1 ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
8
2
TA
What about before the decimal point?
import elice_utils f = open('tpmon.txt', 'r') lines = f.readlines() f.close() avg_tp = [] year = 1723 f = open('tpmon.csv', 'w') for line in lines[1:]: temporary_list = line.split(' ') for i in range(temporary_list.count('')): temporary_list.remove('') temporary_list.remove('\n') temporary_str = str(year)+','+','.join(temporary_list)+'\n' f.write(temporary_str) temporary_list = list(map(float, temporary_list)) avg_winter = round((temporary_list[0] + temporary_list[1]) / 2, 1) avg_summer = round((temporary_list[5] + temporary_list[6]) / 2, 1) avg_tp.append((year, avg_winter, avg_summer)) year = year + 1 f.close() for i in range(len(avg_tp)): print('%d: %.1f / %.1f' % (avg_tp[i][0], avg_tp[i][1], avg_tp[i][2])) elice_utils.send_file('tpmon.csv')
27
27
variable
Make the string length 6 and align it to the far right.
cs1qa
null
null
null
null
null
Question: What about before the decimal point? Code: import elice_utils f = open('tpmon.txt', 'r') lines = f.readlines() f.close() avg_tp = [] year = 1723 f = open('tpmon.csv', 'w') for line in lines[1:]: temporary_list = line.split(' ') for i in range(temporary_list.count('')): temporary_list.remove('') temporary_list.remove('\n') temporary_str = str(year)+','+','.join(temporary_list)+'\n' f.write(temporary_str) temporary_list = list(map(float, temporary_list)) avg_winter = round((temporary_list[0] + temporary_list[1]) / 2, 1) avg_summer = round((temporary_list[5] + temporary_list[6]) / 2, 1) avg_tp.append((year, avg_winter, avg_summer)) year = year + 1 f.close() for i in range(len(avg_tp)): print('%d: %.1f / %.1f' % (avg_tp[i][0], avg_tp[i][1], avg_tp[i][2])) elice_utils.send_file('tpmon.csv')
6
2
TA
Can you briefly explain the role of correct_list?
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards j=0 k=0 i_w = 70 i_h = 90 for i in range(6): for h in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ random.shuffle(cards)# 3-2-1. shuffle the card list ################################################################ for i in range(len(num_pads)): if not i in correct_list: cards[i][0].moveTo(i_w + k, i_h+j) canvas.add(cards[i][0]) k += 100 if k % 600 == 0: k = 0 j += 130 time.sleep(1) for i in range(len(num_pads)): if not i in correct_list: canvas.remove(cards[i][0]) k += 100 if k % 600 == 0: k = 0 j += 130 def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if i in correct_list: # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### a=[] for i in range(24): a.append(i) if num1==num2 or num1 in correct_list or num2 in correct_list or num1 not in a or num2 not in a: return False return True def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### global tries if cards[num1][1]==cards[num2][1]: correct_list.append(num1) correct_list.append(num2) tries+=1 return True else: canvas.add(cards[num1][0]) canvas.add(cards[num2][0]) time.sleep(1) canvas.remove(cards[num1][0]) canvas.remove(cards[num2][0]) tries+=1 return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while not len(correct_list)==24: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs if tries==1: print(str(tries) + "st try. You got " + str(len(correct_list)//2) + " pairs.") elif tries==2: print(str(tries) + "nd try. You got " + str(len(correct_list)//2) + " pairs.") elif tries==3: print(str(tries) + "rd try. You got " + str(len(correct_list)//2) + " pairs.") else: print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") print_cards() else: print("Wrong!") print_cards() ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
0
150
variable
Matched number pad keeps showing matched cards as a list of numbers, used to indicate You got-pairs
cs1qa
null
null
null
null
null
Question: Can you briefly explain the role of correct_list? Code: from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards j=0 k=0 i_w = 70 i_h = 90 for i in range(6): for h in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ random.shuffle(cards)# 3-2-1. shuffle the card list ################################################################ for i in range(len(num_pads)): if not i in correct_list: cards[i][0].moveTo(i_w + k, i_h+j) canvas.add(cards[i][0]) k += 100 if k % 600 == 0: k = 0 j += 130 time.sleep(1) for i in range(len(num_pads)): if not i in correct_list: canvas.remove(cards[i][0]) k += 100 if k % 600 == 0: k = 0 j += 130 def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if i in correct_list: # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### a=[] for i in range(24): a.append(i) if num1==num2 or num1 in correct_list or num2 in correct_list or num1 not in a or num2 not in a: return False return True def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### global tries if cards[num1][1]==cards[num2][1]: correct_list.append(num1) correct_list.append(num2) tries+=1 return True else: canvas.add(cards[num1][0]) canvas.add(cards[num2][0]) time.sleep(1) canvas.remove(cards[num1][0]) canvas.remove(cards[num2][0]) tries+=1 return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while not len(correct_list)==24: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs if tries==1: print(str(tries) + "st try. You got " + str(len(correct_list)//2) + " pairs.") elif tries==2: print(str(tries) + "nd try. You got " + str(len(correct_list)//2) + " pairs.") elif tries==3: print(str(tries) + "rd try. You got " + str(len(correct_list)//2) + " pairs.") else: print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") print_cards() else: print("Wrong!") print_cards() ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
2
0
TA
What is the role of the one_round() function in Task1?
from cs1robots import * load_world('worlds/harvest3.wld') hubo = Robot(beepers=1) hubo.set_trace('blue') def turn_right(): hubo.turn_left() hubo.turn_left() hubo.turn_left() def collect_beeper(): if hubo.on_beeper(): hubo.pick_beeper() def go_straight(): for i in range(5): hubo.move() collect_beeper() def one_round(): go_straight() hubo.turn_left() hubo.move() collect_beeper() hubo.turn_left() go_straight() turn_right() hubo.move() collect_beeper() turn_right() hubo.move() collect_beeper() for i in range(2): one_round() go_straight() hubo.turn_left() hubo.move() collect_beeper() hubo.turn_left() go_straight()
17
27
variable
In task 1, the robot repeats going right and left, so we made it a function and repeated it.
cs1qa
null
null
null
null
null
Question: What is the role of the one_round() function in Task1? Code: from cs1robots import * load_world('worlds/harvest3.wld') hubo = Robot(beepers=1) hubo.set_trace('blue') def turn_right(): hubo.turn_left() hubo.turn_left() hubo.turn_left() def collect_beeper(): if hubo.on_beeper(): hubo.pick_beeper() def go_straight(): for i in range(5): hubo.move() collect_beeper() def one_round(): go_straight() hubo.turn_left() hubo.move() collect_beeper() hubo.turn_left() go_straight() turn_right() hubo.move() collect_beeper() turn_right() hubo.move() collect_beeper() for i in range(2): one_round() go_straight() hubo.turn_left() hubo.move() collect_beeper() hubo.turn_left() go_straight()
9
1
TA
Please explain how you implemented hand_value in No. 2~!
import random from cs1graphics import * img_path = './images/' suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] face_names = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] value = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] bj_board = Canvas(600, 400, 'dark green', 'Black Jack 101') """ Define the Card class """ class Card: def __init__(self, suit, face, value): self.suit = suit self.face = face self.value = value self.img = Image('./images/'+suit+'_'+face+'.png') self.state = True def create_deck(number = 1): """ Create a list("deck") of all 52 cards, shuffle them and return the list. The list 'deck' have to include Card objects A Card is represented by a object with four attributes: the face, the suit, value, state, and the image object First, Have to define class 'Card' """ temp_deck = [] for suit in suit_names: for i in range(13): temp_deck.append(Card(suit, face_names[i], value[i])) random.shuffle(temp_deck) return temp_deck def hand_value(hand): """ hand is a list including card objects Compute the value of the cards in the list "hand" """ value_sum = 0 for card in hand: value_sum += card.value return value_sum def card_string(card): """ Parameter "card" is a Card object Return a nice string to represent a card (sucn as "a King of Spades" or "an Ace of Diamonds") """ return_string = '' if card.face in ['Ace','8']: return_string += 'an ' else: return_string += 'a ' return_string += (card.face + ' of '+ card.suit) return return_string def ask_yesno(prompt): """ Display the text prompt and let's the user enter a string. If the user enters "y", the function returns "True", and if the user enters "n", the function returns "False". If the user enters anything else, the function prints "I beg your pardon!", and asks again, repreting this until the user has entered a correct string. """ while True: answer = input(prompt) if answer == 'y': return True elif answer == 'n': return False else: print("I beg your pardon!") def draw_card(dealer,player): """ This funuction add the cards of dealer and player to canvas, bj_board. If the state of each Card object is false, then you have to show the hidden card image(Back.png). The dealer's first card is hidden state. The parameter dealer and player are List objects including Card Objects. The start position of dealer's card is (100,100). The start position of player's card is (100,300). You can use the following methods for positioning images and text: Image() Object, Text() Object, moveTo() method, setDepth() method. You should use help function - help('cs1graphics.Image') -> about Image(), moveTo(), setDepth() help('cs1graphics.Text') -> about Text(),moveTo(), setDepth() """ depth = 100 x0,y0 = 100,100 x1,y1 = 100,300 back_image = Image('./images/Back.png') dealer_total = 0 dealer_hidden = False player_total = 0 bj_board.clear() for card in dealer: if card.state: card.img.moveTo(x0, y0) bj_board.add(card.img) dealer_total += card.value else: back_image.moveTo(x0, y0) bj_board.add(back_image) dealer_hidden = True x0 += 20 for card in player: card.img.moveTo(x1, y1) bj_board.add(card.img) player_total += card.value x1 += 20 if dealer_hidden: dealer_text = Text(message = "The dealer's Total : "+str(dealer_total)+"+@") else: dealer_text = Text(message = "The dealer's Total : "+str(dealer_total)) dealer_text.moveTo(500, y0) dealer_text.setFontColor("yellow") bj_board.add(dealer_text) player_text = Text(message = "Your Total : "+str(player_total)) player_text.moveTo(500, y1) player_text.setJustification("right") bj_board.add(player_text) def main(): deck = [] while True: # prompt for starting a new game and create a deck print ("Welcome to Black Jack 101!\n") if len(deck) < 12: deck = create_deck() # create two hands of dealer and player dealer = [] player = [] # initial two dealings card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt a hidden card") card.state=False dealer.append(card) card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # player's turn to draw cards while hand_value(player) < 21 and ask_yesno("Would you like another card? (y/n) "): # draw a card for the player card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # if the player's score is over 21, the player loses immediately. if hand_value(player) > 21: print ("You went over 21! You lost.") dealer[0].state = True draw_card(dealer,player) else: # draw cards for the dealer while the dealer's score is less than 17 print ("\nThe dealer's hidden card was " + card_string(dealer[0])) while hand_value(dealer) < 17: card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("The dealer's total is", hand_value(dealer)) dealer[0].state = True draw_card(dealer,player) # summary player_total = hand_value(player) dealer_total = hand_value(dealer) print ("\nYour total is", player_total) print ("The dealer's total is", dealer_total) if dealer_total > 21: print ("The dealer went over 21! You win!") else: if player_total > dealer_total: print ("You win!") elif player_total < dealer_total: print ("You lost!") else: print ("You have a tie!") if not ask_yesno("\nPlay another round? (y/n) "): bj_board.close() break help('cs1graphics.Text') main()
47
58
variable
hand_value was added by extracting only the values of the cards in the hand list.
cs1qa
null
null
null
null
null
Question: Please explain how you implemented hand_value in No. 2~! Code: import random from cs1graphics import * img_path = './images/' suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] face_names = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] value = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] bj_board = Canvas(600, 400, 'dark green', 'Black Jack 101') """ Define the Card class """ class Card: def __init__(self, suit, face, value): self.suit = suit self.face = face self.value = value self.img = Image('./images/'+suit+'_'+face+'.png') self.state = True def create_deck(number = 1): """ Create a list("deck") of all 52 cards, shuffle them and return the list. The list 'deck' have to include Card objects A Card is represented by a object with four attributes: the face, the suit, value, state, and the image object First, Have to define class 'Card' """ temp_deck = [] for suit in suit_names: for i in range(13): temp_deck.append(Card(suit, face_names[i], value[i])) random.shuffle(temp_deck) return temp_deck def hand_value(hand): """ hand is a list including card objects Compute the value of the cards in the list "hand" """ value_sum = 0 for card in hand: value_sum += card.value return value_sum def card_string(card): """ Parameter "card" is a Card object Return a nice string to represent a card (sucn as "a King of Spades" or "an Ace of Diamonds") """ return_string = '' if card.face in ['Ace','8']: return_string += 'an ' else: return_string += 'a ' return_string += (card.face + ' of '+ card.suit) return return_string def ask_yesno(prompt): """ Display the text prompt and let's the user enter a string. If the user enters "y", the function returns "True", and if the user enters "n", the function returns "False". If the user enters anything else, the function prints "I beg your pardon!", and asks again, repreting this until the user has entered a correct string. """ while True: answer = input(prompt) if answer == 'y': return True elif answer == 'n': return False else: print("I beg your pardon!") def draw_card(dealer,player): """ This funuction add the cards of dealer and player to canvas, bj_board. If the state of each Card object is false, then you have to show the hidden card image(Back.png). The dealer's first card is hidden state. The parameter dealer and player are List objects including Card Objects. The start position of dealer's card is (100,100). The start position of player's card is (100,300). You can use the following methods for positioning images and text: Image() Object, Text() Object, moveTo() method, setDepth() method. You should use help function - help('cs1graphics.Image') -> about Image(), moveTo(), setDepth() help('cs1graphics.Text') -> about Text(),moveTo(), setDepth() """ depth = 100 x0,y0 = 100,100 x1,y1 = 100,300 back_image = Image('./images/Back.png') dealer_total = 0 dealer_hidden = False player_total = 0 bj_board.clear() for card in dealer: if card.state: card.img.moveTo(x0, y0) bj_board.add(card.img) dealer_total += card.value else: back_image.moveTo(x0, y0) bj_board.add(back_image) dealer_hidden = True x0 += 20 for card in player: card.img.moveTo(x1, y1) bj_board.add(card.img) player_total += card.value x1 += 20 if dealer_hidden: dealer_text = Text(message = "The dealer's Total : "+str(dealer_total)+"+@") else: dealer_text = Text(message = "The dealer's Total : "+str(dealer_total)) dealer_text.moveTo(500, y0) dealer_text.setFontColor("yellow") bj_board.add(dealer_text) player_text = Text(message = "Your Total : "+str(player_total)) player_text.moveTo(500, y1) player_text.setJustification("right") bj_board.add(player_text) def main(): deck = [] while True: # prompt for starting a new game and create a deck print ("Welcome to Black Jack 101!\n") if len(deck) < 12: deck = create_deck() # create two hands of dealer and player dealer = [] player = [] # initial two dealings card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt a hidden card") card.state=False dealer.append(card) card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # player's turn to draw cards while hand_value(player) < 21 and ask_yesno("Would you like another card? (y/n) "): # draw a card for the player card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # if the player's score is over 21, the player loses immediately. if hand_value(player) > 21: print ("You went over 21! You lost.") dealer[0].state = True draw_card(dealer,player) else: # draw cards for the dealer while the dealer's score is less than 17 print ("\nThe dealer's hidden card was " + card_string(dealer[0])) while hand_value(dealer) < 17: card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("The dealer's total is", hand_value(dealer)) dealer[0].state = True draw_card(dealer,player) # summary player_total = hand_value(player) dealer_total = hand_value(dealer) print ("\nYour total is", player_total) print ("The dealer's total is", dealer_total) if dealer_total > 21: print ("The dealer went over 21! You win!") else: if player_total > dealer_total: print ("You win!") elif player_total < dealer_total: print ("You lost!") else: print ("You have a tie!") if not ask_yesno("\nPlay another round? (y/n) "): bj_board.close() break help('cs1graphics.Text') main()
3
3
TA
Yes, simply explain closing_door!
from cs1robots import * # Your code must work for both of the worlds below. load_world('worlds/rain1.wld') # load_world('worlds/rain2.wld') # Initialize your robot at the door of the house. my_robot = Robot(beepers=100, avenue=2, street=6, orientation='E') # Now close all the windows in the house! my_robot.set_pause(.1) def turn_right(): for i in range(3): my_robot.turn_left() def closing_door(): if my_robot.left_is_clear(): my_robot.drop_beeper() my_robot.move() if my_robot.left_is_clear(): turn_right() turn_right() my_robot.move() my_robot.pick_beeper() turn_right() my_robot.move() else : my_robot.move() my_robot.move() my_robot.drop_beeper() my_robot.turn_left() my_robot.move() while not my_robot.on_beeper(): if my_robot.front_is_clear(): closing_door() else : turn_right() my_robot.pick_beeper() my_robot.turn_left()
15
27
variable
Because all the windows are 1 space If the left side is empty, drop the beeper Even after moving forward, if it is empty, it is judged as a corner, not a window. Come back and retrieve the beeper and turn Or keep going It’s the function set up like that
cs1qa
null
null
null
null
null
Question: Yes, simply explain closing_door! Code: from cs1robots import * # Your code must work for both of the worlds below. load_world('worlds/rain1.wld') # load_world('worlds/rain2.wld') # Initialize your robot at the door of the house. my_robot = Robot(beepers=100, avenue=2, street=6, orientation='E') # Now close all the windows in the house! my_robot.set_pause(.1) def turn_right(): for i in range(3): my_robot.turn_left() def closing_door(): if my_robot.left_is_clear(): my_robot.drop_beeper() my_robot.move() if my_robot.left_is_clear(): turn_right() turn_right() my_robot.move() my_robot.pick_beeper() turn_right() my_robot.move() else : my_robot.move() my_robot.move() my_robot.drop_beeper() my_robot.turn_left() my_robot.move() while not my_robot.on_beeper(): if my_robot.front_is_clear(): closing_door() else : turn_right() my_robot.pick_beeper() my_robot.turn_left()
10
0
TA
Briefly explain the three methods of butterfly among the implemented classes.
from cs1graphics import * from time import sleep _scene = None _world = None def create_world(): global _scene, _world if _scene: raise RuntimeError("A world already exists!") _world = _World(500, 300) _scene = Canvas(_world.width, _world.height) _scene.setTitle("Butterfly") _scene.setBackgroundColor("light blue") _world.draw_scene() class _World(object): def __init__(self, width, height): self.width = width self.height = height def draw_scene(self): """ draw background here Don't forget _scene.add(name) """ ground = Rectangle(600, 100) _scene.add(ground) ground.setFillColor("green") ground.setBorderColor("green") ground.moveTo(200, 250) class butterfly(object): def __init__(self, wing_color,x, y): wing1 = Layer() wing2 = Layer() wing1 = Polygon(Point(200+x,150+y),Point(240+x,100+y),Point(240+x,140+y)) wing1.setFillColor(wing_color) wing2 = Polygon(Point(280+x,130+y),Point(240+x,140+y),Point(240+x,180+y)) wing2.setFillColor(wing_color) self.wing1 = wing1 self.wing2 = wing2 _scene.add(self.wing1) _scene.add(self.wing2) def fly(self): self.wing1.adjustReference(40,-10) self.wing2.adjustReference(-40,10) for i in range(50): if(i%20 <10): self.wing1.rotate(-2) self.wing2.rotate(2) else: self.wing1.rotate(2) self.wing2.rotate(-2) sleep(0.05) def move(self, x, y): for i in range(100): self.wing1.move(x/100, y/100) self.wing2.move(x/100, y/100) if(i%(20) <10): self.wing1.rotate(-2) self.wing2.rotate(2) else: self.wing1.rotate(2) self.wing2.rotate(-2) sleep(0.05) def change(self, color): self.wing1.setFillColor(color) self.wing2.setFillColor(color) """ define your own objects, e.g. Mario and Mushroom class Mushroom (object): def __init__(self, x, y): mushroom = Layer() uppermush = Ellipse(38, 18, Point(x, y)) uppermush.setFillColor('red') uppermush.setDepth(52) mushroom.add(lowermush) lowermush = Ellipse(35, 25, Point(x, y+8)) lowermush.setFillColor('beige') lowermush.setDepth(53) mushroom.add(uppermush) mushroom.setDepth(52) self.layer = mushroom # save mushroom shape in the class _scene.add(self.layer) # add to global Canvas class Mario (object): def __init__(self, ... self.layer = Layer() ... _scene.add(self.layer) """ create_world() # define your objects, e.g. mario = Mario('blue', 'normal') # write your animation scenario here a = butterfly('yellow', 10,10) a.fly() a.move(100,0) a.change('red')
47
71
variable
Fly makes the wings move back and forth in place, and move moves the wings as much as x, y and moves at constant speed over 5 seconds, and change is a method to change the wings to the desired color.
cs1qa
null
null
null
null
null
Question: Briefly explain the three methods of butterfly among the implemented classes. Code: from cs1graphics import * from time import sleep _scene = None _world = None def create_world(): global _scene, _world if _scene: raise RuntimeError("A world already exists!") _world = _World(500, 300) _scene = Canvas(_world.width, _world.height) _scene.setTitle("Butterfly") _scene.setBackgroundColor("light blue") _world.draw_scene() class _World(object): def __init__(self, width, height): self.width = width self.height = height def draw_scene(self): """ draw background here Don't forget _scene.add(name) """ ground = Rectangle(600, 100) _scene.add(ground) ground.setFillColor("green") ground.setBorderColor("green") ground.moveTo(200, 250) class butterfly(object): def __init__(self, wing_color,x, y): wing1 = Layer() wing2 = Layer() wing1 = Polygon(Point(200+x,150+y),Point(240+x,100+y),Point(240+x,140+y)) wing1.setFillColor(wing_color) wing2 = Polygon(Point(280+x,130+y),Point(240+x,140+y),Point(240+x,180+y)) wing2.setFillColor(wing_color) self.wing1 = wing1 self.wing2 = wing2 _scene.add(self.wing1) _scene.add(self.wing2) def fly(self): self.wing1.adjustReference(40,-10) self.wing2.adjustReference(-40,10) for i in range(50): if(i%20 <10): self.wing1.rotate(-2) self.wing2.rotate(2) else: self.wing1.rotate(2) self.wing2.rotate(-2) sleep(0.05) def move(self, x, y): for i in range(100): self.wing1.move(x/100, y/100) self.wing2.move(x/100, y/100) if(i%(20) <10): self.wing1.rotate(-2) self.wing2.rotate(2) else: self.wing1.rotate(2) self.wing2.rotate(-2) sleep(0.05) def change(self, color): self.wing1.setFillColor(color) self.wing2.setFillColor(color) """ define your own objects, e.g. Mario and Mushroom class Mushroom (object): def __init__(self, x, y): mushroom = Layer() uppermush = Ellipse(38, 18, Point(x, y)) uppermush.setFillColor('red') uppermush.setDepth(52) mushroom.add(lowermush) lowermush = Ellipse(35, 25, Point(x, y+8)) lowermush.setFillColor('beige') lowermush.setDepth(53) mushroom.add(uppermush) mushroom.setDepth(52) self.layer = mushroom # save mushroom shape in the class _scene.add(self.layer) # add to global Canvas class Mario (object): def __init__(self, ... self.layer = Layer() ... _scene.add(self.layer) """ create_world() # define your objects, e.g. mario = Mario('blue', 'normal') # write your animation scenario here a = butterfly('yellow', 10,10) a.fly() a.move(100,0) a.change('red')
2
4
TA
What is the role of t in your code?
from cs1robots import * # Your code must work for empty worlds of all possible sizes. create_world(avenues=10, streets=6) # create_world(avenues=11, streets=8) # create_world(avenues=6, streets=9) # create_world(avenues=1, streets=3) # create_world(avenues=2, streets=1) # create_world(avenues=1, streets=2) # ... hubo=Robot(); hubo.set_trace('blue'); t=0; def turn_right(): for i in range(3): hubo.turn_left(); def go_straight(): while hubo.front_is_clear(): hubo.move(); def meet_left_wall(): turn_right(); hubo.move(); turn_right(); def meet_right_wall(): hubo.turn_left(); hubo.move(); hubo.turn_left(); hubo.turn_left(); go_straight(); while hubo.front_is_clear() or hubo.left_is_clear() or hubo.right_is_clear(): if t and not hubo.front_is_clear() and not (hubo.left_is_clear() and hubo.right_is_clear()): break; t=t+1; if not hubo.front_is_clear(): if t%2: meet_left_wall(); else : meet_right_wall(); go_straight();
37
47
variable
It is a variable indicating how far the vertical line has gone, Except for mx1, it excludes the first left corner To be able to finish when you get to the right corner!
cs1qa
null
null
null
null
null
Question: What is the role of t in your code? Code: from cs1robots import * # Your code must work for empty worlds of all possible sizes. create_world(avenues=10, streets=6) # create_world(avenues=11, streets=8) # create_world(avenues=6, streets=9) # create_world(avenues=1, streets=3) # create_world(avenues=2, streets=1) # create_world(avenues=1, streets=2) # ... hubo=Robot(); hubo.set_trace('blue'); t=0; def turn_right(): for i in range(3): hubo.turn_left(); def go_straight(): while hubo.front_is_clear(): hubo.move(); def meet_left_wall(): turn_right(); hubo.move(); turn_right(); def meet_right_wall(): hubo.turn_left(); hubo.move(); hubo.turn_left(); hubo.turn_left(); go_straight(); while hubo.front_is_clear() or hubo.left_is_clear() or hubo.right_is_clear(): if t and not hubo.front_is_clear() and not (hubo.left_is_clear() and hubo.right_is_clear()): break; t=t+1; if not hubo.front_is_clear(): if t%2: meet_left_wall(); else : meet_right_wall(); go_straight();
1
4
TA
What is the role of carrots?
from cs1robots import * load_world("worlds/harvest2.wld") hubo = Robot() carrots = 0 marker = 0 hubo.set_trace("blue") ##optional def turnright(): for i in range(3): hubo.turn_left() def proceed(): for i in range(2): hubo.move() #before collecting halfway def righty(): global carrots hubo.pick_beeper() hubo.move() turnright() hubo.move() hubo.pick_beeper() turnright() carrots += 2 def lefty(): global carrots hubo.pick_beeper() hubo.move() hubo.turn_left() hubo.move() hubo.pick_beeper() hubo.turn_left() carrots += 2 #after collecting halfway def righty2(): global carrots proceed() hubo.pick_beeper() turnright() hubo.move() turnright() hubo.move() def lefty2(): global carrots proceed() hubo.pick_beeper() hubo.turn_left() hubo.move() hubo.turn_left() hubo.move() def initial(): hubo.turn_left() for i in range(6): hubo.move() def execute(): global carrots, marker initial() while carrots < 36 : #proceed, pick up, proceed -- numbers go like 123454321 for i in range(10): if marker%2 == 0 and marker < 5: righty() elif marker%2 == 1 and marker < 5: lefty() elif marker%2 == 0 and marker >= 5: righty2() elif marker%2 == 1 and marker >= 5: lefty2() #proceed() if i == 0 : proceed() pass elif i >= 1 and i < 4 : proceed() for j in range(i): hubo.pick_beeper() carrots += 1 proceed() elif i == 4 : for j in range(4): proceed() hubo.pick_beeper() carrots += 1 elif i >= 5 and i < 8 : for j in range(8-i): hubo.pick_beeper() carrots += 1 proceed() hubo.pick_beeper() elif i >= 8 : hubo.pick_beeper() if i == 9: exit() marker += 1 execute()
4
104
variable
carrots is the number of beepers the robot has collected
cs1qa
null
null
null
null
null
Question: What is the role of carrots? Code: from cs1robots import * load_world("worlds/harvest2.wld") hubo = Robot() carrots = 0 marker = 0 hubo.set_trace("blue") ##optional def turnright(): for i in range(3): hubo.turn_left() def proceed(): for i in range(2): hubo.move() #before collecting halfway def righty(): global carrots hubo.pick_beeper() hubo.move() turnright() hubo.move() hubo.pick_beeper() turnright() carrots += 2 def lefty(): global carrots hubo.pick_beeper() hubo.move() hubo.turn_left() hubo.move() hubo.pick_beeper() hubo.turn_left() carrots += 2 #after collecting halfway def righty2(): global carrots proceed() hubo.pick_beeper() turnright() hubo.move() turnright() hubo.move() def lefty2(): global carrots proceed() hubo.pick_beeper() hubo.turn_left() hubo.move() hubo.turn_left() hubo.move() def initial(): hubo.turn_left() for i in range(6): hubo.move() def execute(): global carrots, marker initial() while carrots < 36 : #proceed, pick up, proceed -- numbers go like 123454321 for i in range(10): if marker%2 == 0 and marker < 5: righty() elif marker%2 == 1 and marker < 5: lefty() elif marker%2 == 0 and marker >= 5: righty2() elif marker%2 == 1 and marker >= 5: lefty2() #proceed() if i == 0 : proceed() pass elif i >= 1 and i < 4 : proceed() for j in range(i): hubo.pick_beeper() carrots += 1 proceed() elif i == 4 : for j in range(4): proceed() hubo.pick_beeper() carrots += 1 elif i >= 5 and i < 8 : for j in range(8-i): hubo.pick_beeper() carrots += 1 proceed() hubo.pick_beeper() elif i >= 8 : hubo.pick_beeper() if i == 9: exit() marker += 1 execute()
5
0
TA
can you briefly explain task1 withdrawal function??
balance = 0 def deposit(money) : global balance # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance balance=balance+money print("You deposited {} won".format(money)) # Do something on here ! pass ################# def withdrawal(money) : global balance # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance if balance>=money: balance=balance-money print("You've withdrawn {} won".format (money)) if balance<money: print("You'be withdrawn {} won".format (money)) print("But you only have {} won".format (balance)) # Do something on here ! pass ################# def bank() : global balance # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. if process =='': return # If a user's input is 'd', then ask the amount of money to deposit and deposit it. if process == 'd': money = int(input('How much do you want to deposit?')) deposit(money) # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. elif process == 'w': money=int(input('How much do you want to withdraw?')) withdrawal(money) # If a user's input is 'c', then check the current balance. elif process == 'c': print('Your current balance is {} won'.format (balance)) else : print('Please, press d or w or c or return') ################# ### implement ### ################# # Do something on here ! pass ################# bank()
16
32
variable
withdrawal is a function that subtracts by the number you entered, but issues a warning when the subtraction number is larger.
cs1qa
null
null
null
null
null
Question: can you briefly explain task1 withdrawal function?? Code: balance = 0 def deposit(money) : global balance # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance balance=balance+money print("You deposited {} won".format(money)) # Do something on here ! pass ################# def withdrawal(money) : global balance # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance if balance>=money: balance=balance-money print("You've withdrawn {} won".format (money)) if balance<money: print("You'be withdrawn {} won".format (money)) print("But you only have {} won".format (balance)) # Do something on here ! pass ################# def bank() : global balance # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. if process =='': return # If a user's input is 'd', then ask the amount of money to deposit and deposit it. if process == 'd': money = int(input('How much do you want to deposit?')) deposit(money) # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. elif process == 'w': money=int(input('How much do you want to withdraw?')) withdrawal(money) # If a user's input is 'c', then check the current balance. elif process == 'c': print('Your current balance is {} won'.format (balance)) else : print('Please, press d or w or c or return') ################# ### implement ### ################# # Do something on here ! pass ################# bank()
3
1
TA
For task 2, why do you have both line 18-19 and line 21-22?
from cs1robots import * # Your code must work for all world files below. # load_world( "worlds/trash1.wld" ) load_world( "worlds/trash2.wld" ) hubo=Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def uturn(): for i in range(2): turn_right() while hubo.front_is_clear(): while hubo.on_beeper(): hubo.pick_beeper() hubo.move() while hubo.on_beeper(): hubo.pick_beeper() uturn() while hubo.front_is_clear(): hubo.move() turn_right() hubo.move() while hubo.carries_beepers(): hubo.drop_beeper() uturn() hubo.move() hubo.turn_left()
17
21
reasoning
Just to pick all the beepers and the reason that line 21-22 exists is that we have to make sure that the robot still pick the beeper(s) at the point which front is not clear too
cs1qa
null
null
null
null
null
Question: For task 2, why do you have both line 18-19 and line 21-22? Code: from cs1robots import * # Your code must work for all world files below. # load_world( "worlds/trash1.wld" ) load_world( "worlds/trash2.wld" ) hubo=Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def uturn(): for i in range(2): turn_right() while hubo.front_is_clear(): while hubo.on_beeper(): hubo.pick_beeper() hubo.move() while hubo.on_beeper(): hubo.pick_beeper() uturn() while hubo.front_is_clear(): hubo.move() turn_right() hubo.move() while hubo.carries_beepers(): hubo.drop_beeper() uturn() hubo.move() hubo.turn_left()
3
2
TA
What is the meaning of the turn variable used here?
from cs1robots import * # Your code must work with any of the world files below. load_world('worlds/trash3.wld') # load_world('worlds/trash4.wld') hubo = Robot() hubo.set_trace("red") # hubo.set_pause(1) turn = 0 def turn_right(): for i in range(3): hubo.turn_left() def move(): while hubo.front_is_clear(): hubo.move() while hubo.on_beeper(): hubo.pick_beeper() turn = 0 while True: move() turn = turn + 1 print(turn) if not hubo.front_is_clear(): if (turn%2 == 0): if hubo.right_is_clear(): turn_right() hubo.move() turn_right() while hubo.on_beeper(): hubo.pick_beeper() else: break else: if hubo.left_is_clear(): hubo.turn_left() hubo.move() hubo.turn_left() while hubo.on_beeper(): hubo.pick_beeper() else: break while not hubo.facing_north(): turn_right() hubo.turn_left() move() hubo.turn_left() move() hubo.turn_left()
22
47
variable
When the turn is even number, it turns to the right, and when the turn is odd number, it turns to the left.
cs1qa
null
null
null
null
null
Question: What is the meaning of the turn variable used here? Code: from cs1robots import * # Your code must work with any of the world files below. load_world('worlds/trash3.wld') # load_world('worlds/trash4.wld') hubo = Robot() hubo.set_trace("red") # hubo.set_pause(1) turn = 0 def turn_right(): for i in range(3): hubo.turn_left() def move(): while hubo.front_is_clear(): hubo.move() while hubo.on_beeper(): hubo.pick_beeper() turn = 0 while True: move() turn = turn + 1 print(turn) if not hubo.front_is_clear(): if (turn%2 == 0): if hubo.right_is_clear(): turn_right() hubo.move() turn_right() while hubo.on_beeper(): hubo.pick_beeper() else: break else: if hubo.left_is_clear(): hubo.turn_left() hubo.move() hubo.turn_left() while hubo.on_beeper(): hubo.pick_beeper() else: break while not hubo.facing_north(): turn_right() hubo.turn_left() move() hubo.turn_left() move() hubo.turn_left()
10
0
TA
Would you please write in this chat room as much detail as possible about what animation you made and how you met each requirement in the description?
from cs1graphics import * from time import sleep _scene = None _world = None def create_world(): global _scene, _world if _scene: raise RuntimeError("A world already exists!") _world = _World(500, 300) _scene = Canvas(_world.width, _world.height) _scene.setTitle("Mario World") _world.draw_scene() class _World(object): def __init__(self, width, height): self.width = width self.height = height def draw_scene(self): """ draw background here Don't forget _scene.add(name) """ grass = Rectangle(1000,500,Point(250,150)) grass.setFillColor('green') grass.setDepth(100) _scene.add(grass) sky = Rectangle(1000,200,Point(250,100)) sky.setFillColor('skyblue') sky.setDepth(99) _scene.add(sky) pass """ define your own objects, e.g. Mario and Mushroom class Mushroom (object): def __init__(self, x, y): mushroom = Layer() uppermush = Ellipse(38, 18, Point(x, y)) uppermush.setFillColor('red') uppermush.setDepth(52) mushroom.add(lowermush) lowermush = Ellipse(35, 25, Point(x, y+8)) lowermush.setFillColor('beige') lowermush.setDepth(53) mushroom.add(uppermush) mushroom.setDepth(52) self.layer = mushroom # save mushroom shape in the class _scene.add(self.layer) # add to global Canvas class Mario (object): def __init__(self, ... self.layer = Layer() ... _scene.add(self.layer) """ create_world() # define your objects, e.g. mario = Mario('blue', 'normal') class Leaf (object): def __init__(self,x,y) : leaf = Layer() leaf1 = Circle(30, Point(x-15,y-45)) leaf1.setFillColor('green') leaf1.setDepth(51) leaf1.setBorderColor('green') leaf.add(leaf1) leaf2 = Circle(30, Point(x+15,y-45)) leaf2.setFillColor('green') leaf2.setDepth(51) leaf2.setBorderColor('green') leaf.add(leaf2) leaf3 = Circle(30, Point(x,y-70)) leaf3.setFillColor('green') leaf3.setDepth(51) leaf3.setBorderColor('green') leaf.add(leaf3) self.layer = leaf _scene.add(self.layer) def shake(self) : self.layer.move(10,0) sleep (0.2) self.layer.move(-10,0) sleep (0.2) self.layer.move(-10,0) sleep (0.2) self.layer.move(10,0) class Pillar (object) : def __init__(self,x,y) : m_pillar = Rectangle(30,90, Point(x,y)) m_pillar.setFillColor('brown') m_pillar.setDepth(52) self.layer = m_pillar _scene.add(self.layer) class Apple (object) : def __init__(self,x,y) : apple = Circle(10, Point(x,y)) apple.setFillColor('red') apple.setDepth(50) self.layer = apple _scene.add(self.layer) def drop(self) : self.layer.move(-12,5) sleep (0.1) self.layer.move(7,5) sleep (0.1) def broke (self,x,y) : self.layer.scale(0.001) broken1 = Ellipse(10,20,Point(x-20,y)) broken1.setFillColor('yellow') broken1.setDepth(50) broken2 = Ellipse(10,20,Point(x,y)) broken2.setFillColor('yellow') broken2.setDepth(50) _scene.add(broken1) _scene.add(broken2) class Rain (object) : def __init__(self,x,y) : rain = Ellipse(10,15,Point(x,y)) rain.setFillColor('blue') rain.setDepth(49) self.layer = rain _scene.add(self.layer) def shake(self) : self.layer.move(10,0) sleep (0.2) self.layer.move(-10,0) sleep (0.2) self.layer.move(-10,0) sleep (0.2) self.layer.move(10,0) pillar = Pillar(300,200) leaf = Leaf(300,200) apple = Apple(300,135) for i in range (15) : sleep(0.2) for a in range (18) : rain = Rain(20*a+30*a, 0+40*i) if i >= 10 : leaf.shake() for i in range(10) : apple.drop() apple.broke(250,255) # write your animation scenario here
0
167
code_explain
The overall animation content is an animation in which the apple on the tree falls and crushes due to the rain falling and the tree shakes. So, first, the gel first expresses the rain, and the leaves of the tree move on the canvas and the apple falls and crushes.
cs1qa
null
null
null
null
null
Question: Would you please write in this chat room as much detail as possible about what animation you made and how you met each requirement in the description? Code: from cs1graphics import * from time import sleep _scene = None _world = None def create_world(): global _scene, _world if _scene: raise RuntimeError("A world already exists!") _world = _World(500, 300) _scene = Canvas(_world.width, _world.height) _scene.setTitle("Mario World") _world.draw_scene() class _World(object): def __init__(self, width, height): self.width = width self.height = height def draw_scene(self): """ draw background here Don't forget _scene.add(name) """ grass = Rectangle(1000,500,Point(250,150)) grass.setFillColor('green') grass.setDepth(100) _scene.add(grass) sky = Rectangle(1000,200,Point(250,100)) sky.setFillColor('skyblue') sky.setDepth(99) _scene.add(sky) pass """ define your own objects, e.g. Mario and Mushroom class Mushroom (object): def __init__(self, x, y): mushroom = Layer() uppermush = Ellipse(38, 18, Point(x, y)) uppermush.setFillColor('red') uppermush.setDepth(52) mushroom.add(lowermush) lowermush = Ellipse(35, 25, Point(x, y+8)) lowermush.setFillColor('beige') lowermush.setDepth(53) mushroom.add(uppermush) mushroom.setDepth(52) self.layer = mushroom # save mushroom shape in the class _scene.add(self.layer) # add to global Canvas class Mario (object): def __init__(self, ... self.layer = Layer() ... _scene.add(self.layer) """ create_world() # define your objects, e.g. mario = Mario('blue', 'normal') class Leaf (object): def __init__(self,x,y) : leaf = Layer() leaf1 = Circle(30, Point(x-15,y-45)) leaf1.setFillColor('green') leaf1.setDepth(51) leaf1.setBorderColor('green') leaf.add(leaf1) leaf2 = Circle(30, Point(x+15,y-45)) leaf2.setFillColor('green') leaf2.setDepth(51) leaf2.setBorderColor('green') leaf.add(leaf2) leaf3 = Circle(30, Point(x,y-70)) leaf3.setFillColor('green') leaf3.setDepth(51) leaf3.setBorderColor('green') leaf.add(leaf3) self.layer = leaf _scene.add(self.layer) def shake(self) : self.layer.move(10,0) sleep (0.2) self.layer.move(-10,0) sleep (0.2) self.layer.move(-10,0) sleep (0.2) self.layer.move(10,0) class Pillar (object) : def __init__(self,x,y) : m_pillar = Rectangle(30,90, Point(x,y)) m_pillar.setFillColor('brown') m_pillar.setDepth(52) self.layer = m_pillar _scene.add(self.layer) class Apple (object) : def __init__(self,x,y) : apple = Circle(10, Point(x,y)) apple.setFillColor('red') apple.setDepth(50) self.layer = apple _scene.add(self.layer) def drop(self) : self.layer.move(-12,5) sleep (0.1) self.layer.move(7,5) sleep (0.1) def broke (self,x,y) : self.layer.scale(0.001) broken1 = Ellipse(10,20,Point(x-20,y)) broken1.setFillColor('yellow') broken1.setDepth(50) broken2 = Ellipse(10,20,Point(x,y)) broken2.setFillColor('yellow') broken2.setDepth(50) _scene.add(broken1) _scene.add(broken2) class Rain (object) : def __init__(self,x,y) : rain = Ellipse(10,15,Point(x,y)) rain.setFillColor('blue') rain.setDepth(49) self.layer = rain _scene.add(self.layer) def shake(self) : self.layer.move(10,0) sleep (0.2) self.layer.move(-10,0) sleep (0.2) self.layer.move(-10,0) sleep (0.2) self.layer.move(10,0) pillar = Pillar(300,200) leaf = Leaf(300,200) apple = Apple(300,135) for i in range (15) : sleep(0.2) for a in range (18) : rain = Rain(20*a+30*a, 0+40*i) if i >= 10 : leaf.shake() for i in range(10) : apple.drop() apple.broke(250,255) # write your animation scenario here
1
3
TA
Please briefly explain the behavior of next_line and next_line2 in task 4!
from cs1robots import * # create_world() # load_world('worlds/world_file_name.wld') load_world('worlds/harvest1.wld') hubo = Robot() hubo.set_trace('blue') hubo.move() def turn_right(): for i in range(3): hubo.turn_left() def harvest_one_line(): for i in range(5): hubo.pick_beeper() hubo.move() hubo.pick_beeper() def next_line(): hubo.turn_left() hubo.move() hubo.turn_left() def next_line_2(): turn_right() hubo.move() turn_right() for i in range(2): harvest_one_line() next_line() harvest_one_line() next_line_2() harvest_one_line() next_line() harvest_one_line()
19
27
variable
next_line is an action to move from the odd numbered line to the even numbered line next_line2 moves from even to odd lines!
cs1qa
null
null
null
null
null
Question: Please briefly explain the behavior of next_line and next_line2 in task 4! Code: from cs1robots import * # create_world() # load_world('worlds/world_file_name.wld') load_world('worlds/harvest1.wld') hubo = Robot() hubo.set_trace('blue') hubo.move() def turn_right(): for i in range(3): hubo.turn_left() def harvest_one_line(): for i in range(5): hubo.pick_beeper() hubo.move() hubo.pick_beeper() def next_line(): hubo.turn_left() hubo.move() hubo.turn_left() def next_line_2(): turn_right() hubo.move() turn_right() for i in range(2): harvest_one_line() next_line() harvest_one_line() next_line_2() harvest_one_line() next_line() harvest_one_line()
1
3
TA
In number 4, there are harvest and harvest2. What does harvest2 do??
from cs1robots import* load_world('worlds/harvest1.wld') hubo=Robot(beepers=1) def turn_right(): for i in range(3): hubo.turn_left() def mnp(): hubo.pick_beeper() hubo.move() def harvest(): for i in range(5): mnp() hubo.pick_beeper() def harvest2(): hubo.move() hubo.turn_left() harvest() turn_right() hubo.move() turn_right() harvest() hubo.turn_left() for i in range(3): harvest2()
10
22
variable
Harvest is to harvest a row, and harvest 2 is to harvest by round trip!
cs1qa
null
null
null
null
null
Question: In number 4, there are harvest and harvest2. What does harvest2 do?? Code: from cs1robots import* load_world('worlds/harvest1.wld') hubo=Robot(beepers=1) def turn_right(): for i in range(3): hubo.turn_left() def mnp(): hubo.pick_beeper() hubo.move() def harvest(): for i in range(5): mnp() hubo.pick_beeper() def harvest2(): hubo.move() hubo.turn_left() harvest() turn_right() hubo.move() turn_right() harvest() hubo.turn_left() for i in range(3): harvest2()
5
0
TA
Is there any reason I used if-pass in task1??
balance = 0 def deposit(money) : # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# if money>0: pass print("You deposited " + str(money) + " won") ################# global balance balance+=money def withdrawal(money) : # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output global balance # Withdraw the money from the current balance if balance>=money: pass else: print ("You've withdrawn " +str(money)+ " won") print("But you only have " +str(balance)+ " won") return print("You've withdrawn " +str(money)+ " won") balance-=money ################# def bank() : # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. if process=='d'or process=='w'or process=='c': pass elif process=='': return else: print('Please, press d or w or c or return') if process=='d': money=int(input("How much do you want to deposit?:")) deposit(money) elif process=='w': money=int(input("How much do you want to withdraw?:")) withdrawal(money) elif process=='c': print ("Your current balnce is " +str(balance)+ " won") ################# bank()
46
47
reasoning
I don't think I need it
cs1qa
null
null
null
null
null
Question: Is there any reason I used if-pass in task1?? Code: balance = 0 def deposit(money) : # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# if money>0: pass print("You deposited " + str(money) + " won") ################# global balance balance+=money def withdrawal(money) : # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output global balance # Withdraw the money from the current balance if balance>=money: pass else: print ("You've withdrawn " +str(money)+ " won") print("But you only have " +str(balance)+ " won") return print("You've withdrawn " +str(money)+ " won") balance-=money ################# def bank() : # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. if process=='d'or process=='w'or process=='c': pass elif process=='': return else: print('Please, press d or w or c or return') if process=='d': money=int(input("How much do you want to deposit?:")) deposit(money) elif process=='w': money=int(input("How much do you want to withdraw?:")) withdrawal(money) elif process=='c': print ("Your current balnce is " +str(balance)+ " won") ################# bank()
1
4
TA
Could you explain the left_up and right_down functions?
from cs1robots import * load_world('worlds/harvest2.wld') hubo=Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() for i in range(5): hubo.move() hubo.turn_left() hubo.move() hubo.turn_left() def left_up(): for i in range(5): hubo.pick_beeper() hubo.move() turn_right() hubo.move() hubo.turn_left() def right_down(): for i in range(5): hubo.pick_beeper() hubo.move() turn_right() hubo.move() hubo.turn_left() for i in range(2): left_up() turn_right() hubo.pick_beeper() hubo.move() turn_right() hubo.move() right_down() hubo.pick_beeper() hubo.move() hubo.turn_left() hubo.move() hubo.turn_left() left_up() turn_right() hubo.pick_beeper() hubo.move() turn_right() hubo.move() right_down() hubo.pick_beeper()
16
29
variable
Left up is a function that collects beepers by stepping up to the left by 5 spaces, and left down is a function that collects beepers by stepping down to the right by 5 spaces.
cs1qa
null
null
null
null
null
Question: Could you explain the left_up and right_down functions? Code: from cs1robots import * load_world('worlds/harvest2.wld') hubo=Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() for i in range(5): hubo.move() hubo.turn_left() hubo.move() hubo.turn_left() def left_up(): for i in range(5): hubo.pick_beeper() hubo.move() turn_right() hubo.move() hubo.turn_left() def right_down(): for i in range(5): hubo.pick_beeper() hubo.move() turn_right() hubo.move() hubo.turn_left() for i in range(2): left_up() turn_right() hubo.pick_beeper() hubo.move() turn_right() hubo.move() right_down() hubo.pick_beeper() hubo.move() hubo.turn_left() hubo.move() hubo.turn_left() left_up() turn_right() hubo.pick_beeper() hubo.move() turn_right() hubo.move() right_down() hubo.pick_beeper()
3
4
TA
In number 5, explain lines 19-24!
from cs1media import * # This code converts an image into a black & white poster. threshold1 = 100 threshold2 = 200 white = (255, 255, 255) black = (0, 0, 0) yellow = (255,255,0) blue = (0,0,255) green = (0,255,0) image = load_picture('./images/pikachu.jpg') width, height = image.size() for y in range(height): for x in range(width): r, g, b = image.get(x, y) average_brightness = (r + g + b) // 3 if average_brightness > threshold2: image.set(x, y, yellow) elif average_brightness < threshold1: image.set(x, y, blue) else: image.set(x, y, green) image.show()
18
23
code_explain
For a very bright color, I set the threshold to 200 so that if it is larger than 200, yellow appears, and if it is a very dark color, it should be close to 0.
cs1qa
null
null
null
null
null
Question: In number 5, explain lines 19-24! Code: from cs1media import * # This code converts an image into a black & white poster. threshold1 = 100 threshold2 = 200 white = (255, 255, 255) black = (0, 0, 0) yellow = (255,255,0) blue = (0,0,255) green = (0,255,0) image = load_picture('./images/pikachu.jpg') width, height = image.size() for y in range(height): for x in range(width): r, g, b = image.get(x, y) average_brightness = (r + g + b) // 3 if average_brightness > threshold2: image.set(x, y, yellow) elif average_brightness < threshold1: image.set(x, y, blue) else: image.set(x, y, green) image.show()
1
0
TA
I think you wrote the code separately for only the last half of the 4 laps. Can I ask why?
from cs1robots import * create_world() hubo=Robot() hubo.turn_left() hubo.set_trace('blue') def turn_right(): for i in range (3): hubo.turn_left() for i in range(4): for j in range(9): hubo.move() turn_right() hubo.move() turn_right() for k in range(9): hubo.move() hubo.turn_left() hubo.move() hubo.turn_left() for j in range(9): hubo.move() turn_right() hubo.move() turn_right() for k in range(9): hubo.move()
11
29
reasoning
Lastly, the path was shorter than the one in front, so if it moved like in the loop, it hit the wall and did it separately.
cs1qa
null
null
null
null
null
Question: I think you wrote the code separately for only the last half of the 4 laps. Can I ask why? Code: from cs1robots import * create_world() hubo=Robot() hubo.turn_left() hubo.set_trace('blue') def turn_right(): for i in range (3): hubo.turn_left() for i in range(4): for j in range(9): hubo.move() turn_right() hubo.move() turn_right() for k in range(9): hubo.move() hubo.turn_left() hubo.move() hubo.turn_left() for j in range(9): hubo.move() turn_right() hubo.move() turn_right() for k in range(9): hubo.move()
3
1
TA
Please also briefly explain the reason why you should use the while statement, not the for statement loop, in the process of picking up the beeper.
from cs1robots import * # Your code must work for all world files below. # load_world( "worlds/trash1.wld" ) load_world( "worlds/trash2.wld" ) hubo = Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def move_and_pick(): for i in range(9): hubo.move() while hubo.on_beeper(): hubo.pick_beeper() def just_move(): for i in range(9): hubo.move() def back(): for i in range(2): hubo.turn_left() move_and_pick() back() just_move() turn_right() hubo.move() while hubo.carries_beepers(): hubo.drop_beeper() back() hubo.move() hubo.turn_left()
15
16
reasoning
When picking up a beeper, it is necessary to give a beeper until there is no beeper, so we used a while statement that repeats while satisfying the condition, not for repeating a certain number.
cs1qa
null
null
null
null
null
Question: Please also briefly explain the reason why you should use the while statement, not the for statement loop, in the process of picking up the beeper. Code: from cs1robots import * # Your code must work for all world files below. # load_world( "worlds/trash1.wld" ) load_world( "worlds/trash2.wld" ) hubo = Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def move_and_pick(): for i in range(9): hubo.move() while hubo.on_beeper(): hubo.pick_beeper() def just_move(): for i in range(9): hubo.move() def back(): for i in range(2): hubo.turn_left() move_and_pick() back() just_move() turn_right() hubo.move() while hubo.carries_beepers(): hubo.drop_beeper() back() hubo.move() hubo.turn_left()
1
3
TA
In number 4, there are harvest and harvest2. What does harvest2 do??
from cs1robots import* load_world('worlds/harvest1.wld') hubo=Robot(beepers=1) def turn_right(): for i in range(3): hubo.turn_left() def mnp(): hubo.pick_beeper() hubo.move() def harvest(): for i in range(5): mnp() hubo.pick_beeper() def harvest2(): hubo.move() hubo.turn_left() harvest() turn_right() hubo.move() turn_right() harvest() hubo.turn_left() for i in range(3): harvest2()
10
22
variable
Harvest is to harvest a row, and harvest 2 is to harvest by round trip!
cs1qa
null
null
null
null
null
Question: In number 4, there are harvest and harvest2. What does harvest2 do?? Code: from cs1robots import* load_world('worlds/harvest1.wld') hubo=Robot(beepers=1) def turn_right(): for i in range(3): hubo.turn_left() def mnp(): hubo.pick_beeper() hubo.move() def harvest(): for i in range(5): mnp() hubo.pick_beeper() def harvest2(): hubo.move() hubo.turn_left() harvest() turn_right() hubo.move() turn_right() harvest() hubo.turn_left() for i in range(3): harvest2()
5
0
TA
Please explain how you used the global variable in task 1!
balance = 0 def deposit(money): # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# # Do something on here ! global balance balance = balance + money print("You deposited",money,"won") ################# def withdrawal(money): # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance ################# ### implement ### ################# # Do something on here ! global balance if money > balance: print("You've withdrawn",money,"won") print("But you only have",balance,"won") else: balance = balance - money print("You've withdraw",money,"won") ################# def bank(): # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. ################# ### implement ### ################# # Do something on here ! if process == '': return elif process == 'd': dmoney = int(input("How much do you want to deposit? ")) deposit(dmoney) elif process == 'w': wmoney = int(input("How much do you want to withdraw? ")) withdrawal(wmoney) elif process == 'c': print("Your current balance is",balance,"won") else: print("Please, press d or w or c or return") ################# bank()
3
36
variable
By specifying the balance as a global variable, all variables can be used in each function, and this is called the bank's remaining money.
cs1qa
null
null
null
null
null
Question: Please explain how you used the global variable in task 1! Code: balance = 0 def deposit(money): # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# # Do something on here ! global balance balance = balance + money print("You deposited",money,"won") ################# def withdrawal(money): # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance ################# ### implement ### ################# # Do something on here ! global balance if money > balance: print("You've withdrawn",money,"won") print("But you only have",balance,"won") else: balance = balance - money print("You've withdraw",money,"won") ################# def bank(): # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. ################# ### implement ### ################# # Do something on here ! if process == '': return elif process == 'd': dmoney = int(input("How much do you want to deposit? ")) deposit(dmoney) elif process == 'w': wmoney = int(input("How much do you want to withdraw? ")) withdrawal(wmoney) elif process == 'c': print("Your current balance is",balance,"won") else: print("Please, press d or w or c or return") ################# bank()
5
0
TA
Can you explain the function of global keyword in Task 1?
balance = 0 def deposit(money) : # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# # Do something on here ! global balance balance = balance + money print("You deposited",money,"won") ################# def withdrawal(money) : # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance ################# ### implement ### ################# # Do something on here ! global balance balance = balance - money print("You've withdraw",money,"won") ################# def bank() : # Input : (None) No Input # Output : (None) No Output global balance while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. ################# ### implement ### ################# # Do something on here ! if process == "": return elif process == "d": m = int(input("How much do you want to deposit? ")) deposit(m) elif process == "w": m = int(input("How much do you want to withdraw? ")) if m > balance: print("You've withdrawn",m,"won") print("But you only have",balance,"won") continue else: withdrawal(m) elif process == "c": print("Your current balance is",balance,"won") else: print("Please, press d or w or c or return") ################# bank()
12
14
variable
Since balance is a global variable, in order to change its value within the function, you must specify the global variable balance using the global keyword.
cs1qa
null
null
null
null
null
Question: Can you explain the function of global keyword in Task 1? Code: balance = 0 def deposit(money) : # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# # Do something on here ! global balance balance = balance + money print("You deposited",money,"won") ################# def withdrawal(money) : # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance ################# ### implement ### ################# # Do something on here ! global balance balance = balance - money print("You've withdraw",money,"won") ################# def bank() : # Input : (None) No Input # Output : (None) No Output global balance while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. ################# ### implement ### ################# # Do something on here ! if process == "": return elif process == "d": m = int(input("How much do you want to deposit? ")) deposit(m) elif process == "w": m = int(input("How much do you want to withdraw? ")) if m > balance: print("You've withdrawn",m,"won") print("But you only have",balance,"won") continue else: withdrawal(m) elif process == "c": print("Your current balance is",balance,"won") else: print("Please, press d or w or c or return") ################# bank()
2
4
TA
Next, please explain the last task 5
from cs1robots import * # Your code must work for empty worlds of all possible sizes. create_world(avenues=10, streets=10) # create_world(avenues=11, streets=8) # create_world(avenues=6, streets=9) # create_world(avenues=1, streets=3) # create_world(avenues=2, streets=1) # create_world(avenues=1, streets=2) # ... tim = Robot() tim.set_trace('blue') def turn_right(): for i in range(3): tim.turn_left() def go_one_line(): while tim.front_is_clear(): tim.move() def turning_point1(): tim.turn_left() tim.move() tim.turn_left() def turning_point2(): turn_right() tim.move() turn_right() tim.turn_left() go_one_line() while tim.right_is_clear(): turning_point2() go_one_line() if tim.left_is_clear(): turning_point1() go_one_line() else: break
17
41
code_explain
We defined a function to move one line and a function to move around, and in order not to collide with the wall, the condition that there is no wall on the side was hung as a while.
cs1qa
null
null
null
null
null
Question: Next, please explain the last task 5 Code: from cs1robots import * # Your code must work for empty worlds of all possible sizes. create_world(avenues=10, streets=10) # create_world(avenues=11, streets=8) # create_world(avenues=6, streets=9) # create_world(avenues=1, streets=3) # create_world(avenues=2, streets=1) # create_world(avenues=1, streets=2) # ... tim = Robot() tim.set_trace('blue') def turn_right(): for i in range(3): tim.turn_left() def go_one_line(): while tim.front_is_clear(): tim.move() def turning_point1(): tim.turn_left() tim.move() tim.turn_left() def turning_point2(): turn_right() tim.move() turn_right() tim.turn_left() go_one_line() while tim.right_is_clear(): turning_point2() go_one_line() if tim.left_is_clear(): turning_point1() go_one_line() else: break
1
3
TA
Why is the condition checked???
from cs1robots import * class Superbot(Robot): def turn_right(self): for _ in range(3): self.turn_left() def turn_around(self): for _ in range(2): self.turn_left() load_world("worlds/harvest1.wld") hubo=Superbot() while True: if hubo.on_beeper(): hubo.pick_beeper() if hubo._x == 7 and hubo._dir == 3: hubo.turn_left() hubo.move() hubo.turn_left() elif hubo._x == 2 and hubo._dir == 1: hubo.turn_right() hubo.move() hubo.turn_right() elif hubo.front_is_clear(): hubo.move() if hubo._beeper_bag == 36: break
19
28
reasoning
Since the x value does not change even after the robot rotates, the direction is also checked.
cs1qa
null
null
null
null
null
Question: Why is the condition checked??? Code: from cs1robots import * class Superbot(Robot): def turn_right(self): for _ in range(3): self.turn_left() def turn_around(self): for _ in range(2): self.turn_left() load_world("worlds/harvest1.wld") hubo=Superbot() while True: if hubo.on_beeper(): hubo.pick_beeper() if hubo._x == 7 and hubo._dir == 3: hubo.turn_left() hubo.move() hubo.turn_left() elif hubo._x == 2 and hubo._dir == 1: hubo.turn_right() hubo.move() hubo.turn_right() elif hubo.front_is_clear(): hubo.move() if hubo._beeper_bag == 36: break
1
0
TA
if i<4: hubo.turn_left() hubo.move() Could you please explain why you added this part?
from cs1robots import * create_world() hubo = Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def go_straight(): for i in range(9): hubo.move() for i in range(5): hubo.turn_left() go_straight() turn_right() hubo.move() turn_right() go_straight() if i<4: hubo.turn_left() hubo.move()
22
24
reasoning
If i=4, there is no more space left on the right, so I tried to stop the code
cs1qa
null
null
null
null
null
Question: if i<4: hubo.turn_left() hubo.move() Could you please explain why you added this part? Code: from cs1robots import * create_world() hubo = Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def go_straight(): for i in range(9): hubo.move() for i in range(5): hubo.turn_left() go_straight() turn_right() hubo.move() turn_right() go_straight() if i<4: hubo.turn_left() hubo.move()
8
1
TA
In Task2, when you split, you split with ", not ". What is the reason?
file=open('average-latitude-longitude-countries.csv',"r") list_all=[] for line in file: if line.strip()=='"ISO 3166 Country Code","Country","Latitude","Longitude"': continue list_splited=line.strip().split('"') list_all.append((list_splited[1],list_splited[3],float(list_splited[4].split(",")[1]), float(list_splited[4].split(",")[2]))) file.close() file=open('average-latitude-longitude-countries.csv',"r") list_cc_cn=[] for line in file: if line.strip()=='"ISO 3166 Country Code","Country","Latitude","Longitude"': continue list_splited=line.strip().split('"') list_cc_cn.append((list_splited[1],list_splited[3])) print(list_cc_cn) file.close() file=open('average-latitude-longitude-countries.csv',"r") list_cc_ll=[] for line in file: if line.strip()=='"ISO 3166 Country Code","Country","Latitude","Longitude"': continue list_splited=line.strip().split('"') list_cc_ll.append((list_splited[1],(float(list_splited[4].split(",")[1]), float(list_splited[4].split(",")[2])))) print(list_cc_ll) file.close() for item in list_cc_ll: if item[1][0]<0: cc=item[0] for items in list_all: if items[0]==cc: print(items[1]) while True: cc=input("Enter Country code: ") for items in list_all: if items[0]==cc: print(items[1])
5
5
reasoning
This is to return a new list divided by "
cs1qa
null
null
null
null
null
Question: In Task2, when you split, you split with ", not ". What is the reason? Code: file=open('average-latitude-longitude-countries.csv',"r") list_all=[] for line in file: if line.strip()=='"ISO 3166 Country Code","Country","Latitude","Longitude"': continue list_splited=line.strip().split('"') list_all.append((list_splited[1],list_splited[3],float(list_splited[4].split(",")[1]), float(list_splited[4].split(",")[2]))) file.close() file=open('average-latitude-longitude-countries.csv',"r") list_cc_cn=[] for line in file: if line.strip()=='"ISO 3166 Country Code","Country","Latitude","Longitude"': continue list_splited=line.strip().split('"') list_cc_cn.append((list_splited[1],list_splited[3])) print(list_cc_cn) file.close() file=open('average-latitude-longitude-countries.csv',"r") list_cc_ll=[] for line in file: if line.strip()=='"ISO 3166 Country Code","Country","Latitude","Longitude"': continue list_splited=line.strip().split('"') list_cc_ll.append((list_splited[1],(float(list_splited[4].split(",")[1]), float(list_splited[4].split(",")[2])))) print(list_cc_ll) file.close() for item in list_cc_ll: if item[1][0]<0: cc=item[0] for items in list_all: if items[0]==cc: print(items[1]) while True: cc=input("Enter Country code: ") for items in list_all: if items[0]==cc: print(items[1])
2
4
TA
What function shuttle_run does in Task 5?
from cs1robots import * # Your code must work for empty worlds of all possible sizes. # create_world(avenues=10, streets=10) # create_world(avenues=11, streets=8) # create_world(avenues=6, streets=9) # create_world(avenues=1, streets=3) # create_world(avenues=2, streets=1) # create_world(avenues=1, streets=2) create_world(avenues=12, streets=3) # ... my_robot = Robot() my_robot.set_trace("blue") def turn_right(): for i in range(3): my_robot.turn_left() def shuttle_run(): my_robot.turn_left() while my_robot.front_is_clear(): my_robot.move() turn_right() if my_robot.front_is_clear(): my_robot.move() turn_right() while my_robot.front_is_clear(): my_robot.move() my_robot.turn_left() shuttle_run() while my_robot.front_is_clear(): my_robot.move() shuttle_run() #make robot look forward at final position turn_right()
20
30
variable
This function is set to go up, move one line to the right in front of the wall and come down again. However, because the number of passages has not been decided If it becomes impossible to move one line to the right from the top, it is set to stop at that position.
cs1qa
null
null
null
null
null
Question: What function shuttle_run does in Task 5? Code: from cs1robots import * # Your code must work for empty worlds of all possible sizes. # create_world(avenues=10, streets=10) # create_world(avenues=11, streets=8) # create_world(avenues=6, streets=9) # create_world(avenues=1, streets=3) # create_world(avenues=2, streets=1) # create_world(avenues=1, streets=2) create_world(avenues=12, streets=3) # ... my_robot = Robot() my_robot.set_trace("blue") def turn_right(): for i in range(3): my_robot.turn_left() def shuttle_run(): my_robot.turn_left() while my_robot.front_is_clear(): my_robot.move() turn_right() if my_robot.front_is_clear(): my_robot.move() turn_right() while my_robot.front_is_clear(): my_robot.move() my_robot.turn_left() shuttle_run() while my_robot.front_is_clear(): my_robot.move() shuttle_run() #make robot look forward at final position turn_right()
9
1
student
But what's the difference between the deck of the main function and the deck of create_deck?
import random from cs1graphics import * img_path = './images/' suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] face_names = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] value = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] bj_board = Canvas(600, 400, 'dark green', 'Black Jack 101') """ Define the Card class """ class Card: def __init__(self, suit, face): self.suit=suit self.face=face self.state=True if self.state==True: self.image="./images/%s_%s.png" %(suit, face) elif self.state==False: self.image="./images/Back.png" def value(self): if type(self.face)==int: return self.face elif self.face=='Ace': return 11 else: return 10 def create_deck(number = 1): """ Create a list("deck") of all 52 cards, shuffle them and return the list. The list 'deck' have to include Card objects A Card is represented by a object with four attributes: the face, the suit, value, state, and the image object First, Have to define class 'Card' """ suits=['Clubs', 'Diamonds', 'Hearts', 'Spades'] faces=['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King'] deck=[] for i in suits: for j in faces: c=Card(i, j) deck.append(c) random.shuffle(deck) def hand_value(hand): """ hand is a list including card objects Compute the value of the cards in the list "hand" """ A=0 for i in hand: A+=i.value() return A def card_string(card): """ Parameter "card" is a Card object Return a nice string to represent a card (sucn as "a King of Spades" or "an Ace of Diamonds") """ article='a' if self.face in [8, 'Ace']: article='an' return (article + str(self.face) + 'of' + sel.suit) def ask_yesno(prompt): """ Display the text prompt and let's the user enter a string. If the user enters "y", the function returns "True", and if the user enters "n", the function returns "False". If the user enters anything else, the function prints "I beg your pardon!", and asks again, repreting this until the user has entered a correct string. """ YN=input(prompt) if YN=='y': return True elif YN=='n': return False else: print('I beg your pardon!') ask_yesno(prompt) def draw_card(dealer,player): """ This funuction add the cards of dealer and player to canvas, bj_board. If the state of each Card object is false, then you have to show the hidden card image(Back.png). The dealer's first card is hidden state. The parameter dealer and player are List objects including Card Objects. The start position of dealer's card is (100,100). The start position of player's card is (100,300). You can use the following methods for positioning images and text: Image() Object, Text() Object, moveTo() method, setDepth() method. You should use help function - help('cs1graphics.Image') -> about Image(), moveTo(), setDepth() help('cs1graphics.Text') -> about Text(),moveTo(), setDepth() """ depth = 100 x0,y0 = 100,100 x1,y1 = 100,300 a=0 b=0 for card in dealer: if a==0: card.state=False card.img.moveTo(100+50*a, 100) bj_board.add(card.img) a+=1 for card in player: card.img.moveTo(100+50*b, 300) bj_board.add(card.img) b+=1 bj_board.clear() def main(): deck = [] while True: # prompt for starting a new game and create a deck print ("Welcome to Black Jack 101!\n") if len(deck) < 12: deck = create_deck() # create two hands of dealer and player dealer = [] player = [] # initial two dealings card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt a hidden card") card.state=False dealer.append(card) card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # player's turn to draw cards while hand_value(player) < 21 and ask_yesno("Would you like another card? (y/n) "): # draw a card for the player card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # if the player's score is over 21, the player loses immediately. if hand_value(player) > 21: print ("You went over 21! You lost.") dealer[0].state = True draw_card(dealer,player) else: # draw cards for the dealer while the dealer's score is less than 17 print ("\nThe dealer's hidden card was " + card_string(dealer[0])) while hand_value(dealer) < 17: card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("The dealer's total is", hand_value(dealer)) dealer[0].state = True draw_card(dealer,player) # summary player_total = hand_value(player) dealer_total = hand_value(dealer) print ("\nYour total is", player_total) print ("The dealer's total is", dealer_total) if dealer_total > 21: print ("The dealer went over 21! You win!") else: if player_total > dealer_total: print ("You win!") elif player_total < dealer_total: print ("You lost!") else: print ("You have a tie!") if not ask_yesno("\nPlay another round? (y/n) "): bj_board.close() break main()
null
null
code_understanding
The deck of the main function and the deck of the create_deck function are the same after all!
cs1qa
null
null
null
null
null
Question: But what's the difference between the deck of the main function and the deck of create_deck? Code: import random from cs1graphics import * img_path = './images/' suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] face_names = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] value = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] bj_board = Canvas(600, 400, 'dark green', 'Black Jack 101') """ Define the Card class """ class Card: def __init__(self, suit, face): self.suit=suit self.face=face self.state=True if self.state==True: self.image="./images/%s_%s.png" %(suit, face) elif self.state==False: self.image="./images/Back.png" def value(self): if type(self.face)==int: return self.face elif self.face=='Ace': return 11 else: return 10 def create_deck(number = 1): """ Create a list("deck") of all 52 cards, shuffle them and return the list. The list 'deck' have to include Card objects A Card is represented by a object with four attributes: the face, the suit, value, state, and the image object First, Have to define class 'Card' """ suits=['Clubs', 'Diamonds', 'Hearts', 'Spades'] faces=['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King'] deck=[] for i in suits: for j in faces: c=Card(i, j) deck.append(c) random.shuffle(deck) def hand_value(hand): """ hand is a list including card objects Compute the value of the cards in the list "hand" """ A=0 for i in hand: A+=i.value() return A def card_string(card): """ Parameter "card" is a Card object Return a nice string to represent a card (sucn as "a King of Spades" or "an Ace of Diamonds") """ article='a' if self.face in [8, 'Ace']: article='an' return (article + str(self.face) + 'of' + sel.suit) def ask_yesno(prompt): """ Display the text prompt and let's the user enter a string. If the user enters "y", the function returns "True", and if the user enters "n", the function returns "False". If the user enters anything else, the function prints "I beg your pardon!", and asks again, repreting this until the user has entered a correct string. """ YN=input(prompt) if YN=='y': return True elif YN=='n': return False else: print('I beg your pardon!') ask_yesno(prompt) def draw_card(dealer,player): """ This funuction add the cards of dealer and player to canvas, bj_board. If the state of each Card object is false, then you have to show the hidden card image(Back.png). The dealer's first card is hidden state. The parameter dealer and player are List objects including Card Objects. The start position of dealer's card is (100,100). The start position of player's card is (100,300). You can use the following methods for positioning images and text: Image() Object, Text() Object, moveTo() method, setDepth() method. You should use help function - help('cs1graphics.Image') -> about Image(), moveTo(), setDepth() help('cs1graphics.Text') -> about Text(),moveTo(), setDepth() """ depth = 100 x0,y0 = 100,100 x1,y1 = 100,300 a=0 b=0 for card in dealer: if a==0: card.state=False card.img.moveTo(100+50*a, 100) bj_board.add(card.img) a+=1 for card in player: card.img.moveTo(100+50*b, 300) bj_board.add(card.img) b+=1 bj_board.clear() def main(): deck = [] while True: # prompt for starting a new game and create a deck print ("Welcome to Black Jack 101!\n") if len(deck) < 12: deck = create_deck() # create two hands of dealer and player dealer = [] player = [] # initial two dealings card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt a hidden card") card.state=False dealer.append(card) card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # player's turn to draw cards while hand_value(player) < 21 and ask_yesno("Would you like another card? (y/n) "): # draw a card for the player card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # if the player's score is over 21, the player loses immediately. if hand_value(player) > 21: print ("You went over 21! You lost.") dealer[0].state = True draw_card(dealer,player) else: # draw cards for the dealer while the dealer's score is less than 17 print ("\nThe dealer's hidden card was " + card_string(dealer[0])) while hand_value(dealer) < 17: card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("The dealer's total is", hand_value(dealer)) dealer[0].state = True draw_card(dealer,player) # summary player_total = hand_value(player) dealer_total = hand_value(dealer) print ("\nYour total is", player_total) print ("The dealer's total is", dealer_total) if dealer_total > 21: print ("The dealer went over 21! You win!") else: if player_total > dealer_total: print ("You win!") elif player_total < dealer_total: print ("You lost!") else: print ("You have a tie!") if not ask_yesno("\nPlay another round? (y/n) "): bj_board.close() break main()
6
2
TA
Can you briefly explain the role of correct_list?
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards j=0 k=0 i_w = 70 i_h = 90 for i in range(6): for h in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ random.shuffle(cards)# 3-2-1. shuffle the card list ################################################################ for i in range(len(num_pads)): if not i in correct_list: cards[i][0].moveTo(i_w + k, i_h+j) canvas.add(cards[i][0]) k += 100 if k % 600 == 0: k = 0 j += 130 time.sleep(1) for i in range(len(num_pads)): if not i in correct_list: canvas.remove(cards[i][0]) k += 100 if k % 600 == 0: k = 0 j += 130 def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if i in correct_list: # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### a=[] for i in range(24): a.append(i) if num1==num2 or num1 in correct_list or num2 in correct_list or num1 not in a or num2 not in a: return False return True def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### global tries if cards[num1][1]==cards[num2][1]: correct_list.append(num1) correct_list.append(num2) tries+=1 return True else: canvas.add(cards[num1][0]) canvas.add(cards[num2][0]) time.sleep(1) canvas.remove(cards[num1][0]) canvas.remove(cards[num2][0]) tries+=1 return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while not len(correct_list)==24: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs if tries==1: print(str(tries) + "st try. You got " + str(len(correct_list)//2) + " pairs.") elif tries==2: print(str(tries) + "nd try. You got " + str(len(correct_list)//2) + " pairs.") elif tries==3: print(str(tries) + "rd try. You got " + str(len(correct_list)//2) + " pairs.") else: print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") print_cards() else: print("Wrong!") print_cards() ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
104
108
variable
Matched number pad keeps showing matched cards as a list of numbers, used to indicate You got-pairs
cs1qa
null
null
null
null
null
Question: Can you briefly explain the role of correct_list? Code: from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards j=0 k=0 i_w = 70 i_h = 90 for i in range(6): for h in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ random.shuffle(cards)# 3-2-1. shuffle the card list ################################################################ for i in range(len(num_pads)): if not i in correct_list: cards[i][0].moveTo(i_w + k, i_h+j) canvas.add(cards[i][0]) k += 100 if k % 600 == 0: k = 0 j += 130 time.sleep(1) for i in range(len(num_pads)): if not i in correct_list: canvas.remove(cards[i][0]) k += 100 if k % 600 == 0: k = 0 j += 130 def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if i in correct_list: # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### a=[] for i in range(24): a.append(i) if num1==num2 or num1 in correct_list or num2 in correct_list or num1 not in a or num2 not in a: return False return True def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### global tries if cards[num1][1]==cards[num2][1]: correct_list.append(num1) correct_list.append(num2) tries+=1 return True else: canvas.add(cards[num1][0]) canvas.add(cards[num2][0]) time.sleep(1) canvas.remove(cards[num1][0]) canvas.remove(cards[num2][0]) tries+=1 return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while not len(correct_list)==24: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs if tries==1: print(str(tries) + "st try. You got " + str(len(correct_list)//2) + " pairs.") elif tries==2: print(str(tries) + "nd try. You got " + str(len(correct_list)//2) + " pairs.") elif tries==3: print(str(tries) + "rd try. You got " + str(len(correct_list)//2) + " pairs.") else: print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") print_cards() else: print("Wrong!") print_cards() ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
6
0
TA
I'll explain task 1!
def fibonacci(upper_bound): l=[0,1] while (l[len(l)-2]+l[len(l)-1])<upper_bound: l.append(l[len(l)-2]+l[len(l)-1]) return l print(fibonacci(1000))
0
7
code_explain
Task 1 is to put 0 1 in the list and add the sum of the two numbers at the end of the list one by one. While loop is used so that the added number does not exceed the upper bound
cs1qa
null
null
null
null
null
Question: I'll explain task 1! Code: def fibonacci(upper_bound): l=[0,1] while (l[len(l)-2]+l[len(l)-1])<upper_bound: l.append(l[len(l)-2]+l[len(l)-1]) return l print(fibonacci(1000))
4
2
TA
Please explain along with the process which constants of the math module were used in Task3~
import math sin = math.sin pi = math.pi a=int(input('How many steps?: ')) for i in range(a): x = float(i) / 30.0 * 2 * pi print (sin(x))
2
3
code_explain
We only used sin and pi in the math module, of which the constant pi was used to calculate x!
cs1qa
null
null
null
null
null
Question: Please explain along with the process which constants of the math module were used in Task3~ Code: import math sin = math.sin pi = math.pi a=int(input('How many steps?: ')) for i in range(a): x = float(i) / 30.0 * 2 * pi print (sin(x))
5
0
TA
What is the pick_up() function in task1?
from cs1robots import * load_world('worlds/harvest3.wld') hubo = Robot() hubo.set_trace('blue') def hubo_turn_right(): for i in range(3): hubo.turn_left() def pick_up(): for i in range(5): hubo.move() if hubo.on_beeper(): hubo.pick_beeper() def turn1(): hubo.turn_left() hubo.move() if hubo.on_beeper(): hubo.pick_beeper() hubo.turn_left() def turn2(): hubo_turn_right() hubo.move() if hubo.on_beeper(): hubo.pick_beeper() hubo_turn_right() hubo.move() hubo.pick_beeper() for i in range(2): pick_up() turn1() pick_up() turn2() pick_up() turn1() pick_up()
9
13
variable
This is a function that picks up the beeper if the robot goes forward and is on the beeper.
cs1qa
null
null
null
null
null
Question: What is the pick_up() function in task1? Code: from cs1robots import * load_world('worlds/harvest3.wld') hubo = Robot() hubo.set_trace('blue') def hubo_turn_right(): for i in range(3): hubo.turn_left() def pick_up(): for i in range(5): hubo.move() if hubo.on_beeper(): hubo.pick_beeper() def turn1(): hubo.turn_left() hubo.move() if hubo.on_beeper(): hubo.pick_beeper() hubo.turn_left() def turn2(): hubo_turn_right() hubo.move() if hubo.on_beeper(): hubo.pick_beeper() hubo_turn_right() hubo.move() hubo.pick_beeper() for i in range(2): pick_up() turn1() pick_up() turn2() pick_up() turn1() pick_up()
8
0
TA
Then, please explain the algorithm you wrote in Task 1!
import elice_utils from time import sleep def merge(input_filenames, output_filename): merge_result = open('output.txt', 'a') for i in range(len(input_filenames)): merge = open(input_filenames[i], 'r') for line in merge: data = line merge_result.write(data) pass merge(['kaist1.txt', 'kaist2.txt', 'kaist3.txt'], 'output.txt') sleep(0.5) # Wait 0.5 seconds before creating a download link. elice_utils.send_file('output.txt')
4
9
code_explain
At number one, the input comes into the list Read each list through iteration After reading this for each line through the open function I wrote it in the output
cs1qa
null
null
null
null
null
Question: Then, please explain the algorithm you wrote in Task 1! Code: import elice_utils from time import sleep def merge(input_filenames, output_filename): merge_result = open('output.txt', 'a') for i in range(len(input_filenames)): merge = open(input_filenames[i], 'r') for line in merge: data = line merge_result.write(data) pass merge(['kaist1.txt', 'kaist2.txt', 'kaist3.txt'], 'output.txt') sleep(0.5) # Wait 0.5 seconds before creating a download link. elice_utils.send_file('output.txt')
2
1
TA
What is plant() in task2?
from cs1robots import * load_world('worlds/harvest3.wld') hubo=Robot(beepers=6) hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def plant(): hubo.move() if not hubo.on_beeper(): hubo.drop_beeper() def curve(): for i in range(5): plant() hubo.turn_left() plant() hubo.turn_left() for i in range(5): plant() turn_right() plant() for i in range(2): curve() plant() turn_right() curve()
7
10
variable
If there is no beeper moving and there is no beeper, this is the dropping function to plant the beeper
cs1qa
null
null
null
null
null
Question: What is plant() in task2? Code: from cs1robots import * load_world('worlds/harvest3.wld') hubo=Robot(beepers=6) hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def plant(): hubo.move() if not hubo.on_beeper(): hubo.drop_beeper() def curve(): for i in range(5): plant() hubo.turn_left() plant() hubo.turn_left() for i in range(5): plant() turn_right() plant() for i in range(2): curve() plant() turn_right() curve()
8
0
TA
Please briefly explain what the meaning of "r" and "w" used to open!
from time import sleep import elice_utils def merge(input_filenames, output_filename): # Implement here # ... file1=open(output_filename,"w") for file_names in input_filenames: file2=open(file_names,"r") for line in file2: file1.write(line) file2.close() file1.close() pass merge(['kaist1.txt', 'kaist2.txt', 'kaist3.txt'], 'output.txt') sleep(0.5) # Wait 0.5 seconds before creating a download link. elice_utils.send_file('output.txt')
6
8
variable
'r' means open for reading (default),'w' means open for writing, truncating the file first.
cs1qa
null
null
null
null
null
Question: Please briefly explain what the meaning of "r" and "w" used to open! Code: from time import sleep import elice_utils def merge(input_filenames, output_filename): # Implement here # ... file1=open(output_filename,"w") for file_names in input_filenames: file2=open(file_names,"r") for line in file2: file1.write(line) file2.close() file1.close() pass merge(['kaist1.txt', 'kaist2.txt', 'kaist3.txt'], 'output.txt') sleep(0.5) # Wait 0.5 seconds before creating a download link. elice_utils.send_file('output.txt')
3
4
TA
How did you do the color classification in task5, and where is the code that makes it blue when dark?
from cs1media import * # This code converts an image into a black & white poster. white = (255, 255, 255) black = (0, 0, 0) yellow = (255, 255, 0) blue = (0, 0, 255) green = (0, 255, 0) image = load_picture('./images/minion.jpg') width, height = image.size() for y in range(height): for x in range(width): r, g, b = image.get(x, y) average_brightness = (r + g + b) // 3 if average_brightness > 150: image.set(x, y, yellow) elif average_brightness < 70: image.set(x, y, blue) else: image.set(x, y, green) image.show()
17
22
code_explain
The average_brightness value is divided by 150 and 70, and lines 20 and 21 are blue.
cs1qa
null
null
null
null
null
Question: How did you do the color classification in task5, and where is the code that makes it blue when dark? Code: from cs1media import * # This code converts an image into a black & white poster. white = (255, 255, 255) black = (0, 0, 0) yellow = (255, 255, 0) blue = (0, 0, 255) green = (0, 255, 0) image = load_picture('./images/minion.jpg') width, height = image.size() for y in range(height): for x in range(width): r, g, b = image.get(x, y) average_brightness = (r + g + b) // 3 if average_brightness > 150: image.set(x, y, yellow) elif average_brightness < 70: image.set(x, y, blue) else: image.set(x, y, green) image.show()
4
1
TA
Why do I need to process float() after receiving input from Task 2?
def is_triangle(a, b, c): return ("YES" if (a < b + c) and (b < a + c) and (c < a + b) else "NO") a = float(input('Side a: ')) b = float(input('Side b: ')) c = float(input('Side c: ')) print(is_triangle(a,b,c))
4
6
reasoning
Since all the contents obtained from the input function are treated as strings, we changed the data type!
cs1qa
null
null
null
null
null
Question: Why do I need to process float() after receiving input from Task 2? Code: def is_triangle(a, b, c): return ("YES" if (a < b + c) and (b < a + c) and (c < a + b) else "NO") a = float(input('Side a: ')) b = float(input('Side b: ')) c = float(input('Side c: ')) print(is_triangle(a,b,c))
1
2
TA
Please briefly explain what functions up_stair, down_stair, and drop_and_turn are and how they work.
from cs1robots import * load_world('worlds/newspaper.wld') hubo = Robot(beepers = 1) hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def up_stair(): while hubo.front_is_clear(): hubo.move() hubo.turn_left() hubo.move() turn_right() def drop_and_turn(): hubo.drop_beeper() for i in range(2): hubo.turn_left() def down_stair(): while not hubo.left_is_clear(): hubo.move() hubo.turn_left() hubo.move() turn_right() def up_stairs(): for i in range(4): up_stair() def down_stairs(): for i in range(4): down_stair() up_stairs() while hubo.front_is_clear(): hubo.move() drop_and_turn() down_stairs() while hubo.front_is_clear(): hubo.move()
7
22
variable
up_stair and down_stair are the functions you need to go up and down the stairs respectively, go up to the front of the stairs, then use turn to go up and down stairs
cs1qa
null
null
null
null
null
Question: Please briefly explain what functions up_stair, down_stair, and drop_and_turn are and how they work. Code: from cs1robots import * load_world('worlds/newspaper.wld') hubo = Robot(beepers = 1) hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def up_stair(): while hubo.front_is_clear(): hubo.move() hubo.turn_left() hubo.move() turn_right() def drop_and_turn(): hubo.drop_beeper() for i in range(2): hubo.turn_left() def down_stair(): while not hubo.left_is_clear(): hubo.move() hubo.turn_left() hubo.move() turn_right() def up_stairs(): for i in range(4): up_stair() def down_stairs(): for i in range(4): down_stair() up_stairs() while hubo.front_is_clear(): hubo.move() drop_and_turn() down_stairs() while hubo.front_is_clear(): hubo.move()
6
1
TA
l = [] for i in range(n): l.append(i) What is the reason why l = range(n) without this
import random def drawing_integers(lb, ub, trials): """ Make a list of the integers :param lb: the lower bound of the integers :param ub: the upper bound of the integers :param trials: the number of trials :return: an integers list. Ex) [1, 4, 3, 5, 2] """ list = [] for i in range(int(trials)): list.append(random.randint(lb,ub)) return list pass def average_integers(num_list): """ Compute the average of the integers in the num_list :param num_list: input list :return: average value of the list """ return sum(num_list)/int(len(num_list)) pass def count_integers(num_list): """ Count the integers in the num_list :param num_list: input list :return: A list of tuples that consist of the integer and its frequency """ l = [] for i in num_list: l.append((i,num_list.count(i))) return list(set(l)) pass # Run the program list1 = drawing_integers(1, 6, 20) print(list1) print(average_integers(list1)) print(count_integers(list1)) print() list2 = drawing_integers(5, 12, 15) print(list2) print(average_integers(list2)) print(count_integers(list2))
null
null
reasoning
I think it’s because range(n) is a list
cs1qa
null
null
null
null
null
Question: l = [] for i in range(n): l.append(i) What is the reason why l = range(n) without this Code: import random def drawing_integers(lb, ub, trials): """ Make a list of the integers :param lb: the lower bound of the integers :param ub: the upper bound of the integers :param trials: the number of trials :return: an integers list. Ex) [1, 4, 3, 5, 2] """ list = [] for i in range(int(trials)): list.append(random.randint(lb,ub)) return list pass def average_integers(num_list): """ Compute the average of the integers in the num_list :param num_list: input list :return: average value of the list """ return sum(num_list)/int(len(num_list)) pass def count_integers(num_list): """ Count the integers in the num_list :param num_list: input list :return: A list of tuples that consist of the integer and its frequency """ l = [] for i in num_list: l.append((i,num_list.count(i))) return list(set(l)) pass # Run the program list1 = drawing_integers(1, 6, 20) print(list1) print(average_integers(list1)) print(count_integers(list1)) print() list2 = drawing_integers(5, 12, 15) print(list2) print(average_integers(list2)) print(count_integers(list2))
1
1
TA
What is pick_beeper() in task2?
from cs1robots import * load_world("worlds/hurdles1.wld") R1 = Robot() R1.set_trace("blue") def turn_right(): for i in range(3): R1.turn_left() for i in range(4): R1.move() R1.turn_left() R1.move() turn_right() R1.move() turn_right() R1.move() R1.turn_left() R1.move() R1.pick_beeper()
17
17
variable
This is a function that the robot (R1) picks up a yellow coin with 1 written on it.
cs1qa
null
null
null
null
null
Question: What is pick_beeper() in task2? Code: from cs1robots import * load_world("worlds/hurdles1.wld") R1 = Robot() R1.set_trace("blue") def turn_right(): for i in range(3): R1.turn_left() for i in range(4): R1.move() R1.turn_left() R1.move() turn_right() R1.move() turn_right() R1.move() R1.turn_left() R1.move() R1.pick_beeper()
5
0
TA
Why should I use global balance in task1?
balance = 0 def deposit(money) : # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# # Do something on here ! global balance balance = balance + money #pass ################# def withdrawal(money) : # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance ################# ### implement ### ################# # Do something on here ! global balance if balance < money: print("You've withdrawn", money, "won") print("But you only have", balance, "won") else: balance = balance - money print("You withdraw", money, "won") #pass ################# def bank() : # Input : (None) No Input # Output : (None) No Output while True: d = 'd' w = 'w' c = 'c' process = input("Deposit(d) or withdrawal(w) or balance check(c)? If you want to finish, just press enter") if process == d: money = int(input("How much do you want to deposit?")) deposit(money) print("You deposited", money, "won") elif process == w: money = int(input("How much do you want to withdraw?")) withdrawal(money) elif process == c: print("Your current balance is", balance, "won") elif process == '': break else: print("Please, press d or w or c or return") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. ################# ### implement ### ################# # Do something on here ! pass ################# bank()
0
37
reasoning
I used it because I had to change the value of the balance (because I have to use it, not just read it)!
cs1qa
null
null
null
null
null
Question: Why should I use global balance in task1? Code: balance = 0 def deposit(money) : # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# # Do something on here ! global balance balance = balance + money #pass ################# def withdrawal(money) : # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance ################# ### implement ### ################# # Do something on here ! global balance if balance < money: print("You've withdrawn", money, "won") print("But you only have", balance, "won") else: balance = balance - money print("You withdraw", money, "won") #pass ################# def bank() : # Input : (None) No Input # Output : (None) No Output while True: d = 'd' w = 'w' c = 'c' process = input("Deposit(d) or withdrawal(w) or balance check(c)? If you want to finish, just press enter") if process == d: money = int(input("How much do you want to deposit?")) deposit(money) print("You deposited", money, "won") elif process == w: money = int(input("How much do you want to withdraw?")) withdrawal(money) elif process == c: print("Your current balance is", balance, "won") elif process == '': break else: print("Please, press d or w or c or return") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. ################# ### implement ### ################# # Do something on here ! pass ################# bank()
3
3
TA
In task4, did you use x to check if you came to the original position??
from cs1robots import * load_world('worlds/rain2.wld') hubo = Robot(beepers=100, avenue=2, street=6, orientation='E') hubo.set_trace('blue') x=0 def check(): global x if hubo.on_beeper(): x=x+1 def turn_right(): for i in range(3): hubo.turn_left() def turn_around(): for j in range(2): hubo.turn_left() def move(): z=0 global x while x!=1: if hubo.right_is_clear(): hubo.move() if not hubo.right_is_clear(): z=z+1 turn_around() hubo.move() hubo.move() turn_around() if not hubo.right_is_clear(): z=z+1 hubo.move() if z==2: hubo.drop_beeper() hubo.move() check() else: turn_right() hubo.move() check() z=0 else: if hubo.front_is_clear(): hubo.move() check() else: hubo.turn_left() hubo.move() check() if x==1: hubo.pick_beeper() turn_right() hubo.move() hubo.drop_beeper() turn_right() hubo.move() check() move()
52
54
variable
I made sure we're back to the starting position
cs1qa
null
null
null
null
null
Question: In task4, did you use x to check if you came to the original position?? Code: from cs1robots import * load_world('worlds/rain2.wld') hubo = Robot(beepers=100, avenue=2, street=6, orientation='E') hubo.set_trace('blue') x=0 def check(): global x if hubo.on_beeper(): x=x+1 def turn_right(): for i in range(3): hubo.turn_left() def turn_around(): for j in range(2): hubo.turn_left() def move(): z=0 global x while x!=1: if hubo.right_is_clear(): hubo.move() if not hubo.right_is_clear(): z=z+1 turn_around() hubo.move() hubo.move() turn_around() if not hubo.right_is_clear(): z=z+1 hubo.move() if z==2: hubo.drop_beeper() hubo.move() check() else: turn_right() hubo.move() check() z=0 else: if hubo.front_is_clear(): hubo.move() check() else: hubo.turn_left() hubo.move() check() if x==1: hubo.pick_beeper() turn_right() hubo.move() hubo.drop_beeper() turn_right() hubo.move() check() move()
1
1
TA
What is pick_beeper() in task2?
from cs1robots import * load_world("worlds/hurdles1.wld") R1 = Robot() R1.set_trace("blue") def turn_right(): for i in range(3): R1.turn_left() for i in range(4): R1.move() R1.turn_left() R1.move() turn_right() R1.move() turn_right() R1.move() R1.turn_left() R1.move() R1.pick_beeper()
17
17
variable
This is a function that the robot (R1) picks up a yellow coin with 1 written on it.
cs1qa
null
null
null
null
null
Question: What is pick_beeper() in task2? Code: from cs1robots import * load_world("worlds/hurdles1.wld") R1 = Robot() R1.set_trace("blue") def turn_right(): for i in range(3): R1.turn_left() for i in range(4): R1.move() R1.turn_left() R1.move() turn_right() R1.move() turn_right() R1.move() R1.turn_left() R1.move() R1.pick_beeper()
1
4
TA
The last thing you did without diagonal_bottom() is because of the conflict?
from cs1robots import* load_world('worlds/harvest2.wld') hubo=Robot() hubo.set_trace('blue') def turn_right(): hubo.turn_left() hubo.turn_left() hubo.turn_left() for i in range(4): hubo.move() def diagonal_top(): for i in range(6): hubo.move() hubo.turn_left() hubo.move() hubo.pick_beeper() turn_right() hubo.turn_left() hubo.move() hubo.turn_left() def diagonal_bottom(): for i in range(5): hubo.move() hubo.pick_beeper() hubo.turn_left() hubo.move() turn_right() hubo.move() hubo.pick_beeper() hubo.move() hubo.move() hubo.turn_left() hubo.turn_left() for i in range(2): diagonal_top() diagonal_bottom() diagonal_top() for i in range(5): hubo.move() hubo.pick_beeper() hubo.turn_left() hubo.move() turn_right() hubo.move() hubo.pick_beeper()
33
44
reasoning
Yeah
cs1qa
null
null
null
null
null
Question: The last thing you did without diagonal_bottom() is because of the conflict? Code: from cs1robots import* load_world('worlds/harvest2.wld') hubo=Robot() hubo.set_trace('blue') def turn_right(): hubo.turn_left() hubo.turn_left() hubo.turn_left() for i in range(4): hubo.move() def diagonal_top(): for i in range(6): hubo.move() hubo.turn_left() hubo.move() hubo.pick_beeper() turn_right() hubo.turn_left() hubo.move() hubo.turn_left() def diagonal_bottom(): for i in range(5): hubo.move() hubo.pick_beeper() hubo.turn_left() hubo.move() turn_right() hubo.move() hubo.pick_beeper() hubo.move() hubo.move() hubo.turn_left() hubo.turn_left() for i in range(2): diagonal_top() diagonal_bottom() diagonal_top() for i in range(5): hubo.move() hubo.pick_beeper() hubo.turn_left() hubo.move() turn_right() hubo.move() hubo.pick_beeper()
4
0
TA
Briefly explain the name and action of the function you add in Task1!
from cs1robots import * load_world('worlds/add34.wld') my_robot = Robot() ''' Abstract, Final, Static class "Logic". Contains useful logics, which are frequently used. Since I started programming with Java, "global functions" do not look so good for me :D ''' class Logic: @staticmethod def rpt(fu, i, args=tuple()): #RePeaT for cnt in range(i): fu(*args) @staticmethod def rptl(fu, i, args=tuple()): #RePeaT, but check Last run for cnt in range(i): fu(*args, last = (cnt == i - 1)) @staticmethod def dw(condition, task = lambda : None): #Do While condition is true cnt = 0 while condition(): task() cnt -= -1 return cnt @staticmethod def until(condition, task = lambda : None): #do UNTIL condition is true cnt = 0 while not condition(): task() cnt -= -1 return cnt @staticmethod def dt(*tasks): #Do Tasks for task in tasks: task() ''' RobotController has-a Robot. ''' class RobotController: def __init__(self, robot): self.rb = robot self.setup_commands() def mv(self, i = 1): Logic.rpt(self.rb.move, i) ''' For who feel like "tl; dr:" start with... "t" -> turn "c" -> is it clear? "b" -> beeper work ''' def setup_commands(self): self.tl = self.rb.turn_left #Turn Left self.tr = lambda : Logic.rpt(self.tl, 3) #Turn Right self.tb = lambda : Logic.rpt(self.tl, 2) #Turn Back self.tn = lambda : Logic.until(self.rb.facing_north, self.tl) #Turn North self.tw = lambda : Logic.dt(self.tn, self.tl) self.ts = lambda : Logic.dt(self.tn, self.tb) self.te = lambda : Logic.dt(self.tn, self.tr) # coding at almost 3:00 AM... My life is legend self.cf = self.rb.front_is_clear #Clear Front self.cl = self.rb.left_is_clear #Clear Left self.cr = self.rb.right_is_clear #Clear Right self.bo = self.rb.on_beeper #Beeper On? self.bp = self.rb.pick_beeper #Beeper Pick self.bd = self.rb.drop_beeper #Beeper Drop self.bc = self.rb.carries_beepers #Beeper Carries? self.st = self.rb.set_trace self.mw = lambda : Logic.dw(self.cf, self.mv) #Move to Wall def setup_self(self): Logic.dt(self.mw, self.tl, self.mv, self.tl) def count_beeps(self): return Logic.dw(self.bo, self.bp) def add_digit(self, addition): foo = addition + self.count_beeps() Logic.dt(self.tl, self.mv) foo += self.count_beeps() Logic.rpt(self.bd, (foo%10)) Logic.dt(self.tb, self.mv, self.tl) return foo//10 def go_to_end_point(self): Logic.dt(self.tl, self.mv, self.tl) Logic.until(self.bo, self.mv) Logic.dt(self.tb, self.mv) def solve_assignment(self): self.setup_self() bar = 0 while self.cf(): bar = self.add_digit(bar) if self.cf(): self.mv() self.go_to_end_point() robot_control = RobotController(my_robot) robot_control.solve_assignment()
124
131
variable
solve_assignment. It repeats add_digit that adds the number of digits to the currently standing column, and performs retrieval and map end processing.
cs1qa
null
null
null
null
null
Question: Briefly explain the name and action of the function you add in Task1! Code: from cs1robots import * load_world('worlds/add34.wld') my_robot = Robot() ''' Abstract, Final, Static class "Logic". Contains useful logics, which are frequently used. Since I started programming with Java, "global functions" do not look so good for me :D ''' class Logic: @staticmethod def rpt(fu, i, args=tuple()): #RePeaT for cnt in range(i): fu(*args) @staticmethod def rptl(fu, i, args=tuple()): #RePeaT, but check Last run for cnt in range(i): fu(*args, last = (cnt == i - 1)) @staticmethod def dw(condition, task = lambda : None): #Do While condition is true cnt = 0 while condition(): task() cnt -= -1 return cnt @staticmethod def until(condition, task = lambda : None): #do UNTIL condition is true cnt = 0 while not condition(): task() cnt -= -1 return cnt @staticmethod def dt(*tasks): #Do Tasks for task in tasks: task() ''' RobotController has-a Robot. ''' class RobotController: def __init__(self, robot): self.rb = robot self.setup_commands() def mv(self, i = 1): Logic.rpt(self.rb.move, i) ''' For who feel like "tl; dr:" start with... "t" -> turn "c" -> is it clear? "b" -> beeper work ''' def setup_commands(self): self.tl = self.rb.turn_left #Turn Left self.tr = lambda : Logic.rpt(self.tl, 3) #Turn Right self.tb = lambda : Logic.rpt(self.tl, 2) #Turn Back self.tn = lambda : Logic.until(self.rb.facing_north, self.tl) #Turn North self.tw = lambda : Logic.dt(self.tn, self.tl) self.ts = lambda : Logic.dt(self.tn, self.tb) self.te = lambda : Logic.dt(self.tn, self.tr) # coding at almost 3:00 AM... My life is legend self.cf = self.rb.front_is_clear #Clear Front self.cl = self.rb.left_is_clear #Clear Left self.cr = self.rb.right_is_clear #Clear Right self.bo = self.rb.on_beeper #Beeper On? self.bp = self.rb.pick_beeper #Beeper Pick self.bd = self.rb.drop_beeper #Beeper Drop self.bc = self.rb.carries_beepers #Beeper Carries? self.st = self.rb.set_trace self.mw = lambda : Logic.dw(self.cf, self.mv) #Move to Wall def setup_self(self): Logic.dt(self.mw, self.tl, self.mv, self.tl) def count_beeps(self): return Logic.dw(self.bo, self.bp) def add_digit(self, addition): foo = addition + self.count_beeps() Logic.dt(self.tl, self.mv) foo += self.count_beeps() Logic.rpt(self.bd, (foo%10)) Logic.dt(self.tb, self.mv, self.tl) return foo//10 def go_to_end_point(self): Logic.dt(self.tl, self.mv, self.tl) Logic.until(self.bo, self.mv) Logic.dt(self.tb, self.mv) def solve_assignment(self): self.setup_self() bar = 0 while self.cf(): bar = self.add_digit(bar) if self.cf(): self.mv() self.go_to_end_point() robot_control = RobotController(my_robot) robot_control.solve_assignment()
9
0
TA
Can you explain reverse_cards first?
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 check_num=0 class Card(object): def personality(self, img, name): self.img=img self.name=name def state(self): self.state=False def initialize(): for i in range(6): for k in range(4): img = Image(path+names[i]) temp=Card() temp.personality(img, names[i]) temp.state() cards.append(temp) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) random.shuffle(cards) def reverse_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): cards[i].img.moveTo(i_w + w, i_h+h) canvas.add(cards[i].img) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(4) def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): if cards[i].state==True: cards[i].img.moveTo(i_w + w, i_h+h) canvas.add(cards[i].img) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(2) def is_valid(num1, num2): if num1<0 or num1>23 or num2<0 or num2>23: return False elif num1==num2: return False elif cards[num1].state==True or cards[num2].state==True: return False else: return True def check(num1, num2): cards[num1].state=True cards[num2].state=True print_cards() if cards[num1].name==cards[num2].name: return True else: cards[num1].state=False cards[num2].state=False return False initialize() reverse_cards() print_cards() print("### Welcome to the Python Memento game!!! ###") while not check_num==12: print(str(tries) + "th try. You got " + str(check_num) + " pairs.") num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") check_num=check_num+1 print_cards() else: print("Wrong!") print_cards() tries=tries+1
45
58
variable
reverse_cards is a function that shows cards shuffled randomly over the first 4 seconds.
cs1qa
null
null
null
null
null
Question: Can you explain reverse_cards first? Code: from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 check_num=0 class Card(object): def personality(self, img, name): self.img=img self.name=name def state(self): self.state=False def initialize(): for i in range(6): for k in range(4): img = Image(path+names[i]) temp=Card() temp.personality(img, names[i]) temp.state() cards.append(temp) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) random.shuffle(cards) def reverse_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): cards[i].img.moveTo(i_w + w, i_h+h) canvas.add(cards[i].img) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(4) def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): if cards[i].state==True: cards[i].img.moveTo(i_w + w, i_h+h) canvas.add(cards[i].img) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(2) def is_valid(num1, num2): if num1<0 or num1>23 or num2<0 or num2>23: return False elif num1==num2: return False elif cards[num1].state==True or cards[num2].state==True: return False else: return True def check(num1, num2): cards[num1].state=True cards[num2].state=True print_cards() if cards[num1].name==cards[num2].name: return True else: cards[num1].state=False cards[num2].state=False return False initialize() reverse_cards() print_cards() print("### Welcome to the Python Memento game!!! ###") while not check_num==12: print(str(tries) + "th try. You got " + str(check_num) + " pairs.") num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") check_num=check_num+1 print_cards() else: print("Wrong!") print_cards() tries=tries+1
4
2
TA
Please explain task3 as well
import math sin = math.sin pi = math.pi a=input('How many steps? ') for i in range(int(a)): x = float(i) / 30.0 * 2 * pi print (sin(x))
5
8
code_explain
task3 receives a number into the variable a and increases the given x value constant during a loop to output the sine value.
cs1qa
null
null
null
null
null
Question: Please explain task3 as well Code: import math sin = math.sin pi = math.pi a=input('How many steps? ') for i in range(int(a)): x = float(i) / 30.0 * 2 * pi print (sin(x))
2
0
TA
Please explain from task1!
from cs1robots import* load_world('worlds/harvest3.wld') hubo=Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def harvest_a_carrot(): hubo.move() if hubo.on_beeper(): hubo.pick_beeper() def harvest_odd_line(): harvest_a_carrot() hubo.turn_left() for i in range(5): harvest_a_carrot() turn_right() def harvest_even_line(): harvest_a_carrot() turn_right() for i in range(5): harvest_a_carrot() hubo.turn_left() def harvest(): for i in range(3): harvest_odd_line() harvest_even_line() harvest()
7
27
code_explain
task1 uses the if statement to think about the case where there is no carrot in the existing task. The picking function has been changed so that only carrots are picked up.
cs1qa
null
null
null
null
null
Question: Please explain from task1! Code: from cs1robots import* load_world('worlds/harvest3.wld') hubo=Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def harvest_a_carrot(): hubo.move() if hubo.on_beeper(): hubo.pick_beeper() def harvest_odd_line(): harvest_a_carrot() hubo.turn_left() for i in range(5): harvest_a_carrot() turn_right() def harvest_even_line(): harvest_a_carrot() turn_right() for i in range(5): harvest_a_carrot() hubo.turn_left() def harvest(): for i in range(3): harvest_odd_line() harvest_even_line() harvest()
1
1
TA
Can you explain what function pattern() is in task2?
from cs1robots import* load_world('worlds/hurdles1.wld') hubo=Robot() hubo.set_trace('red') def pattern(): hubo.move() hubo.turn_left() hubo.move() for i in range(3): hubo.turn_left() hubo.move() for i in range(3): hubo.turn_left() hubo.move() hubo.turn_left() for i in range(4): pattern() hubo.move() hubo.pick_beeper()
7
17
variable
In task2, pattern() just specified a function to skip one hurdle like that.
cs1qa
null
null
null
null
null
Question: Can you explain what function pattern() is in task2? Code: from cs1robots import* load_world('worlds/hurdles1.wld') hubo=Robot() hubo.set_trace('red') def pattern(): hubo.move() hubo.turn_left() hubo.move() for i in range(3): hubo.turn_left() hubo.move() for i in range(3): hubo.turn_left() hubo.move() hubo.turn_left() for i in range(4): pattern() hubo.move() hubo.pick_beeper()
8
1
TA
Why did you use a strip on lines 18-19 in the second task?
f=open("average-latitude-longitude-countries.csv", 'r') for line in f: word=line.strip() print(word) f.close() f=open("average-latitude-longitude-countries.csv", 'r') a=[] b=[] f.readline() for line in f: word=line.strip() p=word.split(',') if len(p)>4: while len(p)>4: name=p.pop(2) p[1]=p[1]+","+name p[0]=p[0].strip('\"') p[1]=p[1].strip('\"') p[2]=float(p[2]) p[3]=float(p[3]) a.append((p[0],p[1])) b.append((p[0],(p[2],p[3]))) print(a) print(b) f.close() for i in range(len(b)): if b[i][1][0]<0: for j in range(len(a)): if b[i][0]==a[j][0]: print(a[j][1]) code=input("Enter country code: ") for i in range(len(a)): if a[i][0]==code: print(a[i][1])
10
22
reasoning
When printed, the country code and country name are displayed in the form of a double quotation mark in a small quotation mark in the list (such as'"code"'), so I used a strip to remove the large quotation marks.
cs1qa
null
null
null
null
null
Question: Why did you use a strip on lines 18-19 in the second task? Code: f=open("average-latitude-longitude-countries.csv", 'r') for line in f: word=line.strip() print(word) f.close() f=open("average-latitude-longitude-countries.csv", 'r') a=[] b=[] f.readline() for line in f: word=line.strip() p=word.split(',') if len(p)>4: while len(p)>4: name=p.pop(2) p[1]=p[1]+","+name p[0]=p[0].strip('\"') p[1]=p[1].strip('\"') p[2]=float(p[2]) p[3]=float(p[3]) a.append((p[0],p[1])) b.append((p[0],(p[2],p[3]))) print(a) print(b) f.close() for i in range(len(b)): if b[i][1][0]<0: for j in range(len(a)): if b[i][0]==a[j][0]: print(a[j][1]) code=input("Enter country code: ") for i in range(len(a)): if a[i][0]==code: print(a[i][1])
9
0
TA
What information does an object of class Card in task2 have?
from cs1graphics import * import time canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct = 0 class Card: def __init__(self, img, name): self.img=img self.name=name self.state=False def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) cards.append(Card(img, names[i])) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) from random import shuffle shuffle(cards) for i in range(24): cards[i].state=True print_cards() for i in range(24): cards[i].state=False def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): if cards[i].state: cards[i].img.moveTo(i_w + w, i_h+h) canvas.add(cards[i].img) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): if cards[num1].state or cards[num2].state: return False if 0<=num1<=23 and 0<=num2<=23 is False: return False if num1==num2: return False return True def check(num1, num2): cards[num1].state=True cards[num2].state=True print_cards() if cards[num1].name==cards[num2].name: global correct correct+=1 return True else: cards[num1].state=False cards[num2].state=False print_cards() return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") while correct<12: if tries==1: print("1st try. You got " + str(correct) + " pairs.") elif tries==2: print("2nd try. You got " + str(correct) + " pairs.") elif tries==3: print("3rd try. You got " + str(correct) + " pairs.") else: print(str(tries) + "th try. You got " + str(correct) + " pairs.") num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") tries+=1
14
18
variable
Has the card image, shape, number, value of the card, and whether the card is hidden
cs1qa
null
null
null
null
null
Question: What information does an object of class Card in task2 have? Code: from cs1graphics import * import time canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct = 0 class Card: def __init__(self, img, name): self.img=img self.name=name self.state=False def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) cards.append(Card(img, names[i])) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) from random import shuffle shuffle(cards) for i in range(24): cards[i].state=True print_cards() for i in range(24): cards[i].state=False def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): if cards[i].state: cards[i].img.moveTo(i_w + w, i_h+h) canvas.add(cards[i].img) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): if cards[num1].state or cards[num2].state: return False if 0<=num1<=23 and 0<=num2<=23 is False: return False if num1==num2: return False return True def check(num1, num2): cards[num1].state=True cards[num2].state=True print_cards() if cards[num1].name==cards[num2].name: global correct correct+=1 return True else: cards[num1].state=False cards[num2].state=False print_cards() return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") while correct<12: if tries==1: print("1st try. You got " + str(correct) + " pairs.") elif tries==2: print("2nd try. You got " + str(correct) + " pairs.") elif tries==3: print("3rd try. You got " + str(correct) + " pairs.") else: print(str(tries) + "th try. You got " + str(correct) + " pairs.") num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") tries+=1
5
0
TA
can you briefly explain task1 withdrawal function??
balance = 0 def deposit(money) : global balance # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance balance=balance+money print("You deposited {} won".format(money)) # Do something on here ! pass ################# def withdrawal(money) : global balance # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance if balance>=money: balance=balance-money print("You've withdrawn {} won".format (money)) if balance<money: print("You'be withdrawn {} won".format (money)) print("But you only have {} won".format (balance)) # Do something on here ! pass ################# def bank() : global balance # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. if process =='': return # If a user's input is 'd', then ask the amount of money to deposit and deposit it. if process == 'd': money = int(input('How much do you want to deposit?')) deposit(money) # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. elif process == 'w': money=int(input('How much do you want to withdraw?')) withdrawal(money) # If a user's input is 'c', then check the current balance. elif process == 'c': print('Your current balance is {} won'.format (balance)) else : print('Please, press d or w or c or return') ################# ### implement ### ################# # Do something on here ! pass ################# bank()
16
29
variable
withdrawal is a function that subtracts by the number you entered, but issues a warning when the subtraction number is larger.
cs1qa
null
null
null
null
null
Question: can you briefly explain task1 withdrawal function?? Code: balance = 0 def deposit(money) : global balance # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance balance=balance+money print("You deposited {} won".format(money)) # Do something on here ! pass ################# def withdrawal(money) : global balance # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance if balance>=money: balance=balance-money print("You've withdrawn {} won".format (money)) if balance<money: print("You'be withdrawn {} won".format (money)) print("But you only have {} won".format (balance)) # Do something on here ! pass ################# def bank() : global balance # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. if process =='': return # If a user's input is 'd', then ask the amount of money to deposit and deposit it. if process == 'd': money = int(input('How much do you want to deposit?')) deposit(money) # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. elif process == 'w': money=int(input('How much do you want to withdraw?')) withdrawal(money) # If a user's input is 'c', then check the current balance. elif process == 'c': print('Your current balance is {} won'.format (balance)) else : print('Please, press d or w or c or return') ################# ### implement ### ################# # Do something on here ! pass ################# bank()
2
0
TA
Could you briefly explain what the move_and_pick function does?
from cs1robots import * load_world('worlds/harvest3.wld') hubo = Robot() hubo.set_trace('blue') def move_and_pick() : hubo.move() if hubo.on_beeper() : hubo.pick_beeper() def turn_right(): hubo.turn_left() hubo.turn_left() hubo.turn_left() for i in range (2): while hubo.front_is_clear(): move_and_pick() for i in range (2): hubo.turn_left() move_and_pick() for i in range (4): move_and_pick() for i in range (2): turn_right() move_and_pick() while hubo.front_is_clear(): move_and_pick() for i in range (2): hubo.turn_left() move_and_pick() for i in range (4): move_and_pick()
5
8
variable
It is a function that moves one space and picks up if there is a beeper in the moved position.
cs1qa
null
null
null
null
null
Question: Could you briefly explain what the move_and_pick function does? Code: from cs1robots import * load_world('worlds/harvest3.wld') hubo = Robot() hubo.set_trace('blue') def move_and_pick() : hubo.move() if hubo.on_beeper() : hubo.pick_beeper() def turn_right(): hubo.turn_left() hubo.turn_left() hubo.turn_left() for i in range (2): while hubo.front_is_clear(): move_and_pick() for i in range (2): hubo.turn_left() move_and_pick() for i in range (4): move_and_pick() for i in range (2): turn_right() move_and_pick() while hubo.front_is_clear(): move_and_pick() for i in range (2): hubo.turn_left() move_and_pick() for i in range (4): move_and_pick()
3
1
TA
Is there any special reason for writing the while statement in Task2 line13?
from cs1robots import * # Your code must work for all world files below. #load_world( "worlds/trash1.wld" ) load_world( "worlds/trash2.wld" ) my_robot = Robot() def turn_right(): for i in range(3): my_robot.turn_left() number_beeper=0 while my_robot.carries_beepers: while my_robot.on_beeper(): my_robot.pick_beeper() number_beeper=number_beeper+1 if not my_robot.front_is_clear(): break my_robot.move() my_robot.turn_left() my_robot.turn_left() while my_robot.front_is_clear(): my_robot.move() turn_right() my_robot.move() for i in range(number_beeper): my_robot.drop_beeper()
12
18
reasoning
I used it to keep the inner loops repeatable while the robot moves the beeper.
cs1qa
null
null
null
null
null
Question: Is there any special reason for writing the while statement in Task2 line13? Code: from cs1robots import * # Your code must work for all world files below. #load_world( "worlds/trash1.wld" ) load_world( "worlds/trash2.wld" ) my_robot = Robot() def turn_right(): for i in range(3): my_robot.turn_left() number_beeper=0 while my_robot.carries_beepers: while my_robot.on_beeper(): my_robot.pick_beeper() number_beeper=number_beeper+1 if not my_robot.front_is_clear(): break my_robot.move() my_robot.turn_left() my_robot.turn_left() while my_robot.front_is_clear(): my_robot.move() turn_right() my_robot.move() for i in range(number_beeper): my_robot.drop_beeper()
8
0
TA
What is the f.read() function in task1?
from time import sleep import elice_utils def merge(input_filenames, output_filename): temp_list = [] for name in input_filenames: fin = open(name, 'rt') temp_list.append(fin.read()) fin.close() fout = open(output_filename, 'xt') fout.write(''.join(temp_list)) fout.close() return None merge(['kaist1.txt', 'kaist2.txt', 'kaist3.txt'], 'output.txt') sleep(0.5) # Wait 0.5 seconds before creating a download link. elice_utils.send_file('output.txt')
7
8
variable
This function reads all the text in the file.
cs1qa
null
null
null
null
null
Question: What is the f.read() function in task1? Code: from time import sleep import elice_utils def merge(input_filenames, output_filename): temp_list = [] for name in input_filenames: fin = open(name, 'rt') temp_list.append(fin.read()) fin.close() fout = open(output_filename, 'xt') fout.write(''.join(temp_list)) fout.close() return None merge(['kaist1.txt', 'kaist2.txt', 'kaist3.txt'], 'output.txt') sleep(0.5) # Wait 0.5 seconds before creating a download link. elice_utils.send_file('output.txt')
5
0
TA
How did you use the balance variable in Task1?
balance = 0 def deposit(money) : # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance global balance balance+=money ################# ### implement ### ################# # Do something on here ! pass ################# def withdrawal(money) : global balance # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance if (money<=balance): balance-=money print("You've withdraw %d won"%money) else: print("You've withdrawn %d won"%money) print("But you only have %d won"%balance) ################# ### implement ### ################# # Do something on here ! pass ################# def bank() : # Input : (None) No Input # Output : (None) No Output global balance while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") if(process==''): return # If a user's input is empty string (''), then quit this function. elif(process=='d'): money=int(input("How much do you want to deposit?")) deposit(money) print("Your deposited %d won"%money) # If a user's input is 'd', then ask the amount of money to deposit and deposit it. elif(process=='w'): money=int(input("How much do you want to withdraw?")) withdrawal(money) # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. elif(process=='c'): print('Your current balance is',balance,'won') # If a user's input is 'c', then check the current balance. else: print("Please, press d or w or c or return") ################# ### implement ### ################# # Do something on here ! pass ################# bank()
0
33
variable
The balance variable was used as a variable representing the total money and used as a global variable so that the amount changed in the function was applied to the entire program.
cs1qa
null
null
null
null
null
Question: How did you use the balance variable in Task1? Code: balance = 0 def deposit(money) : # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance global balance balance+=money ################# ### implement ### ################# # Do something on here ! pass ################# def withdrawal(money) : global balance # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance if (money<=balance): balance-=money print("You've withdraw %d won"%money) else: print("You've withdrawn %d won"%money) print("But you only have %d won"%balance) ################# ### implement ### ################# # Do something on here ! pass ################# def bank() : # Input : (None) No Input # Output : (None) No Output global balance while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") if(process==''): return # If a user's input is empty string (''), then quit this function. elif(process=='d'): money=int(input("How much do you want to deposit?")) deposit(money) print("Your deposited %d won"%money) # If a user's input is 'd', then ask the amount of money to deposit and deposit it. elif(process=='w'): money=int(input("How much do you want to withdraw?")) withdrawal(money) # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. elif(process=='c'): print('Your current balance is',balance,'won') # If a user's input is 'c', then check the current balance. else: print("Please, press d or w or c or return") ################# ### implement ### ################# # Do something on here ! pass ################# bank()
8
0
TA
Please explain the ‘r’ and ‘w’ variables of open().
from time import sleep import elice_utils def merge(input_filenames, output_filename): d = open(output_filename , 'w') a = len(input_filenames) for i in range(a): c = input_filenames[i] f = open(c, 'r') b = f.readlines() for x in range(len(b)): d.write(b[x]) f.close() d.close() pass merge(['kaist1.txt', 'kaist2.txt', 'kaist3.txt'], 'output.txt') sleep(0.5) # Wait 0.5 seconds before creating a download link. elice_utils.send_file('output.txt')
4
8
variable
r is used to read files and w is used to write files.
cs1qa
null
null
null
null
null
Question: Please explain the ‘r’ and ‘w’ variables of open(). Code: from time import sleep import elice_utils def merge(input_filenames, output_filename): d = open(output_filename , 'w') a = len(input_filenames) for i in range(a): c = input_filenames[i] f = open(c, 'r') b = f.readlines() for x in range(len(b)): d.write(b[x]) f.close() d.close() pass merge(['kaist1.txt', 'kaist2.txt', 'kaist3.txt'], 'output.txt') sleep(0.5) # Wait 0.5 seconds before creating a download link. elice_utils.send_file('output.txt')
3
4
TA
in task5 image.set(x, y, yellow) Mean?
from cs1media import * # This code converts an image into a black & white poster. threshold1 = 100 threshold2 = 200 white = (255, 255, 255) black = (0, 0, 0) yellow = (255, 255, 0) green = (0, 255, 0) blue = (0, 0, 255) image = load_picture('./images/minion.jpg') width, height = image.size() for y in range(height): for x in range(width): r, g, b = image.get(x, y) average_brightness = (r + g + b) // 3 if average_brightness > threshold2: image.set(x, y, yellow) elif average_brightness < threshold1: image.set(x, y, blue) else: image.set(x, y, green) image.show()
20
20
variable
The pixel color of the x and y coordinates is set to yellow as defined above.
cs1qa
null
null
null
null
null
Question: in task5 image.set(x, y, yellow) Mean? Code: from cs1media import * # This code converts an image into a black & white poster. threshold1 = 100 threshold2 = 200 white = (255, 255, 255) black = (0, 0, 0) yellow = (255, 255, 0) green = (0, 255, 0) blue = (0, 0, 255) image = load_picture('./images/minion.jpg') width, height = image.size() for y in range(height): for x in range(width): r, g, b = image.get(x, y) average_brightness = (r + g + b) // 3 if average_brightness > threshold2: image.set(x, y, yellow) elif average_brightness < threshold1: image.set(x, y, blue) else: image.set(x, y, green) image.show()
2
2
TA
Could you please tell me why I set the conditions this way?
from cs1robots import * load_world('worlds/hurdles3.wld') hubo= Robot(beepers=100) hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def jump_one_hurdle(): hubo.turn_left() hubo.move() turn_right() hubo.move() turn_right() hubo.move() hubo.turn_left() while not hubo.on_beeper(): if hubo.front_is_clear(): hubo.move() else: jump_one_hurdle()
18
22
reasoning
The second task condition told me to stop if you step on the beeper. If you step on the beeper, the conditions below will not work. Before stepping on the beeper, the lower door will run and move over the hurdles
cs1qa
null
null
null
null
null
Question: Could you please tell me why I set the conditions this way? Code: from cs1robots import * load_world('worlds/hurdles3.wld') hubo= Robot(beepers=100) hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def jump_one_hurdle(): hubo.turn_left() hubo.move() turn_right() hubo.move() turn_right() hubo.move() hubo.turn_left() while not hubo.on_beeper(): if hubo.front_is_clear(): hubo.move() else: jump_one_hurdle()
1
2
TA
Is there a reason for defining jump_up() and jump_down() separately in stair_up() and stair_down()?
from cs1robots import * load_world("worlds/newspaper.wld") hubo = Robot(beepers=1) hubo.set_trace("blue") def turn_right(): for i in range(3): hubo.turn_left() def jump_up(): hubo.turn_left() hubo.move() turn_right() hubo.move() def stair_up(): for i in range (4): jump_up() hubo.move() def jump_down(): hubo.move() jump_up() def stair_down(): for i in range (4): jump_down() hubo.move() stair_up() hubo.drop_beeper() turn_right() turn_right() hubo.move() stair_down()
9
26
reasoning
I have defined it separately to clearly indicate going up and going down.
cs1qa
null
null
null
null
null
Question: Is there a reason for defining jump_up() and jump_down() separately in stair_up() and stair_down()? Code: from cs1robots import * load_world("worlds/newspaper.wld") hubo = Robot(beepers=1) hubo.set_trace("blue") def turn_right(): for i in range(3): hubo.turn_left() def jump_up(): hubo.turn_left() hubo.move() turn_right() hubo.move() def stair_up(): for i in range (4): jump_up() hubo.move() def jump_down(): hubo.move() jump_up() def stair_down(): for i in range (4): jump_down() hubo.move() stair_up() hubo.drop_beeper() turn_right() turn_right() hubo.move() stair_down()
6
4
TA
Please explain your last task!
from cs1robots import * # create_world() # load_world('worlds/world_file_name.wld') load_world('worlds/harvest2.wld') hubo = Robot() def turn_right(): for i in range(3): hubo.turn_left() def diagonal(): hubo.pick_beeper() hubo.move() hubo.turn_left() hubo.move() turn_right() for i in range(5): hubo.move() hubo.turn_left() hubo.move() for i in range(2): for j in range(5): diagonal() hubo.pick_beeper() hubo.move() turn_right() hubo.move() turn_right() for k in range(5): diagonal() hubo.pick_beeper() hubo.turn_left() hubo.move() hubo.turn_left() hubo.move() for j in range(5): diagonal() hubo.pick_beeper() hubo.move() turn_right() hubo.move() turn_right() for k in range(5): diagonal() hubo.pick_beeper()
18
50
code_explain
This is done in a zigzag diagonal direction. The diagonal function consists of moving-left-going-right rotation while looking up. Diagonal lines going up left and down right have different viewing directions, but the process of action is the same. So, only the point where the direction changes is entered separately and the process of moving diagonally is repeated.
cs1qa
null
null
null
null
null
Question: Please explain your last task! Code: from cs1robots import * # create_world() # load_world('worlds/world_file_name.wld') load_world('worlds/harvest2.wld') hubo = Robot() def turn_right(): for i in range(3): hubo.turn_left() def diagonal(): hubo.pick_beeper() hubo.move() hubo.turn_left() hubo.move() turn_right() for i in range(5): hubo.move() hubo.turn_left() hubo.move() for i in range(2): for j in range(5): diagonal() hubo.pick_beeper() hubo.move() turn_right() hubo.move() turn_right() for k in range(5): diagonal() hubo.pick_beeper() hubo.turn_left() hubo.move() hubo.turn_left() hubo.move() for j in range(5): diagonal() hubo.pick_beeper() hubo.move() turn_right() hubo.move() turn_right() for k in range(5): diagonal() hubo.pick_beeper()
2
0
TA
Is there a reason for dividing move1 and move2 in task1?
from cs1robots import * load_world("worlds/harvest3.wld") hubo = Robot() hubo.set_trace("blue") def turn_right(): for i in range(3): hubo.turn_left() def move_and_pick(): hubo.move() if hubo.on_beeper(): hubo.pick_beeper() def move1(): for i in range(5): move_and_pick() hubo.turn_left() move_and_pick() hubo.turn_left() def move2(): for i in range(5): move_and_pick() turn_right() move_and_pick() turn_right() move_and_pick() for i in range(2): move1() move2() move1() for i in range(5): move_and_pick()
11
22
reasoning
Because I tried to separate the two cases of turning left and turning right
cs1qa
null
null
null
null
null
Question: Is there a reason for dividing move1 and move2 in task1? Code: from cs1robots import * load_world("worlds/harvest3.wld") hubo = Robot() hubo.set_trace("blue") def turn_right(): for i in range(3): hubo.turn_left() def move_and_pick(): hubo.move() if hubo.on_beeper(): hubo.pick_beeper() def move1(): for i in range(5): move_and_pick() hubo.turn_left() move_and_pick() hubo.turn_left() def move2(): for i in range(5): move_and_pick() turn_right() move_and_pick() turn_right() move_and_pick() for i in range(2): move1() move2() move1() for i in range(5): move_and_pick()
8
1
TA
Why is there an input("press again") in that animation?
from cs1graphics import * from time import sleep canvas = Canvas(800, 600) canvas.setBackgroundColor("light blue") canvas.setTitle("Zoo") ground = Rectangle(800, 250, Point(400, 475)) ground.setFillColor((0, 255, 0)) ground.setDepth(100) ground.setBorderWidth(5) ground.setBorderColor((0, 255, 0)) canvas.add(ground) elephant = Layer() leg1 = Layer() leg2 = Layer() leg3 = Layer() leg4 = Layer() head = Layer() tail = Layer() nose = Layer() elephant.add(leg1) elephant.add(leg2) elephant.add(leg3) elephant.add(leg4) elephant.add(head) elephant.add(tail) head.add(nose) body = Rectangle(140, 100, Point(400, 320)) body.setFillColor((170, 170, 170)) body.setBorderWidth(0) body.setDepth(100) elephant.add(body) face = Rectangle(80, 61, Point(320, 260)) face.setFillColor((170, 170, 170)) face.setBorderWidth(0) head.add(face) eye = Circle(10, Point(305, 255)) eye.setFillColor((30, 30, 30)) eye.setBorderWidth(0) head.add(eye) horn = Rectangle(60, 11, Point(250, 280)) horn.setFillColor((230, 230, 230)) horn.setBorderWidth(0) head.add(horn) ear_positionx = 90 ear_positiony = -50 ear1 = Rectangle(50, 60, Point(280+ear_positionx, 300+ear_positiony)) ear1.setFillColor((190, 190, 190)) ear1.setBorderWidth(0) ear1.setDepth(10) head.add(ear1) ear2 = Rectangle(20, 30, Point(270+ear_positionx, 290+ear_positiony)) ear2.setFillColor((200, 200, 200)) ear2.setBorderWidth(0) ear2.setDepth(5) head.add(ear2) nose1 = Rectangle(20, 30, Point(280, 300)) nose1.setFillColor((170, 170, 170)) nose1.setBorderWidth(7) nose1.setBorderColor((150, 150, 150)) nose.add(nose1) nose2 = Rectangle(20, 30, Point(276, 330)) nose2.setFillColor((170, 170, 170)) nose2.setBorderWidth(7) nose2.setBorderColor((150, 150, 150)) nose.add(nose2) nose3 = Rectangle(20, 30, Point(274, 360)) nose3.setFillColor((170, 170, 170)) nose3.setBorderWidth(7) nose3.setBorderColor((150, 150, 150)) nose.add(nose3) nose.move(0, -10) leg1_1 = Rectangle(40, 30, Point(280, 300)) leg1_1.setFillColor((170, 170, 170)) leg1_1.setBorderWidth(3) leg1_1.setBorderColor((150, 150, 150)) leg1.add(leg1_1) leg1_2 = Rectangle(40, 30, Point(276, 330)) leg1_2.setFillColor((170, 170, 170)) leg1_2.setBorderWidth(3) leg1_2.setBorderColor((150, 150, 150)) leg1.add(leg1_2) leg1.move(60, 80) leg2_1 = Rectangle(40, 30, Point(280, 300)) leg2_1.setFillColor((170, 170, 170)) leg2_1.setBorderWidth(3) leg2_1.setBorderColor((150, 150, 150)) leg2.add(leg2_1) leg2_2 = Rectangle(40, 30, Point(276, 330)) leg2_2.setFillColor((170, 170, 170)) leg2_2.setBorderWidth(3) leg2_2.setBorderColor((150, 150, 150)) leg2.add(leg2_2) leg2.move(180, 80) leg3_1 = Rectangle(40, 30, Point(280, 300)) leg3_1.setFillColor((170, 170, 170)) leg3_1.setBorderWidth(3) leg3_1.setBorderColor((150, 150, 150)) leg3.add(leg3_1) leg3_2 = Rectangle(40, 30, Point(276, 330)) leg3_2.setFillColor((170, 170, 170)) leg3_2.setBorderWidth(3) leg3_2.setBorderColor((150, 150, 150)) leg3.add(leg3_2) leg3.move(70, 75) leg3.setDepth(120) leg4_1 = Rectangle(40, 30, Point(280, 300)) leg4_1.setFillColor((170, 170, 170)) leg4_1.setBorderWidth(3) leg4_1.setBorderColor((150, 150, 150)) leg4.add(leg4_1) leg4_2 = Rectangle(40, 30, Point(276, 330)) leg4_2.setFillColor((170, 170, 170)) leg4_2.setBorderWidth(3) leg4_2.setBorderColor((150, 150, 150)) leg4.add(leg4_2) leg4.move(190, 75) leg4.setDepth(120) tail1 = Path(Point(465, 300), Point(500, 270),Point(550, 280), Point(590, 265)) tail1.setBorderWidth(10) tail1.setBorderColor((170, 170, 170)) tail.add(tail1) tail.setDepth(10) def draw_animal(): canvas.add(elephant) # Implement this function. pass def show_animation(): for i in range(10): elephant.move(-2, 0) leg1_1.move(1, 0) leg1_2.move(2, 0) leg2_1.move(1, 0) leg2_2.move(2, 0) leg3_1.move(-1, 0) leg3_2.move(-2, 0) leg4_1.move(-1, 0) leg4_2.move(-2, 0) input("press again") for i in range(20): for i in range(20): elephant.move(-2, 0) leg1_1.move(-1, 0) leg1_2.move(-2, 0) leg2_1.move(-1, 0) leg2_2.move(-2, 0) leg3_1.move(1, 0) leg3_2.move(2, 0) leg4_1.move(1, 0) leg4_2.move(2, 0) tail1.rotate(2) for i in range(20): elephant.move(-2, 0) leg1_1.move(1, 0) leg1_2.move(2, 0) leg2_1.move(1, 0) leg2_2.move(2, 0) leg3_1.move(-1, 0) leg3_2.move(-2, 0) leg4_1.move(-1, 0) leg4_2.move(-2, 0) tail1.rotate(-2) # Implement this function. pass draw_animal() input("press any key") elephant.move(300, 0) show_animation()
154
154
reasoning
I will fix it
cs1qa
null
null
null
null
null
Question: Why is there an input("press again") in that animation? Code: from cs1graphics import * from time import sleep canvas = Canvas(800, 600) canvas.setBackgroundColor("light blue") canvas.setTitle("Zoo") ground = Rectangle(800, 250, Point(400, 475)) ground.setFillColor((0, 255, 0)) ground.setDepth(100) ground.setBorderWidth(5) ground.setBorderColor((0, 255, 0)) canvas.add(ground) elephant = Layer() leg1 = Layer() leg2 = Layer() leg3 = Layer() leg4 = Layer() head = Layer() tail = Layer() nose = Layer() elephant.add(leg1) elephant.add(leg2) elephant.add(leg3) elephant.add(leg4) elephant.add(head) elephant.add(tail) head.add(nose) body = Rectangle(140, 100, Point(400, 320)) body.setFillColor((170, 170, 170)) body.setBorderWidth(0) body.setDepth(100) elephant.add(body) face = Rectangle(80, 61, Point(320, 260)) face.setFillColor((170, 170, 170)) face.setBorderWidth(0) head.add(face) eye = Circle(10, Point(305, 255)) eye.setFillColor((30, 30, 30)) eye.setBorderWidth(0) head.add(eye) horn = Rectangle(60, 11, Point(250, 280)) horn.setFillColor((230, 230, 230)) horn.setBorderWidth(0) head.add(horn) ear_positionx = 90 ear_positiony = -50 ear1 = Rectangle(50, 60, Point(280+ear_positionx, 300+ear_positiony)) ear1.setFillColor((190, 190, 190)) ear1.setBorderWidth(0) ear1.setDepth(10) head.add(ear1) ear2 = Rectangle(20, 30, Point(270+ear_positionx, 290+ear_positiony)) ear2.setFillColor((200, 200, 200)) ear2.setBorderWidth(0) ear2.setDepth(5) head.add(ear2) nose1 = Rectangle(20, 30, Point(280, 300)) nose1.setFillColor((170, 170, 170)) nose1.setBorderWidth(7) nose1.setBorderColor((150, 150, 150)) nose.add(nose1) nose2 = Rectangle(20, 30, Point(276, 330)) nose2.setFillColor((170, 170, 170)) nose2.setBorderWidth(7) nose2.setBorderColor((150, 150, 150)) nose.add(nose2) nose3 = Rectangle(20, 30, Point(274, 360)) nose3.setFillColor((170, 170, 170)) nose3.setBorderWidth(7) nose3.setBorderColor((150, 150, 150)) nose.add(nose3) nose.move(0, -10) leg1_1 = Rectangle(40, 30, Point(280, 300)) leg1_1.setFillColor((170, 170, 170)) leg1_1.setBorderWidth(3) leg1_1.setBorderColor((150, 150, 150)) leg1.add(leg1_1) leg1_2 = Rectangle(40, 30, Point(276, 330)) leg1_2.setFillColor((170, 170, 170)) leg1_2.setBorderWidth(3) leg1_2.setBorderColor((150, 150, 150)) leg1.add(leg1_2) leg1.move(60, 80) leg2_1 = Rectangle(40, 30, Point(280, 300)) leg2_1.setFillColor((170, 170, 170)) leg2_1.setBorderWidth(3) leg2_1.setBorderColor((150, 150, 150)) leg2.add(leg2_1) leg2_2 = Rectangle(40, 30, Point(276, 330)) leg2_2.setFillColor((170, 170, 170)) leg2_2.setBorderWidth(3) leg2_2.setBorderColor((150, 150, 150)) leg2.add(leg2_2) leg2.move(180, 80) leg3_1 = Rectangle(40, 30, Point(280, 300)) leg3_1.setFillColor((170, 170, 170)) leg3_1.setBorderWidth(3) leg3_1.setBorderColor((150, 150, 150)) leg3.add(leg3_1) leg3_2 = Rectangle(40, 30, Point(276, 330)) leg3_2.setFillColor((170, 170, 170)) leg3_2.setBorderWidth(3) leg3_2.setBorderColor((150, 150, 150)) leg3.add(leg3_2) leg3.move(70, 75) leg3.setDepth(120) leg4_1 = Rectangle(40, 30, Point(280, 300)) leg4_1.setFillColor((170, 170, 170)) leg4_1.setBorderWidth(3) leg4_1.setBorderColor((150, 150, 150)) leg4.add(leg4_1) leg4_2 = Rectangle(40, 30, Point(276, 330)) leg4_2.setFillColor((170, 170, 170)) leg4_2.setBorderWidth(3) leg4_2.setBorderColor((150, 150, 150)) leg4.add(leg4_2) leg4.move(190, 75) leg4.setDepth(120) tail1 = Path(Point(465, 300), Point(500, 270),Point(550, 280), Point(590, 265)) tail1.setBorderWidth(10) tail1.setBorderColor((170, 170, 170)) tail.add(tail1) tail.setDepth(10) def draw_animal(): canvas.add(elephant) # Implement this function. pass def show_animation(): for i in range(10): elephant.move(-2, 0) leg1_1.move(1, 0) leg1_2.move(2, 0) leg2_1.move(1, 0) leg2_2.move(2, 0) leg3_1.move(-1, 0) leg3_2.move(-2, 0) leg4_1.move(-1, 0) leg4_2.move(-2, 0) input("press again") for i in range(20): for i in range(20): elephant.move(-2, 0) leg1_1.move(-1, 0) leg1_2.move(-2, 0) leg2_1.move(-1, 0) leg2_2.move(-2, 0) leg3_1.move(1, 0) leg3_2.move(2, 0) leg4_1.move(1, 0) leg4_2.move(2, 0) tail1.rotate(2) for i in range(20): elephant.move(-2, 0) leg1_1.move(1, 0) leg1_2.move(2, 0) leg2_1.move(1, 0) leg2_2.move(2, 0) leg3_1.move(-1, 0) leg3_2.move(-2, 0) leg4_1.move(-1, 0) leg4_2.move(-2, 0) tail1.rotate(-2) # Implement this function. pass draw_animal() input("press any key") elephant.move(300, 0) show_animation()
6
2
student
But I'm not sure about the fundamental reason why you need to repeat the code below as many times as the number of cards using a for statement.
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ random.shuffle(num_pads) random.shuffle(cards) ################################################################ def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if : # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### if num1 in correct_list: return False elif num2 in correct_list: return False elif num1 == num2: return False elif num1 > 23 or num2 > 23: return False else: return True ########################################################################### def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### print_cards() return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while True: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
16
30
code_understanding
Yes, as the student said, this is a very inefficient code!
cs1qa
null
null
null
null
null
Question: But I'm not sure about the fundamental reason why you need to repeat the code below as many times as the number of cards using a for statement. Code: from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ random.shuffle(num_pads) random.shuffle(cards) ################################################################ def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if : # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### if num1 in correct_list: return False elif num2 in correct_list: return False elif num1 == num2: return False elif num1 > 23 or num2 > 23: return False else: return True ########################################################################### def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### print_cards() return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while True: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
3
4
TA
task 5 Something is quite yellow. Why is the value set?
from cs1media import * # This code converts an image into a black & white poster. threshold = 100 yellow = (255, 255, 0) blue = (0, 0, 255) green = (0,255,0) image = load_picture('./images/minion.jpg') width, height = image.size() for y in range(height): for x in range(width): r, g, b = image.get(x, y) average_brightness = (r + g + b) // 3 if average_brightness > 150: image.set(x, y, yellow) elif average_brightness > 50: image.set(x, y, blue) else: image.set(x,y,green) image.show()
16
21
reasoning
The task 5 value was just set to look moderately green, because there is no specific standard.
cs1qa
null
null
null
null
null
Question: task 5 Something is quite yellow. Why is the value set? Code: from cs1media import * # This code converts an image into a black & white poster. threshold = 100 yellow = (255, 255, 0) blue = (0, 0, 255) green = (0,255,0) image = load_picture('./images/minion.jpg') width, height = image.size() for y in range(height): for x in range(width): r, g, b = image.get(x, y) average_brightness = (r + g + b) // 3 if average_brightness > 150: image.set(x, y, yellow) elif average_brightness > 50: image.set(x, y, blue) else: image.set(x,y,green) image.show()
9
0
student
In Task 1, it was written even though I didn't enter .jpg. Why?
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 class Card(object): def __init__(self, img, name, complete): self.img = img self.name = name self.complete = complete def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) cards.append(Card(img,names[i],'no')) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ random.shuffle(cards) # 3-2-1. shuffle the card list ################################################################ def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i].img.moveTo(i_w + w, i_h+h) canvas.add(cards[i].img) num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) for i in range(len(num_pads)): canvas.remove(cards[i].img) def is_valid(num1, num2): if cards[num1].complete=='yes': return False pass if cards[num2].complete=='yes': return False pass if num1==num2: return False pass if num1>23 or num1<0: return False pass if num2>23 or num2<0: ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### return False pass return True def check(num1, num2): canvas.add(cards[num1].img) canvas.add(cards[num2].img) time.sleep(1) if cards[num1].name==cards[num2].name: # TA : cards[num1][0] is image, cards[num1][1] is name of image cards[num1].complete='yes' cards[num2].complete='yes' return True else: ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### canvas.remove(cards[num1].img) canvas.remove(cards[num2].img) return False def checkcomplete(): a = [] for i in range(len(cards)): a.append(cards[i].complete) return a initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") tries = 1 ############################################################################### while True: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs if checkcomplete().count('no')>0: print(str(tries) + "th try. You got " + str(checkcomplete().count('yes')//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") ########################################################################### tries = tries + 1 else: break # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
8
9
code_understanding
Each element in the names list contains the string ".jpg".
cs1qa
null
null
null
null
null
Question: In Task 1, it was written even though I didn't enter .jpg. Why? Code: from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 class Card(object): def __init__(self, img, name, complete): self.img = img self.name = name self.complete = complete def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) cards.append(Card(img,names[i],'no')) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ random.shuffle(cards) # 3-2-1. shuffle the card list ################################################################ def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i].img.moveTo(i_w + w, i_h+h) canvas.add(cards[i].img) num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) for i in range(len(num_pads)): canvas.remove(cards[i].img) def is_valid(num1, num2): if cards[num1].complete=='yes': return False pass if cards[num2].complete=='yes': return False pass if num1==num2: return False pass if num1>23 or num1<0: return False pass if num2>23 or num2<0: ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### return False pass return True def check(num1, num2): canvas.add(cards[num1].img) canvas.add(cards[num2].img) time.sleep(1) if cards[num1].name==cards[num2].name: # TA : cards[num1][0] is image, cards[num1][1] is name of image cards[num1].complete='yes' cards[num2].complete='yes' return True else: ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### canvas.remove(cards[num1].img) canvas.remove(cards[num2].img) return False def checkcomplete(): a = [] for i in range(len(cards)): a.append(cards[i].complete) return a initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") tries = 1 ############################################################################### while True: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs if checkcomplete().count('no')>0: print(str(tries) + "th try. You got " + str(checkcomplete().count('yes')//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") ########################################################################### tries = tries + 1 else: break # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
3
0
TA
Why is line 7 in task1?
from cs1robots import * create_world() robot = Robot(orientation='W', avenue=4, street=4) robot.set_trace("red") def initial_position(): while robot.facing_north() is True: robot.turn_left() while robot.front_is_clear(): robot.move() robot.turn_left() while robot.front_is_clear(): robot.move() robot.turn_left() def set_position(): while not robot.facing_north(): robot.turn_left() set_position() initial_position()
6
6
reasoning
At first, it was written in the sense of running the code below when the robot faces north, but it doesn't seem necessary.
cs1qa
null
null
null
null
null
Question: Why is line 7 in task1? Code: from cs1robots import * create_world() robot = Robot(orientation='W', avenue=4, street=4) robot.set_trace("red") def initial_position(): while robot.facing_north() is True: robot.turn_left() while robot.front_is_clear(): robot.move() robot.turn_left() while robot.front_is_clear(): robot.move() robot.turn_left() def set_position(): while not robot.facing_north(): robot.turn_left() set_position() initial_position()
2
2
TA
Please explain each function in Task3 Hurdle
from cs1robots import * # Your code should work with any of the world files below. # TIP: Press Ctrl + '/' (or Cmd + '/' if you are using a Mac) # to comment out or restore the whole line of the code in the editor. #load_world('worlds/hurdles1.wld') #load_world('worlds/hurdles2.wld') load_world('worlds/hurdles3.wld') bot = Robot() bot.set_trace('blue') def turn_right(): bot.turn_left() bot.turn_left() bot.turn_left() def jump_one_hurdle(): if bot.front_is_clear(): bot.move() else: bot.turn_left() bot.move() turn_right() bot.move() turn_right() bot.move() bot.turn_left() while not bot.on_beeper(): jump_one_hurdle() bot.pick_beeper()
14
32
variable
I made a function that rotates to the right, and after making more than one hurdle, when it reaches the beeper, it stops and picks up the beeper.
cs1qa
null
null
null
null
null
Question: Please explain each function in Task3 Hurdle Code: from cs1robots import * # Your code should work with any of the world files below. # TIP: Press Ctrl + '/' (or Cmd + '/' if you are using a Mac) # to comment out or restore the whole line of the code in the editor. #load_world('worlds/hurdles1.wld') #load_world('worlds/hurdles2.wld') load_world('worlds/hurdles3.wld') bot = Robot() bot.set_trace('blue') def turn_right(): bot.turn_left() bot.turn_left() bot.turn_left() def jump_one_hurdle(): if bot.front_is_clear(): bot.move() else: bot.turn_left() bot.move() turn_right() bot.move() turn_right() bot.move() bot.turn_left() while not bot.on_beeper(): jump_one_hurdle() bot.pick_beeper()
4
0
TA
Can you explain task 1 algorithm?
from cs1robots import * load_world( "worlds/add2.wld" ) hubo=Robot(beepers=100) hubo.set_trace('blue') first=[] second=[] for x in range(5): hubo.move() for x in range(4): hubo.move() n=0 while hubo.on_beeper(): hubo.pick_beeper() n+=1 first.append(n) hubo.turn_left() hubo.move() hubo.turn_left() for x in range(4): n=0 while hubo.on_beeper(): hubo.pick_beeper() n+=1 second.append(n) hubo.move() second.reverse() addition=[] for x in range(4): addition.append(first[x]+second[x]) for x in range(4): if addition[x]>9: addition[x-1]+=1 addition[x]-=10 hubo.turn_left() hubo.move() hubo.turn_left() for x in range(4): hubo.move() while addition[x]!=0: hubo.drop_beeper() addition[x]-=1 hubo.turn_left() hubo.move()
0
55
code_explain
Task 1 is implemented by receiving two lines in the form of a list, calculating the sum of each component from each list in the form of a list, and then rounding up if it exceeds 10.
cs1qa
null
null
null
null
null
Question: Can you explain task 1 algorithm? Code: from cs1robots import * load_world( "worlds/add2.wld" ) hubo=Robot(beepers=100) hubo.set_trace('blue') first=[] second=[] for x in range(5): hubo.move() for x in range(4): hubo.move() n=0 while hubo.on_beeper(): hubo.pick_beeper() n+=1 first.append(n) hubo.turn_left() hubo.move() hubo.turn_left() for x in range(4): n=0 while hubo.on_beeper(): hubo.pick_beeper() n+=1 second.append(n) hubo.move() second.reverse() addition=[] for x in range(4): addition.append(first[x]+second[x]) for x in range(4): if addition[x]>9: addition[x-1]+=1 addition[x]-=10 hubo.turn_left() hubo.move() hubo.turn_left() for x in range(4): hubo.move() while addition[x]!=0: hubo.drop_beeper() addition[x]-=1 hubo.turn_left() hubo.move()
3
1
TA
For task 2, why do you have both line 18-19 and line 21-22?
from cs1robots import * # Your code must work for all world files below. # load_world( "worlds/trash1.wld" ) load_world( "worlds/trash2.wld" ) hubo=Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def uturn(): for i in range(2): turn_right() while hubo.front_is_clear(): while hubo.on_beeper(): hubo.pick_beeper() hubo.move() while hubo.on_beeper(): hubo.pick_beeper() uturn() while hubo.front_is_clear(): hubo.move() turn_right() hubo.move() while hubo.carries_beepers(): hubo.drop_beeper() uturn() hubo.move() hubo.turn_left()
17
21
reasoning
Just to pick all the beepers and the reason that line 21-22 exists is that we have to make sure that the robot still pick the beeper(s) at the point which front is not clear too
cs1qa
null
null
null
null
null
Question: For task 2, why do you have both line 18-19 and line 21-22? Code: from cs1robots import * # Your code must work for all world files below. # load_world( "worlds/trash1.wld" ) load_world( "worlds/trash2.wld" ) hubo=Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def uturn(): for i in range(2): turn_right() while hubo.front_is_clear(): while hubo.on_beeper(): hubo.pick_beeper() hubo.move() while hubo.on_beeper(): hubo.pick_beeper() uturn() while hubo.front_is_clear(): hubo.move() turn_right() hubo.move() while hubo.carries_beepers(): hubo.drop_beeper() uturn() hubo.move() hubo.turn_left()
9
2
student
What does valid range mean in is_valid function
from cs1graphics import * import time canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ # 3-2-1. shuffle the card list ################################################################ def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if i%2 == 0: # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### for i in range(len(correct_list)): if correct_list[i]==num1 return False def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### print_cards() if cards[num1][1]==cards[num2][1]: correct_list.append(num1) correct_list.append(num2) return False else: print_cards() return True initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while True: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
59
68
code_understanding
Refers to 0-23
cs1qa
null
null
null
null
null
Question: What does valid range mean in is_valid function Code: from cs1graphics import * import time canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ # 3-2-1. shuffle the card list ################################################################ def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if i%2 == 0: # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### for i in range(len(correct_list)): if correct_list[i]==num1 return False def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### print_cards() if cards[num1][1]==cards[num2][1]: correct_list.append(num1) correct_list.append(num2) return False else: print_cards() return True initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while True: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
4
2
TA
Please explain along with the process which constants of the math module were used in Task3~
import math sin = math.sin pi = math.pi a=int(input('How many steps?: ')) for i in range(a): x = float(i) / 30.0 * 2 * pi print (sin(x))
2
9
code_explain
We only used sin and pi in the math module, of which the constant pi was used to calculate x!
cs1qa
null
null
null
null
null
Question: Please explain along with the process which constants of the math module were used in Task3~ Code: import math sin = math.sin pi = math.pi a=int(input('How many steps?: ')) for i in range(a): x = float(i) / 30.0 * 2 * pi print (sin(x))
1
2
TA
Is there a reason for defining jump_up() and jump_down() separately in stair_up() and stair_down()?
from cs1robots import * load_world("worlds/newspaper.wld") hubo = Robot(beepers=1) hubo.set_trace("blue") def turn_right(): for i in range(3): hubo.turn_left() def jump_up(): hubo.turn_left() hubo.move() turn_right() hubo.move() def stair_up(): for i in range (4): jump_up() hubo.move() def jump_down(): hubo.move() jump_up() def stair_down(): for i in range (4): jump_down() hubo.move() stair_up() hubo.drop_beeper() turn_right() turn_right() hubo.move() stair_down()
9
27
reasoning
I have defined it separately to clearly indicate going up and going down.
cs1qa
null
null
null
null
null
Question: Is there a reason for defining jump_up() and jump_down() separately in stair_up() and stair_down()? Code: from cs1robots import * load_world("worlds/newspaper.wld") hubo = Robot(beepers=1) hubo.set_trace("blue") def turn_right(): for i in range(3): hubo.turn_left() def jump_up(): hubo.turn_left() hubo.move() turn_right() hubo.move() def stair_up(): for i in range (4): jump_up() hubo.move() def jump_down(): hubo.move() jump_up() def stair_down(): for i in range (4): jump_down() hubo.move() stair_up() hubo.drop_beeper() turn_right() turn_right() hubo.move() stair_down()
4
1
TA
In No. 2, a part that applies the float function, such as a = float (a), comes out. Please explain why you need this code!
def is_triangle(a, b, c): if a+b>c and b+c>a and c+a>b: return True else: return False a = input('Side a: ') print('Value of a is', a) a = float (a) b = input('Side b: ') print('Value of b is', b) b = float (b) c = input('Side c: ') print('Value of c is', c) c = float (c) is_triangle(a,b,c) if is_triangle(a,b,c) == True: print("YES") else: print("NO")
7
9
reasoning
Because the value received as an input is a string, you need to convert the value into a float to calculate it as a number!
cs1qa
null
null
null
null
null
Question: In No. 2, a part that applies the float function, such as a = float (a), comes out. Please explain why you need this code! Code: def is_triangle(a, b, c): if a+b>c and b+c>a and c+a>b: return True else: return False a = input('Side a: ') print('Value of a is', a) a = float (a) b = input('Side b: ') print('Value of b is', b) b = float (b) c = input('Side c: ') print('Value of c is', c) c = float (c) is_triangle(a,b,c) if is_triangle(a,b,c) == True: print("YES") else: print("NO")
9
1
TA
What information does an object of class Card in task2 have?
import random from cs1graphics import * img_path = './images/' suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] face_names = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] value = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] bj_board = Canvas(600, 400, 'dark green', 'Black Jack 101') """ Define the Card class """ class Card: def __init__(self,s,f,v,i,h): self.suit=s self.face=f self.value=v self.image=i self.hidden=h def create_deck(number = 1): """ Create a list("deck") of all 52 cards, shuffle them and return the list. The list 'deck' have to include Card objects A Card is represented by a object with four attributes: the face, the suit, value, state, and the image object First, Have to define class 'Card' """ list1=[] for j in range(4): for i in range(13): path=img_path+str(suit_names[j])+'_'+str(face_names[i])+'.png' a=Card(suit_names[j],face_names[i],value[i],path,True) list1.append(a) random.shuffle(list1) return list1 def hand_value(hand): """ hand is a list including card objects Compute the value of the cards in the list "hand" """ summ=0 for i in range(len(hand)): summ=summ+hand[i].value return summ def card_string(card): """ Parameter "card" is a Card object Return a nice string to represent a card (sucn as "a King of Spades" or "an Ace of Diamonds") """ string='' string="a "+str(card.face)+" of "+str(card.suit) return string def ask_yesno(prompt): """ Display the text prompt and let's the user enter a string. If the user enters "y", the function returns "True", and if the user enters "n", the function returns "False". If the user enters anything else, the function prints "I beg your pardon!", and asks again, repreting this until the user has entered a correct string. """ while True: a=input(prompt) if a=='y': return True elif a=='n': return False else: print("I beg your pardon!") def draw_card(dealer,player): """ This funuction add the cards of dealer and player to canvas, bj_board. If the state of each Card object is false, then you have to show the hidden card image(Back.png). The dealer's first card is hidden state. The parameter dealer and player are List objects including Card Objects. The start position of dealer's card is (100,100). The start position of player's card is (100,300). You can use the following methods for positioning images and text: Image() Object, Text() Object, moveTo() method, setDepth() method. You should use help function - help('cs1graphics.Image') -> about Image(), moveTo(), setDepth() help('cs1graphics.Text') -> about Text(),moveTo(), setDepth() """ depth = 100 x0,y0 = 100,100 x1,y1 = 100,300 bj_board.clear() for p in range(len(dealer)): if dealer[p].hidden==True: img=Image(dealer[p].image) img.moveTo(x0+p*20,y0) img.setDepth(depth-p*10) bj_board.add(img) else: img=Image(img_path+'Back.png') img.moveTo(x0+p*20,y0) img.setDepth(depth-p*10) bj_board.add(img) for s in range(len(player)): if player[s].hidden==True: img=Image(player[s].image) img.moveTo(x1+s*20,y1) img.setDepth(depth-s*10) bj_board.add(img) else: img=Image(img_path+'Back.png') img.moveTo(x1+s*20,y1) img.setDepth(depth-s*10) bj_board.add(img) ds=0 yt=0 ds=hand_value(dealer) yt=hand_value(player) d=Text("The dealer's Total:"+str(ds)) d.setFontColor('yellow') y=Text("Your Total:"+str(yt)) y.setFontColor('yellow') d.moveTo(x0+300,y0) y.moveTo(x1+300,y1) bj_board.add(y) if dealer[0].hidden==True: bj_board.add(d) def main(): deck = [] while True: # prompt for starting a new game and create a deck print ("Welcome to Black Jack 101!\n") if len(deck) < 12: deck = create_deck() # create two hands of dealer and player dealer = [] player = [] # initial two dealings card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt a hidden card") card.hidden=False dealer.append(card) card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # player's turn to draw cards while hand_value(player) < 21 and ask_yesno("Would you like another card? (y/n) "): # draw a card for the player card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # if the player's score is over 21, the player loses immediately. if hand_value(player) > 21: print ("You went over 21! You lost.") dealer[0].hidden = True draw_card(dealer,player) else: # draw cards for the dealer while the dealer's score is less than 17 print ("\nThe dealer's hidden card was " + card_string(dealer[0])) while hand_value(dealer) < 17: card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("The dealer's total is", hand_value(dealer)) dealer[0].hidden = True draw_card(dealer,player) # summary player_total = hand_value(player) dealer_total = hand_value(dealer) print ("\nYour total is", player_total) print ("The dealer's total is", dealer_total) if dealer_total > 21: print ("The dealer went over 21! You win!") else: if player_total > dealer_total: print ("You win!") elif player_total < dealer_total: print ("You lost!") else: print ("You have a tie!") if not ask_yesno("\nPlay another round? (y/n) "): bj_board.close() break main()
17
23
variable
Suit, face, value, image file path, front and back information
cs1qa
null
null
null
null
null
Question: What information does an object of class Card in task2 have? Code: import random from cs1graphics import * img_path = './images/' suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] face_names = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] value = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] bj_board = Canvas(600, 400, 'dark green', 'Black Jack 101') """ Define the Card class """ class Card: def __init__(self,s,f,v,i,h): self.suit=s self.face=f self.value=v self.image=i self.hidden=h def create_deck(number = 1): """ Create a list("deck") of all 52 cards, shuffle them and return the list. The list 'deck' have to include Card objects A Card is represented by a object with four attributes: the face, the suit, value, state, and the image object First, Have to define class 'Card' """ list1=[] for j in range(4): for i in range(13): path=img_path+str(suit_names[j])+'_'+str(face_names[i])+'.png' a=Card(suit_names[j],face_names[i],value[i],path,True) list1.append(a) random.shuffle(list1) return list1 def hand_value(hand): """ hand is a list including card objects Compute the value of the cards in the list "hand" """ summ=0 for i in range(len(hand)): summ=summ+hand[i].value return summ def card_string(card): """ Parameter "card" is a Card object Return a nice string to represent a card (sucn as "a King of Spades" or "an Ace of Diamonds") """ string='' string="a "+str(card.face)+" of "+str(card.suit) return string def ask_yesno(prompt): """ Display the text prompt and let's the user enter a string. If the user enters "y", the function returns "True", and if the user enters "n", the function returns "False". If the user enters anything else, the function prints "I beg your pardon!", and asks again, repreting this until the user has entered a correct string. """ while True: a=input(prompt) if a=='y': return True elif a=='n': return False else: print("I beg your pardon!") def draw_card(dealer,player): """ This funuction add the cards of dealer and player to canvas, bj_board. If the state of each Card object is false, then you have to show the hidden card image(Back.png). The dealer's first card is hidden state. The parameter dealer and player are List objects including Card Objects. The start position of dealer's card is (100,100). The start position of player's card is (100,300). You can use the following methods for positioning images and text: Image() Object, Text() Object, moveTo() method, setDepth() method. You should use help function - help('cs1graphics.Image') -> about Image(), moveTo(), setDepth() help('cs1graphics.Text') -> about Text(),moveTo(), setDepth() """ depth = 100 x0,y0 = 100,100 x1,y1 = 100,300 bj_board.clear() for p in range(len(dealer)): if dealer[p].hidden==True: img=Image(dealer[p].image) img.moveTo(x0+p*20,y0) img.setDepth(depth-p*10) bj_board.add(img) else: img=Image(img_path+'Back.png') img.moveTo(x0+p*20,y0) img.setDepth(depth-p*10) bj_board.add(img) for s in range(len(player)): if player[s].hidden==True: img=Image(player[s].image) img.moveTo(x1+s*20,y1) img.setDepth(depth-s*10) bj_board.add(img) else: img=Image(img_path+'Back.png') img.moveTo(x1+s*20,y1) img.setDepth(depth-s*10) bj_board.add(img) ds=0 yt=0 ds=hand_value(dealer) yt=hand_value(player) d=Text("The dealer's Total:"+str(ds)) d.setFontColor('yellow') y=Text("Your Total:"+str(yt)) y.setFontColor('yellow') d.moveTo(x0+300,y0) y.moveTo(x1+300,y1) bj_board.add(y) if dealer[0].hidden==True: bj_board.add(d) def main(): deck = [] while True: # prompt for starting a new game and create a deck print ("Welcome to Black Jack 101!\n") if len(deck) < 12: deck = create_deck() # create two hands of dealer and player dealer = [] player = [] # initial two dealings card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt a hidden card") card.hidden=False dealer.append(card) card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # player's turn to draw cards while hand_value(player) < 21 and ask_yesno("Would you like another card? (y/n) "): # draw a card for the player card = deck.pop() print ("You are dealt " + card_string(card)) player.append(card) print ("Your total is", hand_value(player)) draw_card(dealer,player) # if the player's score is over 21, the player loses immediately. if hand_value(player) > 21: print ("You went over 21! You lost.") dealer[0].hidden = True draw_card(dealer,player) else: # draw cards for the dealer while the dealer's score is less than 17 print ("\nThe dealer's hidden card was " + card_string(dealer[0])) while hand_value(dealer) < 17: card = deck.pop() print ("Dealer is dealt " + card_string(card)) dealer.append(card) print ("The dealer's total is", hand_value(dealer)) dealer[0].hidden = True draw_card(dealer,player) # summary player_total = hand_value(player) dealer_total = hand_value(dealer) print ("\nYour total is", player_total) print ("The dealer's total is", dealer_total) if dealer_total > 21: print ("The dealer went over 21! You win!") else: if player_total > dealer_total: print ("You win!") elif player_total < dealer_total: print ("You lost!") else: print ("You have a tie!") if not ask_yesno("\nPlay another round? (y/n) "): bj_board.close() break main()
1
0
TA
Can you see what the root1 function does?
from cs1robots import * create_world() hubo = Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def root1(): hubo.turn_left() for i in range(9): hubo.move() turn_right() hubo.move() turn_right() for i in range(9): hubo.move() for i in range(4): root1() hubo.turn_left() hubo.move() root1()
10
18
variable
Zigzag up and down repeatedly I made it as a function
cs1qa
null
null
null
null
null
Question: Can you see what the root1 function does? Code: from cs1robots import * create_world() hubo = Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def root1(): hubo.turn_left() for i in range(9): hubo.move() turn_right() hubo.move() turn_right() for i in range(9): hubo.move() for i in range(4): root1() hubo.turn_left() hubo.move() root1()
4
4
TA
Is there any reason you split the range in half?
import math sin = math.sin pi = math.pi for i in range(21) : x = float(i) / 40.0 * 2 * pi character_count_per_line = 3+int((sin(x)+1)*40) output_str = " "* character_count_per_line print (output_str, ".") for i in range(21) : x = float(i) / 40.0 * 2 * pi character_count_per_line =80-int((sin(x)+1)*40) output_str = " "* character_count_per_line print (output_str, ".")
5
17
reasoning
Come to think of it, there was no reason to split it up... sorry
cs1qa
null
null
null
null
null
Question: Is there any reason you split the range in half? Code: import math sin = math.sin pi = math.pi for i in range(21) : x = float(i) / 40.0 * 2 * pi character_count_per_line = 3+int((sin(x)+1)*40) output_str = " "* character_count_per_line print (output_str, ".") for i in range(21) : x = float(i) / 40.0 * 2 * pi character_count_per_line =80-int((sin(x)+1)*40) output_str = " "* character_count_per_line print (output_str, ".")
1
2
TA
At number 3 hubo.move() time.sleep(0.2) hubo.drop_beeper() time.sleep(0.2) hubo.turn_left() time.sleep(0.2) hubo.turn_left() time.sleep(0.2) Can you explain what this part does?
from cs1robots import * load_world('worlds/newspaper.wld') import time hubo=Robot(beepers=1) hubo.set_trace('blue') def turn_right(): for i in range (3): hubo.turn_left() time.sleep(0.2) def go_up_stair(): hubo.turn_left() time.sleep(0.2) hubo.move() time.sleep(0.2) turn_right() hubo.move() time.sleep(0.2) def go_down_stair(): hubo.move() time.sleep(0.2) hubo.turn_left() time.sleep(0.2) hubo.move() time.sleep(0.2) turn_right() for i in range(4): hubo.move() time.sleep(0.2) go_up_stair() hubo.move() time.sleep(0.2) hubo.drop_beeper() time.sleep(0.2) hubo.turn_left() time.sleep(0.2) hubo.turn_left() time.sleep(0.2) for i in range(4): hubo.move() time.sleep(0.2) go_down_stair() hubo.move()
35
42
code_explain
This is the process of the robot turning around after delivering the newspaper. Since it is used only once, no function is specified.
cs1qa
null
null
null
null
null
Question: At number 3 hubo.move() time.sleep(0.2) hubo.drop_beeper() time.sleep(0.2) hubo.turn_left() time.sleep(0.2) hubo.turn_left() time.sleep(0.2) Can you explain what this part does? Code: from cs1robots import * load_world('worlds/newspaper.wld') import time hubo=Robot(beepers=1) hubo.set_trace('blue') def turn_right(): for i in range (3): hubo.turn_left() time.sleep(0.2) def go_up_stair(): hubo.turn_left() time.sleep(0.2) hubo.move() time.sleep(0.2) turn_right() hubo.move() time.sleep(0.2) def go_down_stair(): hubo.move() time.sleep(0.2) hubo.turn_left() time.sleep(0.2) hubo.move() time.sleep(0.2) turn_right() for i in range(4): hubo.move() time.sleep(0.2) go_up_stair() hubo.move() time.sleep(0.2) hubo.drop_beeper() time.sleep(0.2) hubo.turn_left() time.sleep(0.2) hubo.turn_left() time.sleep(0.2) for i in range(4): hubo.move() time.sleep(0.2) go_down_stair() hubo.move()
6
2
student
But what is 3-2-2 next to # on line 45??
from cs1graphics import * import time canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ # 3-2-1. shuffle the card list ################################################################ def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if i%2 == 0: # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### return False def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### print_cards() return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while True: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
44
44
code_understanding
It is a story to fix the condition of the string It's just a comment
cs1qa
null
null
null
null
null
Question: But what is 3-2-2 next to # on line 45?? Code: from cs1graphics import * import time canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ # 3-2-1. shuffle the card list ################################################################ def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if i%2 == 0: # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### return False def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### print_cards() return False initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while True: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
3
3
TA
Please explain how you wrote the code for the protruding part in the middle of the rain2 world!
from cs1robots import * # Your code must work for both of the worlds below. # load_world('worlds/rain1.wld') load_world('worlds/rain2.wld') # Initialize your robot at the door of the house. my_robot = Robot(beepers=100, avenue=2, street=6, orientation='E') my_robot.set_trace("blue") def turn_right(): for i in range(3): my_robot.turn_left() def change_direction(): if not my_robot.front_is_clear(): if my_robot.right_is_clear(): turn_right() elif my_robot.left_is_clear(): my_robot.turn_left() def move_or_close_window(): my_robot.move() if my_robot.right_is_clear and my_robot.left_is_clear(): my_robot.drop_beeper() my_robot.move() my_robot.turn_left() my_robot.move() my_robot.move() change_direction() while my_robot.front_is_clear(): move_or_close_window() change_direction() while my_robot.front_is_clear(): move_or_close_window() change_direction() move_or_close_window() move_or_close_window() if not my_robot.front_is_clear(): turn_right() my_robot.move() my_robot.turn_left() my_robot.move() while my_robot.front_is_clear(): move_or_close_window() change_direction() my_robot.move() my_robot.move() my_robot.turn_left() # Now close all the windows in the house!
38
42
code_explain
If there is a protruding part in the middle, the cord is squeezed so that only that part is properly passed.
cs1qa
null
null
null
null
null
Question: Please explain how you wrote the code for the protruding part in the middle of the rain2 world! Code: from cs1robots import * # Your code must work for both of the worlds below. # load_world('worlds/rain1.wld') load_world('worlds/rain2.wld') # Initialize your robot at the door of the house. my_robot = Robot(beepers=100, avenue=2, street=6, orientation='E') my_robot.set_trace("blue") def turn_right(): for i in range(3): my_robot.turn_left() def change_direction(): if not my_robot.front_is_clear(): if my_robot.right_is_clear(): turn_right() elif my_robot.left_is_clear(): my_robot.turn_left() def move_or_close_window(): my_robot.move() if my_robot.right_is_clear and my_robot.left_is_clear(): my_robot.drop_beeper() my_robot.move() my_robot.turn_left() my_robot.move() my_robot.move() change_direction() while my_robot.front_is_clear(): move_or_close_window() change_direction() while my_robot.front_is_clear(): move_or_close_window() change_direction() move_or_close_window() move_or_close_window() if not my_robot.front_is_clear(): turn_right() my_robot.move() my_robot.turn_left() my_robot.move() while my_robot.front_is_clear(): move_or_close_window() change_direction() my_robot.move() my_robot.move() my_robot.turn_left() # Now close all the windows in the house!
5
0
TA
What method did you use to change the balance amount in the deposit and withdrawal functions?
balance = 0 def deposit(money) : # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# # Do something on here ! global balance balance = money + balance print("You deposited",money,"won") pass ################# def withdrawal(money) : # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance ################# ### implement ### ################# # Do something on here ! global balance if money > balance: print("You've withdrwan",money,"won") print("But you only have",balance,"won") else: balance = balance - money print("You've withdrawn",money,"won") pass ################# def bank() : # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. ################# ### implement ### ################# # Do something on here ! if process == '': return None elif process == 'd': money = int(input("How much do you want to deposit? ")) deposit(money) elif process == 'w': money = int(input("How much do you want to withdraw ")) withdrawal(money) elif process == 'c': print("Your current balance is",balance,"won") else: print("Please, press d or w or c or return") pass ################# bank()
0
35
code_explain
We used global to change the value of the global variable balance in a function, and add or take away the balance according to the function by setting the parameter money in each function.
cs1qa
null
null
null
null
null
Question: What method did you use to change the balance amount in the deposit and withdrawal functions? Code: balance = 0 def deposit(money) : # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# # Do something on here ! global balance balance = money + balance print("You deposited",money,"won") pass ################# def withdrawal(money) : # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance ################# ### implement ### ################# # Do something on here ! global balance if money > balance: print("You've withdrwan",money,"won") print("But you only have",balance,"won") else: balance = balance - money print("You've withdrawn",money,"won") pass ################# def bank() : # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. ################# ### implement ### ################# # Do something on here ! if process == '': return None elif process == 'd': money = int(input("How much do you want to deposit? ")) deposit(money) elif process == 'w': money = int(input("How much do you want to withdraw ")) withdrawal(money) elif process == 'c': print("Your current balance is",balance,"won") else: print("Please, press d or w or c or return") pass ################# bank()
2
0
TA
Please explain what the flag is for Tasks 1 and 2.
from cs1robots import * load_world('worlds/harvest3.wld') def move(n=1): for i in range(n): h.move() def left(): h.turn_left() def right(): for i in range(3): left() h = Robot(beepers=36) h.set_trace('blue') move() def oneStep(): if h.on_beeper(): h.pick_beeper() move() def oneLine(flag): for i in range(5): oneStep() if h.on_beeper(): h.pick_beeper() if flag % 2 == 0: left() move() left() else: right() move() right() for i in range(6): oneLine(i)
20
32
variable
Yes, in 1,2, the flag is a variable indicating whether the current line is an even number or an odd number, and is used to determine whether the current line ends and rotates left or right.
cs1qa
null
null
null
null
null
Question: Please explain what the flag is for Tasks 1 and 2. Code: from cs1robots import * load_world('worlds/harvest3.wld') def move(n=1): for i in range(n): h.move() def left(): h.turn_left() def right(): for i in range(3): left() h = Robot(beepers=36) h.set_trace('blue') move() def oneStep(): if h.on_beeper(): h.pick_beeper() move() def oneLine(flag): for i in range(5): oneStep() if h.on_beeper(): h.pick_beeper() if flag % 2 == 0: left() move() left() else: right() move() right() for i in range(6): oneLine(i)
5
1
TA
I set variables such as car and canvas to global. Is there any reason?
from cs1graphics import * from time import sleep canvas = Canvas(600,200) canvas.setBackgroundColor("light blue") car = Layer() gas = Circle(1) gas.setFillColor("white") gas.moveTo(45,135) canvas.add(gas) def draw_animal(): # Implement this function. global car global canvas tire1 = Circle(10, Point(-20,-10)) tire1.setFillColor("black") car.add(tire1) tire2 = Circle(10, Point(20,-10)) tire2.setFillColor("black") car.add(tire2) body = Rectangle(70, 30, Point(0,-25)) body.setFillColor("blue") body.setDepth(60) car.add(body) pipe = Rectangle(10,10, Point(-40,-15)) pipe.setFillColor("gray") car.add(pipe) car.moveTo(100, 150) canvas.add(car) def show_animation(): # Implement this function. global car global gas for i in range(200): car.move(2,0) gas.setRadius(1+i%10) gas.move(2,0) sleep(0.01) draw_animal() show_animation()
34
35
reasoning
Isn't it necessary to use global to get and use a global variable in a function? Is it not necessary to modify the variable value?
cs1qa
null
null
null
null
null
Question: I set variables such as car and canvas to global. Is there any reason? Code: from cs1graphics import * from time import sleep canvas = Canvas(600,200) canvas.setBackgroundColor("light blue") car = Layer() gas = Circle(1) gas.setFillColor("white") gas.moveTo(45,135) canvas.add(gas) def draw_animal(): # Implement this function. global car global canvas tire1 = Circle(10, Point(-20,-10)) tire1.setFillColor("black") car.add(tire1) tire2 = Circle(10, Point(20,-10)) tire2.setFillColor("black") car.add(tire2) body = Rectangle(70, 30, Point(0,-25)) body.setFillColor("blue") body.setDepth(60) car.add(body) pipe = Rectangle(10,10, Point(-40,-15)) pipe.setFillColor("gray") car.add(pipe) car.moveTo(100, 150) canvas.add(car) def show_animation(): # Implement this function. global car global gas for i in range(200): car.move(2,0) gas.setRadius(1+i%10) gas.move(2,0) sleep(0.01) draw_animal() show_animation()
2
0
TA
Please briefly explain how to pick up the beeper in step 1 along with the function name!
from cs1robots import * load_world("worlds/harvest3.wld") hubo = Robot() hubo.set_trace('blue') hubo.move() def turn_right(): for i in range(3): hubo.turn_left() def goStraight(): for i in range(5): if hubo.on_beeper(): hubo.pick_beeper() hubo.move() def turnAroundLeft(): if hubo.on_beeper(): hubo.pick_beeper() hubo.turn_left() hubo.move() if hubo.on_beeper(): hubo.pick_beeper() hubo.turn_left() def turnAroundRight(): if hubo.on_beeper(): hubo.pick_beeper() turn_right() hubo.move() if hubo.on_beeper(): hubo.pick_beeper() turn_right() for i in range(6): goStraight() if i == 5: pass elif i%2 == 0: turnAroundLeft() else: turnAroundRight()
11
33
code_explain
First, in the straight section, the goStraight() function was used to pick up the beeper, and turnAroundRight() and turnAroundLeft() were used when turning to the right and turning to the left, respectively.
cs1qa
null
null
null
null
null
Question: Please briefly explain how to pick up the beeper in step 1 along with the function name! Code: from cs1robots import * load_world("worlds/harvest3.wld") hubo = Robot() hubo.set_trace('blue') hubo.move() def turn_right(): for i in range(3): hubo.turn_left() def goStraight(): for i in range(5): if hubo.on_beeper(): hubo.pick_beeper() hubo.move() def turnAroundLeft(): if hubo.on_beeper(): hubo.pick_beeper() hubo.turn_left() hubo.move() if hubo.on_beeper(): hubo.pick_beeper() hubo.turn_left() def turnAroundRight(): if hubo.on_beeper(): hubo.pick_beeper() turn_right() hubo.move() if hubo.on_beeper(): hubo.pick_beeper() turn_right() for i in range(6): goStraight() if i == 5: pass elif i%2 == 0: turnAroundLeft() else: turnAroundRight()
9
0
TA
Why is the while statement termination condition if n==25:?
# Copy your "Memento" code from the task in Lab 6. from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 class Card(object): """ Memento""" pass def initialize(): for i in range(6): for k in range(4): card=Card() img = Image(path+names[i]) card.img=img card.name=names[i] card.state=True cards.append(card) random.shuffle(cards) n=0 for card in cards: card.num_pads_rect=Rectangle(90, 120, Point(0, 0)) card.num_pads_text=Text(str(n), 18, Point(0, 0)) n=n+1 def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for card in cards: if card.state==True: card.img.moveTo(i_w + w, i_h+h) canvas.add(card.img) else: card.num_pads_text.moveTo(i_w + w, i_h+h) card.num_pads_rect.moveTo(i_w + w, i_h+h) canvas.add(card.num_pads_rect) canvas.add(card.num_pads_text) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): if num1<0 or num1>23: return False elif num2<0 or num1>23: return False elif cards[num1].state==True: return False elif cards[num2].state==True: return False else: return True def check(num1, num2): if cards[num1].name==cards[num2].name: cards[num1].state=True cards[num2].state=True print_cards() return True else: cards[num1].state=True cards[num2].state=True print_cards() cards[num1].state=False cards[num2].state=False print_cards() return False initialize() for i in range(24): cards[i].state=True print_cards() for i in range(24): cards[i].state=False print_cards() print("### Welcome to the Python Memento game!!! ###") n=0 while True: if n==25: break if tries%10==1: print(str(tries) + "st try. You got " + str(n//2) + " pairs.") elif tries%10==2: print(str(tries) + "nd try. You got " + str(n//2) + " pairs.") elif tries%10==3: print(str(tries) + "rd try. You got " + str(n//2) + " pairs.") else: print(str(tries) + "th try. You got " + str(n//2) + " pairs.") num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") n=n+2 else: print("Wrong!") tries=tries+1
100
124
reasoning
When n is the number of cards with state=True, when n becomes 25, it means that all 24 cards are turned upside down.
cs1qa
null
null
null
null
null
Question: Why is the while statement termination condition if n==25:? Code: # Copy your "Memento" code from the task in Lab 6. from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 class Card(object): """ Memento""" pass def initialize(): for i in range(6): for k in range(4): card=Card() img = Image(path+names[i]) card.img=img card.name=names[i] card.state=True cards.append(card) random.shuffle(cards) n=0 for card in cards: card.num_pads_rect=Rectangle(90, 120, Point(0, 0)) card.num_pads_text=Text(str(n), 18, Point(0, 0)) n=n+1 def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for card in cards: if card.state==True: card.img.moveTo(i_w + w, i_h+h) canvas.add(card.img) else: card.num_pads_text.moveTo(i_w + w, i_h+h) card.num_pads_rect.moveTo(i_w + w, i_h+h) canvas.add(card.num_pads_rect) canvas.add(card.num_pads_text) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) def is_valid(num1, num2): if num1<0 or num1>23: return False elif num2<0 or num1>23: return False elif cards[num1].state==True: return False elif cards[num2].state==True: return False else: return True def check(num1, num2): if cards[num1].name==cards[num2].name: cards[num1].state=True cards[num2].state=True print_cards() return True else: cards[num1].state=True cards[num2].state=True print_cards() cards[num1].state=False cards[num2].state=False print_cards() return False initialize() for i in range(24): cards[i].state=True print_cards() for i in range(24): cards[i].state=False print_cards() print("### Welcome to the Python Memento game!!! ###") n=0 while True: if n==25: break if tries%10==1: print(str(tries) + "st try. You got " + str(n//2) + " pairs.") elif tries%10==2: print(str(tries) + "nd try. You got " + str(n//2) + " pairs.") elif tries%10==3: print(str(tries) + "rd try. You got " + str(n//2) + " pairs.") else: print(str(tries) + "th try. You got " + str(n//2) + " pairs.") num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") n=n+2 else: print("Wrong!") tries=tries+1
3
1
TA
Please tell me about the function and role of the plant() function.
from cs1robots import * load_world('worlds/harvest3.wld') hubo = Robot(beepers=100) hubo.set_trace("blue") def turn_right(): for i in range(3): hubo.turn_left() def plant_beeper(): # If hubo is not on beeper, plant a beeper if not hubo.on_beeper(): hubo.drop_beeper() # Scans 2 floors(rows) which have {num} columns and if there is no beeper, then plant it def scan_two_floor(num): for k in range(num - 1): plant_beeper() hubo.move() plant_beeper() hubo.turn_left() if hubo.front_is_clear(): hubo.move() hubo.turn_left() for k in range(num - 1): plant_beeper() hubo.move() plant_beeper() # Input the number of row and column of check area,{row},{col} each def plant(row, col): itr = int(row / 2) for k in range(itr): scan_two_floor(col) if k != itr -1: turn_right() hubo.move() turn_right() if row % 2 == 1: # If number of the row is odd turn_right() hubo.move() turn_right() for k in range(col - 1): plant_beeper() hubo.move() plant_beeper() hubo.move() plant(6,6)
29
44
variable
This is the code that checks if there is no beeper where the robot is located, and if not
cs1qa
null
null
null
null
null
Question: Please tell me about the function and role of the plant() function. Code: from cs1robots import * load_world('worlds/harvest3.wld') hubo = Robot(beepers=100) hubo.set_trace("blue") def turn_right(): for i in range(3): hubo.turn_left() def plant_beeper(): # If hubo is not on beeper, plant a beeper if not hubo.on_beeper(): hubo.drop_beeper() # Scans 2 floors(rows) which have {num} columns and if there is no beeper, then plant it def scan_two_floor(num): for k in range(num - 1): plant_beeper() hubo.move() plant_beeper() hubo.turn_left() if hubo.front_is_clear(): hubo.move() hubo.turn_left() for k in range(num - 1): plant_beeper() hubo.move() plant_beeper() # Input the number of row and column of check area,{row},{col} each def plant(row, col): itr = int(row / 2) for k in range(itr): scan_two_floor(col) if k != itr -1: turn_right() hubo.move() turn_right() if row % 2 == 1: # If number of the row is odd turn_right() hubo.move() turn_right() for k in range(col - 1): plant_beeper() hubo.move() plant_beeper() hubo.move() plant(6,6)
4
2
TA
What could be the reason?
import math sin = math.sin pi = math.pi n=int(input('How many steps? ')) for i in range(n): x = float(i) / (n-1) * 2 * pi print (sin(x))
5
5
reasoning
This is because the input state is not an integer, but a string, so in order to use a loop and calculate using the received value, it must be converted to an int.
cs1qa
null
null
null
null
null
Question: What could be the reason? Code: import math sin = math.sin pi = math.pi n=int(input('How many steps? ')) for i in range(n): x = float(i) / (n-1) * 2 * pi print (sin(x))
1
3
TA
What is the role of the harvest_1() function in Task4?
from cs1robots import * load_world('worlds/harvest1.wld') hubo = Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def U_turn_left(): hubo.turn_left() hubo.move() hubo.turn_left() def U_turn_right(): turn_right() hubo.move() turn_right() def harvest_1(): if hubo.front_is_clear(): hubo.move() hubo.pick_beeper() else: U_turn_left() def harvest_2(): if hubo.front_is_clear(): hubo.pick_beeper() hubo.move() else: U_turn_right() def harvest_two_line(): for i in range(7): harvest_1() for i in range(7): harvest_2() for i in range(3): harvest_two_line()
18
23
variable
harvest_1 is a function of picking up the beeper of the odd line on the y-axis and then going up to the even line if there is a wall!
cs1qa
null
null
null
null
null
Question: What is the role of the harvest_1() function in Task4? Code: from cs1robots import * load_world('worlds/harvest1.wld') hubo = Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def U_turn_left(): hubo.turn_left() hubo.move() hubo.turn_left() def U_turn_right(): turn_right() hubo.move() turn_right() def harvest_1(): if hubo.front_is_clear(): hubo.move() hubo.pick_beeper() else: U_turn_left() def harvest_2(): if hubo.front_is_clear(): hubo.pick_beeper() hubo.move() else: U_turn_right() def harvest_two_line(): for i in range(7): harvest_1() for i in range(7): harvest_2() for i in range(3): harvest_two_line()
4
3
TA
Why do you add 40 to the end of line 9 in the 4th task?
import math sin = math.sin pi = math.pi cos = math.cos for i in range(41) : x = float(i) / 40.0 * 2 * pi character_count_per_line = math.sin(x)+40*sin(x)+40# Change this line to print out sine curve correctly. output_str = '#' * int(character_count_per_line) print (output_str)
8
8
reasoning
I decided on the function, but I used trial and error a bit, but the first line was 40 #s.
cs1qa
null
null
null
null
null
Question: Why do you add 40 to the end of line 9 in the 4th task? Code: import math sin = math.sin pi = math.pi cos = math.cos for i in range(41) : x = float(i) / 40.0 * 2 * pi character_count_per_line = math.sin(x)+40*sin(x)+40# Change this line to print out sine curve correctly. output_str = '#' * int(character_count_per_line) print (output_str)
5
0
TA
How did you use the balance variable in Task1?
balance = 0 def deposit(money) : global balance balance = balance + money print("You deposited "+str(money)+" won") def withdrawal(money) : global balance if money > balance : print("You've withdrawn "+str(money)+" won") print("But you only have "+str(balance)+" won") else : balance = balance - money print("You've withdraw "+str(money)+" won") def bank() : global balance while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") if process == 'd' : dmoney = int(input("How much do you want to deposit?")) deposit(dmoney) elif process == 'w' : wmoney = int(input("How much do you want to withdraw?")) withdrawal(wmoney) elif process == 'c' : print("Your current balance is "+str(balance)+" won") elif process == '' : break else : print("Please, press d or w or c or return") bank()
0
14
variable
The balance variable is made available to all functions by using global to use in the newly defined function, and it means the total money in the bank.
cs1qa
null
null
null
null
null
Question: How did you use the balance variable in Task1? Code: balance = 0 def deposit(money) : global balance balance = balance + money print("You deposited "+str(money)+" won") def withdrawal(money) : global balance if money > balance : print("You've withdrawn "+str(money)+" won") print("But you only have "+str(balance)+" won") else : balance = balance - money print("You've withdraw "+str(money)+" won") def bank() : global balance while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") if process == 'd' : dmoney = int(input("How much do you want to deposit?")) deposit(dmoney) elif process == 'w' : wmoney = int(input("How much do you want to withdraw?")) withdrawal(wmoney) elif process == 'c' : print("Your current balance is "+str(balance)+" won") elif process == '' : break else : print("Please, press d or w or c or return") bank()
8
1
TA
At the end, entering the country code and outputting the country name Could you briefly explain how it was made?
import csv f = open('average-latitude-longitude-countries.csv','r') li1 = [] li2 = [] li3 = [] li4 = [] while True: line = f.readline() if not line: break line = line.strip('\n') li = [1,1,1,1] li[0] = line.split(',')[0] a = line.split(',')[-1] li[-1] = a.strip('"') b = line.split(',')[-2] li[-2] = b.strip('"') if len(line.split(',')) == 4: li[1] = line.split(',')[1] else: li[1] = line.split(',')[1] + line.split(',')[2] li1.append((li[0].strip('"'),li[1].strip('"'))) li2.append((li[0].strip('"'),(li[2],li[3]))) li3.append((li[1],(li[2],li[3]))) f.close() li1.pop(0) li2.pop(0) li3.pop(0) li4 = [] a = 0 for i in range(len(li3)): c = (li3[i][0],(float(li3[i][1][0]),float(li3[i][1][1]))) li4.append(c) print(li1) print(li2) print(li4) for i in range(len(li4)): if float(li4[i][1][0]) < 0: print(li4[i][0].strip('"')) con = input("Enter country code: ") for i in range(len(li1)): if con == li1[i][0]: print(li1[i][1]) a += 1 if a == 0: print ('not exist')
41
47
code_explain
After receiving the country code through input, the country code is output if the code is in the country code part of the list consisting of country code and country name
cs1qa
null
null
null
null
null
Question: At the end, entering the country code and outputting the country name Could you briefly explain how it was made? Code: import csv f = open('average-latitude-longitude-countries.csv','r') li1 = [] li2 = [] li3 = [] li4 = [] while True: line = f.readline() if not line: break line = line.strip('\n') li = [1,1,1,1] li[0] = line.split(',')[0] a = line.split(',')[-1] li[-1] = a.strip('"') b = line.split(',')[-2] li[-2] = b.strip('"') if len(line.split(',')) == 4: li[1] = line.split(',')[1] else: li[1] = line.split(',')[1] + line.split(',')[2] li1.append((li[0].strip('"'),li[1].strip('"'))) li2.append((li[0].strip('"'),(li[2],li[3]))) li3.append((li[1],(li[2],li[3]))) f.close() li1.pop(0) li2.pop(0) li3.pop(0) li4 = [] a = 0 for i in range(len(li3)): c = (li3[i][0],(float(li3[i][1][0]),float(li3[i][1][1]))) li4.append(c) print(li1) print(li2) print(li4) for i in range(len(li4)): if float(li4[i][1][0]) < 0: print(li4[i][0].strip('"')) con = input("Enter country code: ") for i in range(len(li1)): if con == li1[i][0]: print(li1[i][1]) a += 1 if a == 0: print ('not exist')
2
0
TA
Is there any reason why you didn't put the two for statements at the bottom of Task1 in the for statement at the top?
from cs1robots import * load_world("worlds/harvest3.wld") hubo=Robot() hubo.set_trace("red") def turn_right(): for i in range(3): hubo.turn_left() def beeper_pick(): while hubo.on_beeper(): hubo.pick_beeper() hubo.move() for j in range(2): for i in range(5): beeper_pick() hubo.move() beeper_pick() hubo.turn_left() hubo.move() beeper_pick() hubo.turn_left() for i in range(5): beeper_pick() hubo.move() beeper_pick() turn_right() hubo.move() turn_right() for i in range(5): beeper_pick() hubo.move() beeper_pick() hubo.turn_left() hubo.move() beeper_pick() hubo.turn_left() for i in range(5): beeper_pick() hubo.move()
16
43
reasoning
At the very end, I didn't have to do the work of going up.
cs1qa
null
null
null
null
null
Question: Is there any reason why you didn't put the two for statements at the bottom of Task1 in the for statement at the top? Code: from cs1robots import * load_world("worlds/harvest3.wld") hubo=Robot() hubo.set_trace("red") def turn_right(): for i in range(3): hubo.turn_left() def beeper_pick(): while hubo.on_beeper(): hubo.pick_beeper() hubo.move() for j in range(2): for i in range(5): beeper_pick() hubo.move() beeper_pick() hubo.turn_left() hubo.move() beeper_pick() hubo.turn_left() for i in range(5): beeper_pick() hubo.move() beeper_pick() turn_right() hubo.move() turn_right() for i in range(5): beeper_pick() hubo.move() beeper_pick() hubo.turn_left() hubo.move() beeper_pick() hubo.turn_left() for i in range(5): beeper_pick() hubo.move()
6
2
TA
What is the case for num1 and num2 that return False when is_valid in Task 3?
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) rect.setFillColor("white") text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ # 3-2-1. shuffle the card list ################################################################ random.shuffle(cards) def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ count = correct_list.count(i) if (count==0) : # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): cards[i][0].moveTo(i_w + w, i_h+h) canvas.remove(cards[i][0]) num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### num1yes = correct_list.count(num1) num2yes = correct_list.count(num2) if (num1yes!=0 or num2yes!=0): return False elif (num1>24 or num2>24 or num1<0 or num2<0): return False elif (num1==num2): return False else: return True def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): if i==num1: cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) num_pads[i].moveTo(i_w + w, i_h+h) canvas.remove(num_pads[i]) elif i==num2: cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) num_pads[i].moveTo(i_w + w, i_h+h) canvas.remove(num_pads[i]) #break w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) if (cards[num1][1] == cards[num2][1]): correct_list.append(num1) correct_list.append(num2) return True else: w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if (i==num1 or i ==num2) : # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.remove(cards[i][0]) num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 return False #-------------------------------------------------------------------------------------- initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while len(correct_list)!=24: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") tries = tries+1 ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
81
99
variable
If it already exists in correct_list, if num1 and num2 are the same, returns False if it is not an integer from 0 to 23.
cs1qa
null
null
null
null
null
Question: What is the case for num1 and num2 that return False when is_valid in Task 3? Code: from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards for i in range(6): for k in range(4): img = Image(path+names[i]) temp_tuple = (img, names[i]) cards.append(temp_tuple) for i in range(24): card = Layer() rect = Rectangle(90, 120, Point(0, 0)) rect.setFillColor("white") text = Text(str(i), 18, Point(0, 0)) card.add(rect) card.add(text) num_pads.append(card) ################################################################ # 3-2-1. shuffle the card list ################################################################ random.shuffle(cards) def print_cards(): canvas.clear() w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ count = correct_list.count(i) if (count==0) : # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) else: num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): cards[i][0].moveTo(i_w + w, i_h+h) canvas.remove(cards[i][0]) num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 def is_valid(num1, num2): ########################################################################### # 3-1-1. Check if any of two numbers exists in the current correct list, # two numbers are the same, # or both of the numbers are within a valid range. # Return Boolean value according to the result. ########################################################################### num1yes = correct_list.count(num1) num2yes = correct_list.count(num2) if (num1yes!=0 or num2yes!=0): return False elif (num1>24 or num2>24 or num1<0 or num2<0): return False elif (num1==num2): return False else: return True def check(num1, num2): ########################################################################### # 3-1-2. At first, visualize the screen including the two cards # (num1-th card and num2-th card). # If two pictures of the two cards are same, # put two numbers into the correct list. # If not, re-visualize the original screen. # Return Boolean value according to the result. ########################################################################### w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): if i==num1: cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) num_pads[i].moveTo(i_w + w, i_h+h) canvas.remove(num_pads[i]) elif i==num2: cards[i][0].moveTo(i_w + w, i_h+h) canvas.add(cards[i][0]) num_pads[i].moveTo(i_w + w, i_h+h) canvas.remove(num_pads[i]) #break w += 100 if w % 600 == 0: w = 0 h += 130 time.sleep(1) if (cards[num1][1] == cards[num2][1]): correct_list.append(num1) correct_list.append(num2) return True else: w = 0 h = 0 i_w = 70 i_h = 90 for i in range(len(num_pads)): ################################################################ if (i==num1 or i ==num2) : # 3-2-2. rewrite the condition for visualization. ################################################################ cards[i][0].moveTo(i_w + w, i_h+h) canvas.remove(cards[i][0]) num_pads[i].moveTo(i_w + w, i_h+h) canvas.add(num_pads[i]) w += 100 if w % 600 == 0: w = 0 h += 130 return False #-------------------------------------------------------------------------------------- initialize() print_cards() print("### Welcome to the Python Memento game!!! ###") ############################################################################### while len(correct_list)!=24: # 3-2-3. Rewrite the condition for termination ############################################################################### ########################################################################### # 3-2-4. Print the number of tries and the corrected pairs print(str(tries) + "th try. You got " + str(len(correct_list)//2) + " pairs.") ########################################################################### num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) if not is_valid(num1, num2): continue if check(num1, num2): print("Correct!") else: print("Wrong!") tries = tries+1 ########################################################################### # 3-2-5. Update number of tries (global variable, tries) ###########################################################################
10
0
student
If you look at the animation execution code of Mario Code right now, there is no for statement. Can you still give a slow moving effect?
from cs1graphics import * from time import sleep _scene = None _world = None t = 0.2 def create_world(): global _scene, _world if _scene: raise RuntimeError("A world already exists!") _world = _World(500, 300) _scene = Canvas(_world.width, _world.height) _scene.setTitle("Mario World") _world.draw_scene() class _World(object): def __init__(self, width, height): self.width = width self.height = height def draw_scene(self): """ draw background here Don't forget _scene.add(name) """ grass = Rectangle(1000, 150, Point(250, 250)) grass.setFillColor('green') grass.setDepth(100) _scene.add(grass) #blocks block = Rectangle(40, 40, Point(200, 100)) block.setFillColor('brown') qmark = Text("?", 20, Point(200, 100)) qmark.setFontColor('Yellow') qmark.setDepth(48) _scene.add(qmark) block2 = block.clone() block2.move(40, 0) block.setDepth(50) _scene.add(block) _scene.add(block2) #pipe pipe = Polygon(Point(400, 150), Point(400, 160), Point(410, 160), Point(410, 320), Point(470, 320), Point(470, 160), Point(480, 160), Point(480, 150)) pipe.setFillColor('lightgreen') pipe.setDepth(10) pipe.move(-10, 0) _scene.add(pipe) class Mushroom(object): def __init__(self, x=200, y=92): mushroom = Layer() uppermush = Ellipse(38, 18, Point(x, y)) uppermush.setFillColor('red') uppermush.setDepth(52) lowermush = Ellipse(35, 25, Point(x, y+8)) lowermush.setFillColor('beige') lowermush.setDepth(53) mushroom.add(lowermush) mushroom.add(uppermush) mushroom.setDepth(52) self.layer = mushroom _scene.add(self.layer) def diappear(self): self.layer.scale(0.001) def move(self, x, y): self.layer.move(x, y) def arise(self): self.layer.setDepth(45) self.layer.move(0, -20) COLOR = ['Red', 'Blue'] TYPE = ['super', 'normal'] class Mario(object): def __init__(self, color='Blue', type='normal'): assert type in TYPE and color in COLOR self.color = color self.type = type self.step_size = 3 # Constructing Mario mario = Layer() # body body = Rectangle(33, 22, Point(200, 200)) body.setFillColor(color) body.setDepth(50) mario.add(body) # face face = Ellipse(30, 20, Point(200, 180)) face.setFillColor('beige') face.setDepth(40) mario.add(face) #hat hat = Polygon(Point(185, 175), Point(220, 175), Point(220, 173), Point(215, 173), Point(212, 168), Point(188, 168)) hat.setFillColor(color) hat.setDepth(39) mario.add(hat) #beard beard = Polygon(Point(207, 183), Point(217, 183), Point(215, 180), Point(209, 180)) beard.setFillColor('Brown') beard.setDepth(38) mario.add(beard) shoe = Layer() #left shoe lshoe = Rectangle(15, 6, Point(191, 215)) lshoe.setFillColor('black') lshoe.setDepth(52) shoe.add(lshoe) #right shoe rshoe = lshoe.clone() rshoe.move(17, 0) shoe.add(rshoe) mario.add(shoe) # save alias of moveable parts self.layer = mario self.body = body self.hat = hat self.shoe = shoe _scene.add(self.layer) self.moving_part_count = 0 if type == 'super': self.supermario() def shoe_move(self): if self.moving_part_count % 3 == 0: self.shoe.move(3, 0) elif self.moving_part_count % 3 == 1: self.shoe.move(-5,0) else: self.shoe.move(2,0) self.moving_part_count += 1 if self.moving_part_count % 3 == 0: self.moving_part_count = 0 def move(self,x=10,y=0): self.layer.move(x,y) def supermario(self): tempPt = self.body.getReferencePoint() self.layer.adjustReference(tempPt.getX(), tempPt.getY()) for i in range(3): self.layer.scale(1.3) sleep(t/2) self.layer.scale(0.9) sleep(t/2) def walk(self,x=20): assert x > 0 total_step = int(x / self.step_size) for i in range(total_step): sleep(t/4) self.move(self.step_size, 0) self.shoe_move() def show_animation(): sleep(t) mario.move(0, -50) mushroom.arise() sleep(t) mario.move(0, 50) mushroom.move(0, 8) for i in range(7): sleep(t/2) mushroom.move(10, 0) mario.move(10, 0) mario.shoe_move() sleep(t/2) mario.shoe_move() sleep(t/2) mushroom.move(0, 50) mario.move(10, 0) mario.shoe_move() sleep(t/2) mario.shoe_move() sleep(t) mushroom.move(0, 50) sleep(t/2) mushroom.diappear() sleep(t/2) mario.supermario() for i in range(6): sleep(t/2) mario.move(10, 0) mario.shoe_move() sleep(t/2) mario.shoe_move() for i in range(2): sleep(t) mario.move(28, -60) for i in range(1): sleep(t) mario.move(32, 40) sleep(2*t) for i in range(4): sleep(t) mario.move(0, 25) def interactive_example(): while True: e = _scene.wait() d = e.getDescription() if d == "keyboard": k = e.getKey() if k == "q": _scene.close() break elif k == "w": mario.walk(20) elif k == "r": mario.walk(40) elif k == "j": mario.move(0, -50) sleep(t) mario.move(0, 50) create_world() mario = Mario('Blue', 'normal') mushroom = Mushroom(200, 92) show_animation() # interactive_example()
155
156
code_understanding
mario's move is a function that only moves once
cs1qa
null
null
null
null
null
Question: If you look at the animation execution code of Mario Code right now, there is no for statement. Can you still give a slow moving effect? Code: from cs1graphics import * from time import sleep _scene = None _world = None t = 0.2 def create_world(): global _scene, _world if _scene: raise RuntimeError("A world already exists!") _world = _World(500, 300) _scene = Canvas(_world.width, _world.height) _scene.setTitle("Mario World") _world.draw_scene() class _World(object): def __init__(self, width, height): self.width = width self.height = height def draw_scene(self): """ draw background here Don't forget _scene.add(name) """ grass = Rectangle(1000, 150, Point(250, 250)) grass.setFillColor('green') grass.setDepth(100) _scene.add(grass) #blocks block = Rectangle(40, 40, Point(200, 100)) block.setFillColor('brown') qmark = Text("?", 20, Point(200, 100)) qmark.setFontColor('Yellow') qmark.setDepth(48) _scene.add(qmark) block2 = block.clone() block2.move(40, 0) block.setDepth(50) _scene.add(block) _scene.add(block2) #pipe pipe = Polygon(Point(400, 150), Point(400, 160), Point(410, 160), Point(410, 320), Point(470, 320), Point(470, 160), Point(480, 160), Point(480, 150)) pipe.setFillColor('lightgreen') pipe.setDepth(10) pipe.move(-10, 0) _scene.add(pipe) class Mushroom(object): def __init__(self, x=200, y=92): mushroom = Layer() uppermush = Ellipse(38, 18, Point(x, y)) uppermush.setFillColor('red') uppermush.setDepth(52) lowermush = Ellipse(35, 25, Point(x, y+8)) lowermush.setFillColor('beige') lowermush.setDepth(53) mushroom.add(lowermush) mushroom.add(uppermush) mushroom.setDepth(52) self.layer = mushroom _scene.add(self.layer) def diappear(self): self.layer.scale(0.001) def move(self, x, y): self.layer.move(x, y) def arise(self): self.layer.setDepth(45) self.layer.move(0, -20) COLOR = ['Red', 'Blue'] TYPE = ['super', 'normal'] class Mario(object): def __init__(self, color='Blue', type='normal'): assert type in TYPE and color in COLOR self.color = color self.type = type self.step_size = 3 # Constructing Mario mario = Layer() # body body = Rectangle(33, 22, Point(200, 200)) body.setFillColor(color) body.setDepth(50) mario.add(body) # face face = Ellipse(30, 20, Point(200, 180)) face.setFillColor('beige') face.setDepth(40) mario.add(face) #hat hat = Polygon(Point(185, 175), Point(220, 175), Point(220, 173), Point(215, 173), Point(212, 168), Point(188, 168)) hat.setFillColor(color) hat.setDepth(39) mario.add(hat) #beard beard = Polygon(Point(207, 183), Point(217, 183), Point(215, 180), Point(209, 180)) beard.setFillColor('Brown') beard.setDepth(38) mario.add(beard) shoe = Layer() #left shoe lshoe = Rectangle(15, 6, Point(191, 215)) lshoe.setFillColor('black') lshoe.setDepth(52) shoe.add(lshoe) #right shoe rshoe = lshoe.clone() rshoe.move(17, 0) shoe.add(rshoe) mario.add(shoe) # save alias of moveable parts self.layer = mario self.body = body self.hat = hat self.shoe = shoe _scene.add(self.layer) self.moving_part_count = 0 if type == 'super': self.supermario() def shoe_move(self): if self.moving_part_count % 3 == 0: self.shoe.move(3, 0) elif self.moving_part_count % 3 == 1: self.shoe.move(-5,0) else: self.shoe.move(2,0) self.moving_part_count += 1 if self.moving_part_count % 3 == 0: self.moving_part_count = 0 def move(self,x=10,y=0): self.layer.move(x,y) def supermario(self): tempPt = self.body.getReferencePoint() self.layer.adjustReference(tempPt.getX(), tempPt.getY()) for i in range(3): self.layer.scale(1.3) sleep(t/2) self.layer.scale(0.9) sleep(t/2) def walk(self,x=20): assert x > 0 total_step = int(x / self.step_size) for i in range(total_step): sleep(t/4) self.move(self.step_size, 0) self.shoe_move() def show_animation(): sleep(t) mario.move(0, -50) mushroom.arise() sleep(t) mario.move(0, 50) mushroom.move(0, 8) for i in range(7): sleep(t/2) mushroom.move(10, 0) mario.move(10, 0) mario.shoe_move() sleep(t/2) mario.shoe_move() sleep(t/2) mushroom.move(0, 50) mario.move(10, 0) mario.shoe_move() sleep(t/2) mario.shoe_move() sleep(t) mushroom.move(0, 50) sleep(t/2) mushroom.diappear() sleep(t/2) mario.supermario() for i in range(6): sleep(t/2) mario.move(10, 0) mario.shoe_move() sleep(t/2) mario.shoe_move() for i in range(2): sleep(t) mario.move(28, -60) for i in range(1): sleep(t) mario.move(32, 40) sleep(2*t) for i in range(4): sleep(t) mario.move(0, 25) def interactive_example(): while True: e = _scene.wait() d = e.getDescription() if d == "keyboard": k = e.getKey() if k == "q": _scene.close() break elif k == "w": mario.walk(20) elif k == "r": mario.walk(40) elif k == "j": mario.move(0, -50) sleep(t) mario.move(0, 50) create_world() mario = Mario('Blue', 'normal') mushroom = Mushroom(200, 92) show_animation() # interactive_example()
8
2
TA
What is the role of list1 and temp?
import elice_utils f = open("tpmon.txt", "r") temp = [] list1 = [] temp = f.readlines() for i in range(len(temp)): list1.append(0) for i in range(len(temp)): if i==0: continue list1[i] = temp[i].split( ) for i in range(len(list1)-1): print('%d: %6.1f / %4.1f' % (int(i+1723), (float(list1[i+1][0])+float(list1[i+1][1]))/2, (float(list1[i+1][6])+float(list1[i+1][7]))/2)) g = open("tpmon.csv", "w") for i in range(len(temp)): if i==0: continue g.write(str(i+1722)) g.write(",") g.write(",".join(list1[i])) g.write("\n") f.close() g.close() elice_utils.send_file('tpmon.csv')
4
5
variable
temp is a list of files that have been read, and one column of the list contains a string of yearly weather, and list1 is a list that lets you know the monthly temperature by relisting the string of temp by month.
cs1qa
null
null
null
null
null
Question: What is the role of list1 and temp? Code: import elice_utils f = open("tpmon.txt", "r") temp = [] list1 = [] temp = f.readlines() for i in range(len(temp)): list1.append(0) for i in range(len(temp)): if i==0: continue list1[i] = temp[i].split( ) for i in range(len(list1)-1): print('%d: %6.1f / %4.1f' % (int(i+1723), (float(list1[i+1][0])+float(list1[i+1][1]))/2, (float(list1[i+1][6])+float(list1[i+1][7]))/2)) g = open("tpmon.csv", "w") for i in range(len(temp)): if i==0: continue g.write(str(i+1722)) g.write(",") g.write(",".join(list1[i])) g.write("\n") f.close() g.close() elice_utils.send_file('tpmon.csv')
5
0
TA
Please briefly explain when to use global!
balance=0 def deposit(money) : global balance # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# # Do something on here ! balance=balance+money ################# def withdrawal(money) : global balance # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance ################# ### implement ### ################# # Do something on here ! if balance>money: balance=balance-money else: print("But you only have",balance,'won') ################# def bank() : # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. ################# ### implement ### ################# # Do something on here ! if process=='d': money=int(input('How much do you want to deposit?')) print('You deposit', money, 'won') deposit(money) elif process=='w': money=int(input('How much do you want to withdrawal?')) print("You've withdraw", money, 'won') withdrawal(money) elif process=='c': print("Your current balance is", balance, "won") elif process=='': return else: print("Please, press d or w or c or return") ################# bank()
null
null
variable
Global is a global variable, and when used in two or more functions, we know that global is used.
cs1qa
null
null
null
null
null
Question: Please briefly explain when to use global! Code: balance=0 def deposit(money) : global balance # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output # Add the money to the current balance ################# ### implement ### ################# # Do something on here ! balance=balance+money ################# def withdrawal(money) : global balance # Input : (Integer) The amount of money that a user wants to withdraw # Output : (None) No Output # Withdraw the money from the current balance ################# ### implement ### ################# # Do something on here ! if balance>money: balance=balance-money else: print("But you only have",balance,'won') ################# def bank() : # Input : (None) No Input # Output : (None) No Output while True: process = input("Deposit(d) or withdrawal(w) or balance check(c)? ") # If a user's input is empty string (''), then quit this function. # If a user's input is 'd', then ask the amount of money to deposit and deposit it. # If a user's input is 'w', then ask the amount of money to withdraw and withdraw it. # If a user's input is 'c', then check the current balance. ################# ### implement ### ################# # Do something on here ! if process=='d': money=int(input('How much do you want to deposit?')) print('You deposit', money, 'won') deposit(money) elif process=='w': money=int(input('How much do you want to withdrawal?')) print("You've withdraw", money, 'won') withdrawal(money) elif process=='c': print("Your current balance is", balance, "won") elif process=='': return else: print("Please, press d or w or c or return") ################# bank()
2
2
TA
Please briefly explain the code
from cs1robots import * # Your code should work with any of the world files below. # TIP: Press Ctrl + '/' (or Cmd + '/' if you are using a Mac) # to comment out or restore the whole line of the code in the editor. #load_world('worlds/hurdles1.wld') #load_world('worlds/hurdles2.wld') load_world('worlds/hurdles3.wld') hubo = Robot() hubo.set_trace("blue") def turn_right(): for i in range(3): hubo.turn_left() def jump_one_hurdle(): hubo.turn_left() hubo.move() turn_right() hubo.move() turn_right() hubo.move() hubo.turn_left() while not hubo.on_beeper(): if hubo.front_is_clear(): hubo.move() else: jump_one_hurdle()
26
30
code_explain
Task 3 created a function over one hurdle and crossed the hurdle whenever the front was blocked.
cs1qa
null
null
null
null
null
Question: Please briefly explain the code Code: from cs1robots import * # Your code should work with any of the world files below. # TIP: Press Ctrl + '/' (or Cmd + '/' if you are using a Mac) # to comment out or restore the whole line of the code in the editor. #load_world('worlds/hurdles1.wld') #load_world('worlds/hurdles2.wld') load_world('worlds/hurdles3.wld') hubo = Robot() hubo.set_trace("blue") def turn_right(): for i in range(3): hubo.turn_left() def jump_one_hurdle(): hubo.turn_left() hubo.move() turn_right() hubo.move() turn_right() hubo.move() hubo.turn_left() while not hubo.on_beeper(): if hubo.front_is_clear(): hubo.move() else: jump_one_hurdle()