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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8 | 0 | TA | Please explain the ‘r’ and ‘w’ variables of open(). | # -*- coding: utf-8 -*
'''
Merge a set of input files into a single output file.
Define a function merge.
Parameter 1: names of a set of input files (list of strings)
Parameter 2: a name of a single output file (string)
Return: None
'''
from time import sleep
import elice_utils
def merge(input_filenames, output_filename):
content = ""
for filename in input_filenames:
with open(filename, "r") as f:
lines = f.readlines()
for line in lines:
content = content + line
with open(output_filename, "w") as f:
f.write(content)
merge(['kaist1.txt', 'kaist2.txt', 'kaist3.txt'], 'output.txt')
elice_utils.send_file('output.txt')
| 16 | 22 | variable | r-Used when only reading a file, and writing the contents to a w file. | cs1qa | null | null | null | null | null | Question:
Please explain the ‘r’ and ‘w’ variables of open().
Code:
# -*- coding: utf-8 -*
'''
Merge a set of input files into a single output file.
Define a function merge.
Parameter 1: names of a set of input files (list of strings)
Parameter 2: a name of a single output file (string)
Return: None
'''
from time import sleep
import elice_utils
def merge(input_filenames, output_filename):
content = ""
for filename in input_filenames:
with open(filename, "r") as f:
lines = f.readlines()
for line in lines:
content = content + line
with open(output_filename, "w") as f:
f.write(content)
merge(['kaist1.txt', 'kaist2.txt', 'kaist3.txt'], 'output.txt')
elice_utils.send_file('output.txt')
|
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
global balance
# Add the money to the current balance
balance = balance + int(money)
print("You deposited "+ str(money) + " won")
#################
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 int(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")
#################
### implement ###
#################
# Do something on here !
#################
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 == 'd':
dep = int(input("How much do you want to deposit?"))
deposit(dep)
elif process == 'w':
wit = int(input('How much do you want to withdraw?'))
withdrawal(wit)
elif process == 'c':
print("Your current balance is "+str(balance)+" won")
elif process == 'return' or process == '':
return
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 | 26 | variable | Since the functions used in this task are to add, subtract, or check a value from the global variable balance, he said that each function would use the global variable balance. | 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
global balance
# Add the money to the current balance
balance = balance + int(money)
print("You deposited "+ str(money) + " won")
#################
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 int(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")
#################
### implement ###
#################
# Do something on here !
#################
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 == 'd':
dep = int(input("How much do you want to deposit?"))
deposit(dep)
elif process == 'w':
wit = int(input('How much do you want to withdraw?'))
withdrawal(wit)
elif process == 'c':
print("Your current balance is "+str(balance)+" won")
elif process == 'return' or process == '':
return
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()
|
9 | 1 | TA | Please briefly explain how the 5 functions work! | 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 Cards :
def setdata1(self,suit,face,Img,value) :
self.suit = suit
self.face = face
self.img = Img
self.value = value
def setdata2(self, hid_or_not) :
self.state = hid_or_not
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'
"""
cards = []
for i in range (4) :
for k in range (13) :
img_code = Image(img_path+suit_names[i]+'_'+face_names[k]+'.png')
C = Cards()
C.setdata1(suit_names[i],face_names[i], img_code, value[k])
C.setdata2(True)
cards.append(C)
random.shuffle(cards)
return cards
def hand_value(hand):
"""
hand is a list including card objects
Compute the value of the cards in the list "hand"
"""
give_money = 0
for i in range(len(hand)) :
give_money = give_money + hand[i].value
return give_money
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")
"""
card_name_nicely = str('a ' + card.face + ' of ' + card.suit)
return card_name_nicely
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 :
ask = input(prompt)
if ask == 'y':
return True
elif ask == 'n':
return False
else :
print("I beg your pardon!")
continue
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 i in range(len(dealer)):
if dealer[i].state:
bj_board.add(dealer[i].img)
dealer[i].img.moveTo(x0+i*20,y0)
dealer[i].img.setDepth(depth-10*i)
else:
back_of_the_card_image=Image(img_path+'Back.png')
bj_board.add(back_of_the_card_image)
back_of_the_card_image.moveTo(x0+i*20,y0)
back_of_the_card_image.setDepth(depth-10*i)
for i in range(len(player)):
if player[i].state:
bj_board.add(player[i].img)
player[i].img.moveTo(x1+i*20,y1)
player[i].img.setDepth(depth-10*i)
else:
back_of_the_card_image=Image(img_path+'Back.png')
bj_board.add(back_of_the_card_image)
back_of_the_card_image.moveTo(x1+i*20,y1)
back_of_the_card_image.setDepth(depth-10*i)
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()
| 50 | 58 | variable | The hand_value function adds all the values of the cards that are elements of the hand given as a list and returns the sum of the values. | cs1qa | null | null | null | null | null | Question:
Please briefly explain how the 5 functions work!
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 Cards :
def setdata1(self,suit,face,Img,value) :
self.suit = suit
self.face = face
self.img = Img
self.value = value
def setdata2(self, hid_or_not) :
self.state = hid_or_not
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'
"""
cards = []
for i in range (4) :
for k in range (13) :
img_code = Image(img_path+suit_names[i]+'_'+face_names[k]+'.png')
C = Cards()
C.setdata1(suit_names[i],face_names[i], img_code, value[k])
C.setdata2(True)
cards.append(C)
random.shuffle(cards)
return cards
def hand_value(hand):
"""
hand is a list including card objects
Compute the value of the cards in the list "hand"
"""
give_money = 0
for i in range(len(hand)) :
give_money = give_money + hand[i].value
return give_money
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")
"""
card_name_nicely = str('a ' + card.face + ' of ' + card.suit)
return card_name_nicely
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 :
ask = input(prompt)
if ask == 'y':
return True
elif ask == 'n':
return False
else :
print("I beg your pardon!")
continue
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 i in range(len(dealer)):
if dealer[i].state:
bj_board.add(dealer[i].img)
dealer[i].img.moveTo(x0+i*20,y0)
dealer[i].img.setDepth(depth-10*i)
else:
back_of_the_card_image=Image(img_path+'Back.png')
bj_board.add(back_of_the_card_image)
back_of_the_card_image.moveTo(x0+i*20,y0)
back_of_the_card_image.setDepth(depth-10*i)
for i in range(len(player)):
if player[i].state:
bj_board.add(player[i].img)
player[i].img.moveTo(x1+i*20,y1)
player[i].img.setDepth(depth-10*i)
else:
back_of_the_card_image=Image(img_path+'Back.png')
bj_board.add(back_of_the_card_image)
back_of_the_card_image.moveTo(x1+i*20,y1)
back_of_the_card_image.setDepth(depth-10*i)
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()
|
8 | 1 | TA | How did you process the data in #2? | f = open("average-latitude-longitude-countries.csv", "r")
name = []
coordinate = []
a = []
for line in f:
a.append(line.split(","))
for i in range(1,len(a)):
if len(a[i]) == 4:
name.append((a[i][0][1:-1], a[i][1][1:-1]))
coordinate.append((a[i][0][1:-1],(float(a[i][2]), float(a[i][3]))))
else:
name.append((a[i][0][1:-1], a[i][1][1:] + "," + a[i][2][:-1]))
coordinate.append((a[i][0][1:-1], (float(a[i][3]), float(a[i][4]))))
for i in range(len(coordinate)):
if coordinate[i][1][0] < 0:
print(name[i][1])
print(name)
print(coordinate)
b = str(input("Enter country code: "))
for i in range(len(name)):
if b == name[i][0]:
print(name[i][1])
| 4 | 12 | code_explain | First, the data was divided by the split function based on',', and the front and back "" were cut and saved in the list.
In addition, countries containing, were classified separately and processed. | cs1qa | null | null | null | null | null | Question:
How did you process the data in #2?
Code:
f = open("average-latitude-longitude-countries.csv", "r")
name = []
coordinate = []
a = []
for line in f:
a.append(line.split(","))
for i in range(1,len(a)):
if len(a[i]) == 4:
name.append((a[i][0][1:-1], a[i][1][1:-1]))
coordinate.append((a[i][0][1:-1],(float(a[i][2]), float(a[i][3]))))
else:
name.append((a[i][0][1:-1], a[i][1][1:] + "," + a[i][2][:-1]))
coordinate.append((a[i][0][1:-1], (float(a[i][3]), float(a[i][4]))))
for i in range(len(coordinate)):
if coordinate[i][1][0] < 0:
print(name[i][1])
print(name)
print(coordinate)
b = str(input("Enter country code: "))
for i in range(len(name)):
if b == name[i][0]:
print(name[i][1])
|
8 | 1 | TA | What is f.readlines()? | f = open('average-latitude-longitude-countries.csv', 'r')
code_name = []
code_lat_long = []
l = f.readlines()
for n in range(len(l)-1):
i = n+1
code = l[i].split(',')[0].replace('"','')
if l[i].count(',')==3:
name = l[i].split(',')[1].replace('"','')
else:
name = l[i].split(',')[1].replace('"','')+','+l[i].split(',')[2].replace('"','')
code_name.append((code, name))
lat = float(l[i].split(',')[-2])
long = float(l[i].split(',')[-1])
code_lat_long.append((code, (lat, long)))
if lat<0:
print(name)
print(code_name)
print(code_lat_long)
what_code = input('Enter country code: ')
for i in range(len(code_name)):
if what_code == code_name[i][0]:
print(code_name[i][1])
break
| 3 | 3 | variable | Create a list l where each line is a string element, similar to the method used in task2 | cs1qa | null | null | null | null | null | Question:
What is f.readlines()?
Code:
f = open('average-latitude-longitude-countries.csv', 'r')
code_name = []
code_lat_long = []
l = f.readlines()
for n in range(len(l)-1):
i = n+1
code = l[i].split(',')[0].replace('"','')
if l[i].count(',')==3:
name = l[i].split(',')[1].replace('"','')
else:
name = l[i].split(',')[1].replace('"','')+','+l[i].split(',')[2].replace('"','')
code_name.append((code, name))
lat = float(l[i].split(',')[-2])
long = float(l[i].split(',')[-1])
code_lat_long.append((code, (lat, long)))
if lat<0:
print(name)
print(code_name)
print(code_lat_long)
what_code = input('Enter country code: ')
for i in range(len(code_name)):
if what_code == code_name[i][0]:
print(code_name[i][1])
break
|
6 | 0 | TA | Please explain what upper_bound does in Task 1 | def fibonacci(upper_bound):
fib=[0,1]
n=3
a=0
while n<=upper_bound:
a=fib[n-3]+fib[n-2]
fib.append(a)
n+=1
return fib
pass
print(fibonacci(1000))
| 0 | 4 | variable | In task 1, upper_bound tells how many times the terms of the Fibonacci sequence will be expanded. | cs1qa | null | null | null | null | null | Question:
Please explain what upper_bound does in Task 1
Code:
def fibonacci(upper_bound):
fib=[0,1]
n=3
a=0
while n<=upper_bound:
a=fib[n-3]+fib[n-2]
fib.append(a)
n+=1
return fib
pass
print(fibonacci(1000))
|
10 | 0 | TA | Why did you do _scene.add(cc)? | 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()
| null | null | reasoning | Conventionally, only bullets are fired.
The original animation has an effect called cc
But in order to make it interactive, the cc must rotate together when the position of the gun changes, but it is difficult to implement
I added cc (fire effect) to animation only | cs1qa | null | null | null | null | null | Question:
Why did you do _scene.add(cc)?
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()
|
4 | 2 | TA | What is the unit of x in sin(x) in task3? | import math
sin = math.sin
pi = math.pi
a= int(input('How many steps? '))
for i in range(a):
x = float(i) / (a-1) * 2 * pi
print (sin(x)) | 8 | 9 | variable | Radians | cs1qa | null | null | null | null | null | Question:
What is the unit of x in sin(x) 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) / (a-1) * 2 * pi
print (sin(x)) |
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) |
2 | 0 | TA | I'm going to check it now. Can you explain how you made it for each task in the meantime? | from cs1robots import *
load_world('worlds/harvest3.wld')
hubo=Robot()
hubo.set_trace("blue")
def harvest():
if hubo.on_beeper():
hubo.pick_beeper()
def st1():
for i in range(5):
hubo.move()
harvest()
hubo.turn_left()
hubo.move()
harvest()
hubo.turn_left()
for i in range(5):
hubo.move()
harvest()
for i in range(3):
hubo.turn_left()
hubo.move()
harvest()
for i in range(3):
hubo.turn_left()
hubo.move()
harvest()
for i in range(2):
st1()
for i in range(5):
hubo.move()
harvest()
hubo.turn_left()
hubo.move()
harvest()
hubo.turn_left()
for i in range(5):
hubo.move()
harvest() | 9 | 40 | code_explain | task1 wrote a program that moves all paths with beepers and then wrote a separate function that collects beepers when there is a beeper in each moving state, so that the function works after every move. | cs1qa | null | null | null | null | null | Question:
I'm going to check it now. Can you explain how you made it for each task in the meantime?
Code:
from cs1robots import *
load_world('worlds/harvest3.wld')
hubo=Robot()
hubo.set_trace("blue")
def harvest():
if hubo.on_beeper():
hubo.pick_beeper()
def st1():
for i in range(5):
hubo.move()
harvest()
hubo.turn_left()
hubo.move()
harvest()
hubo.turn_left()
for i in range(5):
hubo.move()
harvest()
for i in range(3):
hubo.turn_left()
hubo.move()
harvest()
for i in range(3):
hubo.turn_left()
hubo.move()
harvest()
for i in range(2):
st1()
for i in range(5):
hubo.move()
harvest()
hubo.turn_left()
hubo.move()
harvest()
hubo.turn_left()
for i in range(5):
hubo.move()
harvest() |
3 | 4 | TA | When solving Task 5, why do you need to nest two for statements? | from cs1media import *
# This code converts an image into a black & white poster.
threshold1 = 170
threshold2 = 85
yellow = (255, 255, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
image = load_picture('./images/ironman.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 > threshold1:
image.set(x, y, yellow)
elif average_brightness < threshold2:
image.set(x, y, blue)
else:
image.set(x, y, green)
image.show() | 13 | 15 | reasoning | Since the picture is two-dimensional, you need to use a double for statement to iterate over all x and y. | cs1qa | null | null | null | null | null | Question:
When solving Task 5, why do you need to nest two for statements?
Code:
from cs1media import *
# This code converts an image into a black & white poster.
threshold1 = 170
threshold2 = 85
yellow = (255, 255, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
image = load_picture('./images/ironman.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 > threshold1:
image.set(x, y, yellow)
elif average_brightness < threshold2:
image.set(x, y, blue)
else:
image.set(x, y, green)
image.show() |
2 | 2 | TA | In code 3, explain the meaning of the while statement written in line 29 :) | 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')
ojing = Robot()
ojing.set_trace('blue')
def turn_right():
for i in range(3):
ojing.turn_left()
def jump_one_hurdle():
if not ojing.front_is_clear():
ojing.turn_left()
ojing.move()
for i in range(2):
turn_right()
ojing.move()
ojing.turn_left()
def jump_hurdles():
while not ojing.on_beeper():
jump_one_hurdle()
if not ojing.on_beeper() and ojing.front_is_clear():
ojing.move()
jump_hurdles() | 28 | 31 | variable | That while statement was used to prevent the jump_one_hurdle function from being executed when the robot climbed on the beeper, because the motion must be finished. | cs1qa | null | null | null | null | null | Question:
In code 3, explain the meaning of the while statement written in line 29 :)
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')
ojing = Robot()
ojing.set_trace('blue')
def turn_right():
for i in range(3):
ojing.turn_left()
def jump_one_hurdle():
if not ojing.front_is_clear():
ojing.turn_left()
ojing.move()
for i in range(2):
turn_right()
ojing.move()
ojing.turn_left()
def jump_hurdles():
while not ojing.on_beeper():
jump_one_hurdle()
if not ojing.on_beeper() and ojing.front_is_clear():
ojing.move()
jump_hurdles() |
3 | 4 | TA | Yes, lastly, in task5, please briefly explain how to classify into three colors! | from cs1media import *
# This code converts an image into a black & white poster.
threshold = 190
white = (255, 255, 255)
black = (0, 0, 0)
image = load_picture('./images/ironman.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 > threshold:
image.set(x, y, (255,255,0))
elif average_brightness < 90:
image.set(x, y, (0,0,255))
else:
image.set(x, y, (0,255,0))
image.show() | 15 | 20 | code_explain | If the average brightness is less than 95, it is classified as blue, 95 to 190 is green, and if it is greater than 190, it is classified as yellow. | cs1qa | null | null | null | null | null | Question:
Yes, lastly, in task5, please briefly explain how to classify into three colors!
Code:
from cs1media import *
# This code converts an image into a black & white poster.
threshold = 190
white = (255, 255, 255)
black = (0, 0, 0)
image = load_picture('./images/ironman.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 > threshold:
image.set(x, y, (255,255,0))
elif average_brightness < 90:
image.set(x, y, (0,0,255))
else:
image.set(x, y, (0,255,0))
image.show() |
3 | 3 | TA | Please explain the drop_go function | 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.
hubo = Robot(beepers=100, avenue=2, street=6, orientation='E')
hubo.set_trace('blue')
# Now close all the windows in the house!
def back():
for i in range(2):
hubo.turn_left()
hubo.move()
def turn_right():
for i in range(3):
hubo.turn_left()
def drop_go():
if hubo.left_is_clear():
hubo.move()
if not hubo.left_is_clear():
back()
hubo.drop_beeper()
back()
else:
back()
turn_right()
hubo.move()
def left_clear():
if hubo.left_is_clear():
hubo.turn_left()
hubo.move()
hubo.move()
hubo.drop_beeper()
hubo.turn_left()
hubo.move()
hubo.drop_beeper()
hubo.move()
turn_right()
while not hubo.on_beeper():
hubo.move()
drop_go()
if not hubo.front_is_clear():
turn_right()
hubo.pick_beeper()
back()
hubo.pick_beeper()
hubo.pick_beeper()
turn_right()
| 18 | 28 | variable | This is a function that distinguishes between windows and non-windows. | cs1qa | null | null | null | null | null | Question:
Please explain the drop_go function
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.
hubo = Robot(beepers=100, avenue=2, street=6, orientation='E')
hubo.set_trace('blue')
# Now close all the windows in the house!
def back():
for i in range(2):
hubo.turn_left()
hubo.move()
def turn_right():
for i in range(3):
hubo.turn_left()
def drop_go():
if hubo.left_is_clear():
hubo.move()
if not hubo.left_is_clear():
back()
hubo.drop_beeper()
back()
else:
back()
turn_right()
hubo.move()
def left_clear():
if hubo.left_is_clear():
hubo.turn_left()
hubo.move()
hubo.move()
hubo.drop_beeper()
hubo.turn_left()
hubo.move()
hubo.drop_beeper()
hubo.move()
turn_right()
while not hubo.on_beeper():
hubo.move()
drop_go()
if not hubo.front_is_clear():
turn_right()
hubo.pick_beeper()
back()
hubo.pick_beeper()
hubo.pick_beeper()
turn_right()
|
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')
| 32 | 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')
|
8 | 0 | TA | Please explain code 1 | import elice_utils
from time import sleep
def merge(input_filenames, output_filename):
# Implement here
# ...
input_file = []
s = ""
for i in range(len(input_filenames)):
input_file.append(open(input_filenames[i], "r" ))
s = s + input_file[i].read() + "\n"
for i in range(len(input_filenames)):
input_file[i].close()
output_file = open(output_filename,"w")
output_file.write(s)
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 | 14 | code_explain | I read three text files with the read function and made them into one string to create an output file. | cs1qa | null | null | null | null | null | Question:
Please explain code 1
Code:
import elice_utils
from time import sleep
def merge(input_filenames, output_filename):
# Implement here
# ...
input_file = []
s = ""
for i in range(len(input_filenames)):
input_file.append(open(input_filenames[i], "r" ))
s = s + input_file[i].read() + "\n"
for i in range(len(input_filenames)):
input_file[i].close()
output_file = open(output_filename,"w")
output_file.write(s)
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') |
9 | 1 | TA | Yes I checked~~ What is the deck list, dealer list, and player list in task 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]
deck = []
bj_board = Canvas(600, 400, 'dark green', 'Black Jack 101')
"""
Define the Card class
"""
class Card():
pass
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'
"""
deck = []
for i in range(4):
for j in range(13):
card = Card()
card.suit = suit_names[i]
card.face = face_names[j]
card.value = value[j]
path = img_path+suit_names[i]+'_'+face_names[j]+'.png'
card.image = Image(path)
card.state = True
deck.append(card)
random.shuffle(deck)
return deck
def hand_value(hand):
"""
hand is a list including card objects
Compute the value of the cards in the list "hand"
"""
num = 0
for i in range(len(hand)):
num += hand[i].value
return num
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 card.face == '8' or card.face == 'Ace':
article = "an "
return (article+card.face+' of '+card.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.
"""
while True:
answer = input(prompt)
if answer =='y' or answer=='n':
break
else:
print("I beg your pardon!")
if answer == 'y':
return True
else:
return False
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
hidden = 0
back_image = Image('./images/Back.png')
bj_board.clear()
for i in range(len(dealer)):
if dealer[i].state == False:
bj_board.add(back_image)
back_image.moveTo(x0,y0)
back_image.setDepth(depth)
hidden = 1
else:
bj_board.add(dealer[i].image)
dealer[i].image.moveTo(x0,y0)
dealer[i].image.setDepth(depth)
x0 += 20
depth -= 10
for i in range(len(player)):
bj_board.add(player[i].image)
player[i].image.moveTo(x1,y1)
player[i].image.setDepth(depth)
x1 += 20
depth -= 10
if hidden == 0:
dealer_score = Text("""The dealer's Total:"""+str(hand_value(dealer)))
bj_board.add(dealer_score)
dealer_score.setFontColor('yellow')
dealer_score.moveTo(500, y0)
dealer_score.setDepth(0)
player_score = Text("Your Total: "+str(hand_value(player)))
bj_board.add(player_score)
player_score.setFontColor('yellow')
player_score.moveTo(500, y1)
player_score.setDepth(0)
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()
| 174 | 175 | variable | The deck list is a list of 52 cards in total, and the dealer list and player list are lists that have the assigned card objects as elements!! | cs1qa | null | null | null | null | null | Question:
Yes I checked~~ What is the deck list, dealer list, and player list in task 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]
deck = []
bj_board = Canvas(600, 400, 'dark green', 'Black Jack 101')
"""
Define the Card class
"""
class Card():
pass
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'
"""
deck = []
for i in range(4):
for j in range(13):
card = Card()
card.suit = suit_names[i]
card.face = face_names[j]
card.value = value[j]
path = img_path+suit_names[i]+'_'+face_names[j]+'.png'
card.image = Image(path)
card.state = True
deck.append(card)
random.shuffle(deck)
return deck
def hand_value(hand):
"""
hand is a list including card objects
Compute the value of the cards in the list "hand"
"""
num = 0
for i in range(len(hand)):
num += hand[i].value
return num
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 card.face == '8' or card.face == 'Ace':
article = "an "
return (article+card.face+' of '+card.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.
"""
while True:
answer = input(prompt)
if answer =='y' or answer=='n':
break
else:
print("I beg your pardon!")
if answer == 'y':
return True
else:
return False
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
hidden = 0
back_image = Image('./images/Back.png')
bj_board.clear()
for i in range(len(dealer)):
if dealer[i].state == False:
bj_board.add(back_image)
back_image.moveTo(x0,y0)
back_image.setDepth(depth)
hidden = 1
else:
bj_board.add(dealer[i].image)
dealer[i].image.moveTo(x0,y0)
dealer[i].image.setDepth(depth)
x0 += 20
depth -= 10
for i in range(len(player)):
bj_board.add(player[i].image)
player[i].image.moveTo(x1,y1)
player[i].image.setDepth(depth)
x1 += 20
depth -= 10
if hidden == 0:
dealer_score = Text("""The dealer's Total:"""+str(hand_value(dealer)))
bj_board.add(dealer_score)
dealer_score.setFontColor('yellow')
dealer_score.moveTo(500, y0)
dealer_score.setDepth(0)
player_score = Text("Your Total: "+str(hand_value(player)))
bj_board.add(player_score)
player_score.setFontColor('yellow')
player_score.moveTo(500, y1)
player_score.setDepth(0)
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()
|
5 | 0 | TA | Please explain how withdrawal works 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
global balance
balance = balance + money
#################
### implement ###
#################
# Do something on here !
print('You deposited',money,'won')
return balance
#################
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 money > balance:
print("You've withdrawn",money,'won')
print('But you only have',balance,'won')
else:
balance = balance - money
print("You've widthdraw",money,'won')
#################
### implement ###
#################
# Do something on here !
return balance
#################
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 process == '':
return
# If a user's input is 'd', then ask the amount of money to deposit and deposit it.
elif 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', balance, 'won')
else:
print('Please, press d or w or c to return')
#################
### implement ###
#################
# Do something on here !
#################
bank()
| 18 | 35 | variable | Withdrawal is a function that withdraws when the amount you want to withdraw is deposited and the balance is greater than that amount. | cs1qa | null | null | null | null | null | Question:
Please explain how withdrawal works 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
global balance
balance = balance + money
#################
### implement ###
#################
# Do something on here !
print('You deposited',money,'won')
return balance
#################
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 money > balance:
print("You've withdrawn",money,'won')
print('But you only have',balance,'won')
else:
balance = balance - money
print("You've widthdraw",money,'won')
#################
### implement ###
#################
# Do something on here !
return balance
#################
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 process == '':
return
# If a user's input is 'd', then ask the amount of money to deposit and deposit it.
elif 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', balance, 'won')
else:
print('Please, press d or w or c to return')
#################
### implement ###
#################
# Do something on here !
#################
bank()
|
6 | 0 | TA | Fn.remove(Fn[-1]) from task1
Why should I do it? | def fibonacci(upper_bound):
Fn = [0, 1]
while Fn[-1] < upper_bound :
Fn.append(Fn[-1] + Fn[-2])
Fn.remove(Fn[-1])
return Fn
pass
print(fibonacci(1000))
| 4 | 4 | reasoning | This is because the last term in the list is the value of the smallest Fibonacci sequence over 1000, so I have to delete the last term to get it as desired in the problem. | cs1qa | null | null | null | null | null | Question:
Fn.remove(Fn[-1]) from task1
Why should I do it?
Code:
def fibonacci(upper_bound):
Fn = [0, 1]
while Fn[-1] < upper_bound :
Fn.append(Fn[-1] + Fn[-2])
Fn.remove(Fn[-1])
return Fn
pass
print(fibonacci(1000))
|
2 | 2 | TA | What does jump_one_hurdle in Task 3 do? | from cs1robots import *
load_world('worlds/hurdles1.wld')
#load_world('worlds/hurdles2.wld')
#load_world('worlds/hurdles3.wld')
my_robot = Robot()
my_robot.set_trace("blue")
a=0
def turnright():
my_robot.turn_left()
my_robot.turn_left()
my_robot.turn_left()
def check():
if my_robot.on_beeper()==True:
a=1
else:
a=0
def jump_one_hurdle():
if my_robot.front_is_clear()==False:
my_robot.turn_left()
my_robot.move()
turnright()
my_robot.move()
turnright()
my_robot.move()
my_robot.turn_left()
else:
my_robot.move()
while my_robot.on_beeper()==False:
jump_one_hurdle() | 18 | 30 | variable | If there is a wall in front of the robot, it goes over the wall, and if there is no wall, it moves forward one space. | cs1qa | null | null | null | null | null | Question:
What does jump_one_hurdle in Task 3 do?
Code:
from cs1robots import *
load_world('worlds/hurdles1.wld')
#load_world('worlds/hurdles2.wld')
#load_world('worlds/hurdles3.wld')
my_robot = Robot()
my_robot.set_trace("blue")
a=0
def turnright():
my_robot.turn_left()
my_robot.turn_left()
my_robot.turn_left()
def check():
if my_robot.on_beeper()==True:
a=1
else:
a=0
def jump_one_hurdle():
if my_robot.front_is_clear()==False:
my_robot.turn_left()
my_robot.move()
turnright()
my_robot.move()
turnright()
my_robot.move()
my_robot.turn_left()
else:
my_robot.move()
while my_robot.on_beeper()==False:
jump_one_hurdle() |
4 | 2 | TA | What is the unit of x in sin(x) in task3? | 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)) | 8 | 8 | variable | Radians
Data type is real | cs1qa | null | null | null | null | null | Question:
What is the unit of x in sin(x) in task3?
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)) |
2 | 4 | TA | Please explain the function r | 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)
# ...
bot = Robot()
bot.set_trace('blue')
bot.turn_left()
def r():
bot.turn_left()
bot.turn_left()
bot.turn_left()
def zigzag():
while bot.front_is_clear():
bot.move()
r()
bot.move()
r()
while bot.front_is_clear():
bot.move()
bot.turn_left()
bot.move()
bot.turn_left()
while bot.front_is_clear():
zigzag()
| 16 | 19 | variable | Function r is a function that rotates to the right. | cs1qa | null | null | null | null | null | Question:
Please explain the function r
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)
# ...
bot = Robot()
bot.set_trace('blue')
bot.turn_left()
def r():
bot.turn_left()
bot.turn_left()
bot.turn_left()
def zigzag():
while bot.front_is_clear():
bot.move()
r()
bot.move()
r()
while bot.front_is_clear():
bot.move()
bot.turn_left()
bot.move()
bot.turn_left()
while bot.front_is_clear():
zigzag()
|
5 | 1 | TA | How did you write your code to move the wings of the bee? | from cs1graphics import *
from time import sleep
paper = Canvas(400, 300)
paper.setBackgroundColor('skyBlue')
paper.setTitle('My world')
sun = Circle(30)
sun.setFillColor('yellow')
sun.setBorderColor('yellow')
paper.add(sun)
sun.moveTo(340, 50)
sun.setDepth(90)
tree = Layer()
tree1 = Rectangle(40, 100, Point(0, -50))
tree1.setFillColor('brown')
tree.add(tree1)
tree2 = Polygon(Point(50,-100), Point(-50,-100), Point(0,-150))
tree2.setFillColor('darkgreen')
tree.add(tree2)
paper.add(tree)
tree.moveTo(80, 200)
tree.setDepth(90)
grass = Rectangle(400,200)
grass.setFillColor('green')
paper.add(grass)
grass.moveTo(200, 250)
grass.setDepth(100)
def draw_animal():
# Implement this function.
bee = Layer()
body1 = Rectangle(70, 50, Point(0, -25))
body1.setFillColor('yellow')
body1.setDepth(70)
bee.add(body1)
body2 = Circle(25, Point(-35, -25))
body2.setFillColor('yellow')
body2.setDepth(75)
body3 = body2.clone()
body3.moveTo(35, -25)
bee.add(body2)
bee.add(body3)
body4 = Rectangle(14, 50, Point(-28, -25))
body4.setFillColor('black')
bee.add(body4)
for i in range(2):
body5 = body4.clone()
body5.move(14*2*(i+1), 0)
bee.add(body5)
wing1 = Ellipse(50, 70, Point(0, -70))
wing1.setFillColor('white')
wing1.setDepth(80)
wing2 = wing1.clone()
wing2.moveTo(0, 20)
wing1.adjustReference(0, 35)
wing2.adjustReference(0, -35)
bee.add(wing1)
bee.add(wing2)
eye11 = Circle(10, Point(58, -35))
eye12 = Circle(5, Point(58, -35))
eye11.setFillColor('white')
eye11.setDepth(55)
eye12.setFillColor('black')
bee.add(eye11)
bee.add(eye12)
eye21 = Circle(10, Point(58, -15))
eye22 = Circle(5, Point(58, -15))
eye21.setFillColor('white')
eye21.setDepth(55)
eye22.setFillColor('black')
bee.add(eye21)
bee.add(eye22)
return bee, wing1, wing2
pass
def show_animation():
# Implement this function
bee, wing1, wing2 = draw_animal()
paper.add(bee)
bee.moveTo(200, 140)
for i in range(150):
bee.move(2, 0)
wing1.flip(-10)
wing2.flip(10)
sleep(0.1)
wing1.flip(-10)
wing2.flip(10)
sleep(0.1)
pass
draw_animal()
show_animation() | 87 | 94 | code_explain | So I make the wings sway down and forth by using flip method. First the upper wing will flip around the -10 degree axis from vertical, and the lower wing will flip around the 10 degree axis. Then, they will return to the initial position by applying the same code | cs1qa | null | null | null | null | null | Question:
How did you write your code to move the wings of the bee?
Code:
from cs1graphics import *
from time import sleep
paper = Canvas(400, 300)
paper.setBackgroundColor('skyBlue')
paper.setTitle('My world')
sun = Circle(30)
sun.setFillColor('yellow')
sun.setBorderColor('yellow')
paper.add(sun)
sun.moveTo(340, 50)
sun.setDepth(90)
tree = Layer()
tree1 = Rectangle(40, 100, Point(0, -50))
tree1.setFillColor('brown')
tree.add(tree1)
tree2 = Polygon(Point(50,-100), Point(-50,-100), Point(0,-150))
tree2.setFillColor('darkgreen')
tree.add(tree2)
paper.add(tree)
tree.moveTo(80, 200)
tree.setDepth(90)
grass = Rectangle(400,200)
grass.setFillColor('green')
paper.add(grass)
grass.moveTo(200, 250)
grass.setDepth(100)
def draw_animal():
# Implement this function.
bee = Layer()
body1 = Rectangle(70, 50, Point(0, -25))
body1.setFillColor('yellow')
body1.setDepth(70)
bee.add(body1)
body2 = Circle(25, Point(-35, -25))
body2.setFillColor('yellow')
body2.setDepth(75)
body3 = body2.clone()
body3.moveTo(35, -25)
bee.add(body2)
bee.add(body3)
body4 = Rectangle(14, 50, Point(-28, -25))
body4.setFillColor('black')
bee.add(body4)
for i in range(2):
body5 = body4.clone()
body5.move(14*2*(i+1), 0)
bee.add(body5)
wing1 = Ellipse(50, 70, Point(0, -70))
wing1.setFillColor('white')
wing1.setDepth(80)
wing2 = wing1.clone()
wing2.moveTo(0, 20)
wing1.adjustReference(0, 35)
wing2.adjustReference(0, -35)
bee.add(wing1)
bee.add(wing2)
eye11 = Circle(10, Point(58, -35))
eye12 = Circle(5, Point(58, -35))
eye11.setFillColor('white')
eye11.setDepth(55)
eye12.setFillColor('black')
bee.add(eye11)
bee.add(eye12)
eye21 = Circle(10, Point(58, -15))
eye22 = Circle(5, Point(58, -15))
eye21.setFillColor('white')
eye21.setDepth(55)
eye22.setFillColor('black')
bee.add(eye21)
bee.add(eye22)
return bee, wing1, wing2
pass
def show_animation():
# Implement this function
bee, wing1, wing2 = draw_animal()
paper.add(bee)
bee.moveTo(200, 140)
for i in range(150):
bee.move(2, 0)
wing1.flip(-10)
wing2.flip(10)
sleep(0.1)
wing1.flip(-10)
wing2.flip(10)
sleep(0.1)
pass
draw_animal()
show_animation() |
2 | 0 | TA | What is the role of flag in Task1 right(n, flag) function? | from cs1robots import *
#create_world()
load_world('worlds/harvest3.wld')
def turn_right():
for j in range(1,4):
hubo.turn_left()
def go_n(n):
for i in range(1,n+1):
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
hubo=Robot()
hubo.set_trace('blue')
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
'''
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
for i in range(1,5):
hubo.move()
hubo.turn_left()
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
turn_right()
'''
arr1=[5,5,5]
arr2=[5,5,5]
def left(n):
go_n(n)
hubo.turn_left()
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
hubo.turn_left()
def right(n,flag):
go_n(n)
if flag == 1:
turn_right()
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
turn_right()
for i in range(3):
left(arr1[i])
if i == 2:
right(arr2[i],0)
else:
right(arr2[i],1)
#go-turnleft *2, go-turn right*2 | 43 | 48 | variable | The flag was meant to slightly adjust the position as the last movement protrudes and does not match the picture in the task video. | cs1qa | null | null | null | null | null | Question:
What is the role of flag in Task1 right(n, flag) function?
Code:
from cs1robots import *
#create_world()
load_world('worlds/harvest3.wld')
def turn_right():
for j in range(1,4):
hubo.turn_left()
def go_n(n):
for i in range(1,n+1):
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
hubo=Robot()
hubo.set_trace('blue')
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
'''
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
for i in range(1,5):
hubo.move()
hubo.turn_left()
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
turn_right()
'''
arr1=[5,5,5]
arr2=[5,5,5]
def left(n):
go_n(n)
hubo.turn_left()
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
hubo.turn_left()
def right(n,flag):
go_n(n)
if flag == 1:
turn_right()
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
turn_right()
for i in range(3):
left(arr1[i])
if i == 2:
right(arr2[i],0)
else:
right(arr2[i],1)
#go-turnleft *2, go-turn right*2 |
2 | 4 | TA | Why does the while statement exit when there is a wall on the left and right? | from cs1robots import *
# Your code must work for empty worlds of all possible sizes.
create_world(avenues=4, streets=9)
# 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)
# ...
my_robot=Robot()
my_robot.set_trace('blue')
def turn_right():
for i in range(3):
my_robot.turn_left()
turn=1
my_robot.turn_left()
while True:
while my_robot.front_is_clear():
my_robot.move()
if turn:
if my_robot.right_is_clear()==False:
break
else:
turn_right()
my_robot.move()
turn_right()
turn=False
else:
if my_robot.left_is_clear()==False:
break
else:
my_robot.turn_left()
my_robot.move()
my_robot.turn_left()
turn=True
| 21 | 39 | reasoning | I used break to set the robot to stop at the last avenue. | cs1qa | null | null | null | null | null | Question:
Why does the while statement exit when there is a wall on the left and right?
Code:
from cs1robots import *
# Your code must work for empty worlds of all possible sizes.
create_world(avenues=4, streets=9)
# 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)
# ...
my_robot=Robot()
my_robot.set_trace('blue')
def turn_right():
for i in range(3):
my_robot.turn_left()
turn=1
my_robot.turn_left()
while True:
while my_robot.front_is_clear():
my_robot.move()
if turn:
if my_robot.right_is_clear()==False:
break
else:
turn_right()
my_robot.move()
turn_right()
turn=False
else:
if my_robot.left_is_clear()==False:
break
else:
my_robot.turn_left()
my_robot.move()
my_robot.turn_left()
turn=True
|
9 | 1 | TA | Please explain how you implemented the hand value! | 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(object):
def __init__(self, face, suit, value, hidden):
self.face = face
self.suit = suit
self.value = value
self.hidden = hidden
self.image = img_path + suit + '_' + face + '.png'
def create_deck(number = 1):
deck = []
for suit in suit_names:
for face in face_names:
deck.append(Card(face, suit, value[face_names.index(face)], False))
random.shuffle(deck)
return deck
"""
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'
"""
def hand_value(hand):
value = 0
for card in hand:
value += card.value
return value
"""
hand is a list including card objects
Compute the value of the cards in the list "hand"
"""
def card_string(card):
article = 'a '
if card.face in [8, 'Ace']: article = 'an '
return article + str(card.face) + ' of ' + card.suit
"""
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")
"""
def ask_yesno(prompt):
while True :
user_input = input(prompt)
if user_input == "y" :
return True
elif user_input == "n" :
return False
else :
print("I beg your pardon!")
"""
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.
"""
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()
def put(cards, x, y):
for i in range(len(cards)):
a = Image(img_path + cards[i].suit + '_' + cards[i].face + '.png')
if cards[i].hidden:
a = Image(img_path + 'Back.png')
a.moveTo(x + 30*i, y)
a.setDepth(100-i)
bj_board.add(a)
put(dealer, x0, y0)
put(player, x1, y1)
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()
| 45 | 49 | variable | 3. In the hand value, the card value is added. | cs1qa | null | null | null | null | null | Question:
Please explain how you implemented the hand value!
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(object):
def __init__(self, face, suit, value, hidden):
self.face = face
self.suit = suit
self.value = value
self.hidden = hidden
self.image = img_path + suit + '_' + face + '.png'
def create_deck(number = 1):
deck = []
for suit in suit_names:
for face in face_names:
deck.append(Card(face, suit, value[face_names.index(face)], False))
random.shuffle(deck)
return deck
"""
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'
"""
def hand_value(hand):
value = 0
for card in hand:
value += card.value
return value
"""
hand is a list including card objects
Compute the value of the cards in the list "hand"
"""
def card_string(card):
article = 'a '
if card.face in [8, 'Ace']: article = 'an '
return article + str(card.face) + ' of ' + card.suit
"""
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")
"""
def ask_yesno(prompt):
while True :
user_input = input(prompt)
if user_input == "y" :
return True
elif user_input == "n" :
return False
else :
print("I beg your pardon!")
"""
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.
"""
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()
def put(cards, x, y):
for i in range(len(cards)):
a = Image(img_path + cards[i].suit + '_' + cards[i].face + '.png')
if cards[i].hidden:
a = Image(img_path + 'Back.png')
a.moveTo(x + 30*i, y)
a.setDepth(100-i)
bj_board.add(a)
put(dealer, x0, y0)
put(player, x1, y1)
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()
|
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/trash2.wld" )
# load_world( "worlds/trash2.wld" )
hubo = Robot()
hubo.set_trace('red')
def turn_around():
hubo.turn_left()
hubo.turn_left()
while hubo.front_is_clear():
hubo.move()
while hubo.on_beeper():
hubo.pick_beeper()
turn_around()
while hubo.front_is_clear():
hubo.move()
for i in range(3):
hubo.turn_left()
hubo.move()
while hubo.carries_beepers():
hubo.drop_beeper()
turn_around()
hubo.move()
hubo.turn_left()
| 12 | 13 | reasoning | If the for statement is used, when the number of beepers changes, it cannot be retrieved accordingly, so I used the while statement. | 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/trash2.wld" )
# load_world( "worlds/trash2.wld" )
hubo = Robot()
hubo.set_trace('red')
def turn_around():
hubo.turn_left()
hubo.turn_left()
while hubo.front_is_clear():
hubo.move()
while hubo.on_beeper():
hubo.pick_beeper()
turn_around()
while hubo.front_is_clear():
hubo.move()
for i in range(3):
hubo.turn_left()
hubo.move()
while hubo.carries_beepers():
hubo.drop_beeper()
turn_around()
hubo.move()
hubo.turn_left()
|
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)
###########################################################################
| 44 | 57 | 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)
###########################################################################
|
4 | 0 | TA | What is count()? | from cs1robots import *
load_world('worlds/add34.wld')
hubo = Robot(beepers=100)
count = 0
def number():
num = []
for i in range(9):
hubo.move()
if hubo.on_beeper()==True:
k = count()
print(k)
num+=(count() * (10**(8-i)))
turn_back()
for i in range(9): hubo.move()
turn_back()
return num
def turn_back():
for i in range(2):
hubo.turn_left()
def turn_right():
for i in range(3):
hubo.turn_left()
def count():
k=0
while hubo.on_beeper():
hubo.pick_beeper()
for i in range(k):
hubo.drop_beeper()
k+=1
return k
def clear():
for i in range(9):
hubo.move()
while hubo.on_beeper():
hubo.pick_beeper()
turn_back()
for i in range(9):
hubo.move()
turn_back()
num1 = number()
clear()
hubo.turn_left()
hubo.move()
turn_right()
num2 = number()
clear()
print(num1, num2)
turn_right()
hubo.move()
hubo.turn_left()
n = num1 + num2
ans = []
for i in range(9):
temp = n % (10**(i+1))
temp = temp // (10**i)
ans.append(temp)
print(ans)
ans.reverse()
for i in range(9):
hubo.move()
for j in range(ans[i]):
hubo.drop_beeper()
| 28 | 35 | variable | This is a function that counts the number of beepers in place. | cs1qa | null | null | null | null | null | Question:
What is count()?
Code:
from cs1robots import *
load_world('worlds/add34.wld')
hubo = Robot(beepers=100)
count = 0
def number():
num = []
for i in range(9):
hubo.move()
if hubo.on_beeper()==True:
k = count()
print(k)
num+=(count() * (10**(8-i)))
turn_back()
for i in range(9): hubo.move()
turn_back()
return num
def turn_back():
for i in range(2):
hubo.turn_left()
def turn_right():
for i in range(3):
hubo.turn_left()
def count():
k=0
while hubo.on_beeper():
hubo.pick_beeper()
for i in range(k):
hubo.drop_beeper()
k+=1
return k
def clear():
for i in range(9):
hubo.move()
while hubo.on_beeper():
hubo.pick_beeper()
turn_back()
for i in range(9):
hubo.move()
turn_back()
num1 = number()
clear()
hubo.turn_left()
hubo.move()
turn_right()
num2 = number()
clear()
print(num1, num2)
turn_right()
hubo.move()
hubo.turn_left()
n = num1 + num2
ans = []
for i in range(9):
temp = n % (10**(i+1))
temp = temp // (10**i)
ans.append(temp)
print(ans)
ans.reverse()
for i in range(9):
hubo.move()
for j in range(ans[i]):
hubo.drop_beeper()
|
4 | 0 | TA | Can you explain how you solved the rounding of addition in Task 1? | from cs1robots import *
# Your code must work for all world files below.
load_world( "worlds/add34.wld" )
# load_world( "worlds/trash2.wld" )
hubo= Robot()
pocket = []
def turn_right():
for i in range(3):
hubo.turn_left()
def back():
turn_right()
turn_right()
def ini_pick():
n=0
while hubo.on_beeper() == bool(True):
hubo.pick_beeper()
n += 1
pocket.append(n)
def moveallpick():
hubo.move()
n=0
while hubo.on_beeper() == bool(True):
hubo.pick_beeper()
n += 1
pocket.append(n)
def straight():
while hubo.front_is_clear() == bool(True):
moveallpick()
def northfacing():
while hubo.facing_north() == bool(False):
hubo.turn_left()
def gountilend():
while hubo.front_is_clear() == bool(True):
hubo.move()
def returnn():
northfacing()
hubo.turn_left()
gountilend()
hubo.turn_left()
gountilend()
hubo.turn_left()
def dropall():
if pocket[0] == 0:
del pocket[0]
else:
for i in range(pocket[0]):
hubo.drop_beeper()
pocket[0] == pocket[0]-1
del pocket[0]
def movedrop():
dropall()
hubo.move()
def straight1():
while hubo.front_is_clear() == bool(True):
movedrop()
def round_up():
n=0
while hubo.on_beeper() == bool(True):
n +=1
hubo.pick_beeper()
p = n // 10
if (n // 10) >= 1:
for i in range(n%10):
hubo.drop_beeper()
hubo.move()
for i in range(n//10):
hubo.drop_beeper()
back()
hubo.move()
back()
else:
for i in range(n):
hubo.drop_beeper()
hubo.move()
def addition():
while hubo.front_is_clear() == bool(True):
round_up()
hubo.turn_left()
hubo.move()
turn_right()
ini_pick()
straight()
returnn()
straight1()
dropall()
back()
addition()
#print(pocket)
#print(len(pocket))
#print(hubo._beeper_bag) | 73 | 93 | code_explain | The round-up process of the addition itself created a function called round-up, so if the number of beepers stored in the picked up list is greater than 10, go one space next to it, drop the quotient divided by 10, and come back and drop the remainder divided by 10. | cs1qa | null | null | null | null | null | Question:
Can you explain how you solved the rounding of addition in Task 1?
Code:
from cs1robots import *
# Your code must work for all world files below.
load_world( "worlds/add34.wld" )
# load_world( "worlds/trash2.wld" )
hubo= Robot()
pocket = []
def turn_right():
for i in range(3):
hubo.turn_left()
def back():
turn_right()
turn_right()
def ini_pick():
n=0
while hubo.on_beeper() == bool(True):
hubo.pick_beeper()
n += 1
pocket.append(n)
def moveallpick():
hubo.move()
n=0
while hubo.on_beeper() == bool(True):
hubo.pick_beeper()
n += 1
pocket.append(n)
def straight():
while hubo.front_is_clear() == bool(True):
moveallpick()
def northfacing():
while hubo.facing_north() == bool(False):
hubo.turn_left()
def gountilend():
while hubo.front_is_clear() == bool(True):
hubo.move()
def returnn():
northfacing()
hubo.turn_left()
gountilend()
hubo.turn_left()
gountilend()
hubo.turn_left()
def dropall():
if pocket[0] == 0:
del pocket[0]
else:
for i in range(pocket[0]):
hubo.drop_beeper()
pocket[0] == pocket[0]-1
del pocket[0]
def movedrop():
dropall()
hubo.move()
def straight1():
while hubo.front_is_clear() == bool(True):
movedrop()
def round_up():
n=0
while hubo.on_beeper() == bool(True):
n +=1
hubo.pick_beeper()
p = n // 10
if (n // 10) >= 1:
for i in range(n%10):
hubo.drop_beeper()
hubo.move()
for i in range(n//10):
hubo.drop_beeper()
back()
hubo.move()
back()
else:
for i in range(n):
hubo.drop_beeper()
hubo.move()
def addition():
while hubo.front_is_clear() == bool(True):
round_up()
hubo.turn_left()
hubo.move()
turn_right()
ini_pick()
straight()
returnn()
straight1()
dropall()
back()
addition()
#print(pocket)
#print(len(pocket))
#print(hubo._beeper_bag) |
2 | 1 | TA | Please explain the plant2 function to task2. | from cs1robots import *
load_world('worlds/harvest3.wld')
hubo=Robot(beepers=64)
hubo.set_trace('blue')
def move():
hubo.move()
def cw():
for i in range(3):
hubo.turn_left()
def ccw():
hubo.turn_left()
def pick():
hubo.pick_beeper()
def harvest():
move()
if hubo.on_beeper()==True:
pick()
def plant():
move()
if hubo.on_beeper()==False:
hubo.drop_beeper()
def plant_line():
for i in range(5):
plant()
#harvest()
plant()
def plant_2():
plant_line()
ccw()
plant()
ccw()
plant_line()
cw()
for i in range (2):
plant_2()
plant()
cw()
plant_2() | 22 | 25 | variable | It is a code that goes to the right and picks up one space up and to the left. | cs1qa | null | null | null | null | null | Question:
Please explain the plant2 function to task2.
Code:
from cs1robots import *
load_world('worlds/harvest3.wld')
hubo=Robot(beepers=64)
hubo.set_trace('blue')
def move():
hubo.move()
def cw():
for i in range(3):
hubo.turn_left()
def ccw():
hubo.turn_left()
def pick():
hubo.pick_beeper()
def harvest():
move()
if hubo.on_beeper()==True:
pick()
def plant():
move()
if hubo.on_beeper()==False:
hubo.drop_beeper()
def plant_line():
for i in range(5):
plant()
#harvest()
plant()
def plant_2():
plant_line()
ccw()
plant()
ccw()
plant_line()
cw()
for i in range (2):
plant_2()
plant()
cw()
plant_2() |
4 | 3 | TA | At tasks 4 and 5
How did you handle when the sine function value was negative | import math
sin = math.sin
pi = math.pi
for i in range(41) :
x = float(i) / 40.0 * 2 * pi
character_count_per_line = int(40+40*sin(x)) # Change this line to print out sine curve correctly.
output_str = '#' * character_count_per_line
print (output_str) | 6 | 7 | code_explain | Based on 40
character_count_per_line is
Always be positive
Was | cs1qa | null | null | null | null | null | Question:
At tasks 4 and 5
How did you handle when the sine function value was negative
Code:
import math
sin = math.sin
pi = math.pi
for i in range(41) :
x = float(i) / 40.0 * 2 * pi
character_count_per_line = int(40+40*sin(x)) # Change this line to print out sine curve correctly.
output_str = '#' * character_count_per_line
print (output_str) |
3 | 4 | TA | Yes, lastly, in task5, please briefly explain how to classify into three colors! | from cs1media import *
# This code converts an image into a black & white poster.
threshold = 190
white = (255, 255, 255)
black = (0, 0, 0)
image = load_picture('./images/ironman.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 > threshold:
image.set(x, y, (255,255,0))
elif average_brightness < 90:
image.set(x, y, (0,0,255))
else:
image.set(x, y, (0,255,0))
image.show() | 15 | 20 | code_explain | If the average brightness is less than 95, it is classified as blue, 95 to 190 is green, and if it is greater than 190, it is classified as yellow. | cs1qa | null | null | null | null | null | Question:
Yes, lastly, in task5, please briefly explain how to classify into three colors!
Code:
from cs1media import *
# This code converts an image into a black & white poster.
threshold = 190
white = (255, 255, 255)
black = (0, 0, 0)
image = load_picture('./images/ironman.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 > threshold:
image.set(x, y, (255,255,0))
elif average_brightness < 90:
image.set(x, y, (0,0,255))
else:
image.set(x, y, (0,255,0))
image.show() |
5 | 0 | TA | How did you make sure that the code doesn't finish and keeps receiving inputs in the bank problem? | 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 ', balance, ' 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 withdrawn ", money, ' won' )
print('But you only have ', balance, ' won')
else:
print("You've withdraw ", money, ' won')
balance=balance-money
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=='d':
money=input('How much do you want to deposit? ')
money=int(money)
deposit(money)
elif process=='w':
money=input('How much do you want to withdraw? ')
money=int(money)
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')
pass
#################
bank()
| 44 | 45 | code_explain | I wrote while True at the top to keep it running, and to escape when process=''. | cs1qa | null | null | null | null | null | Question:
How did you make sure that the code doesn't finish and keeps receiving inputs in the bank problem?
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 ', balance, ' 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 withdrawn ", money, ' won' )
print('But you only have ', balance, ' won')
else:
print("You've withdraw ", money, ' won')
balance=balance-money
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=='d':
money=input('How much do you want to deposit? ')
money=int(money)
deposit(money)
elif process=='w':
money=input('How much do you want to withdraw? ')
money=int(money)
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')
pass
#################
bank()
|
2 | 4 | TA | Please explain how you checked the termination condition of task5 | from cs1robots import *
# 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)
# ...
my_robot = Robot(beepers=1)
my_robot.set_trace('blue')
my_robot.set_pause(0.01)
def turn_right():
for i in range(3):
my_robot.turn_left()
def turn_left_larger():
my_robot.turn_left()
my_robot.move()
my_robot.turn_left()
def turn_right_larger():
turn_right()
my_robot.move()
turn_right()
def go_straight():
while my_robot.front_is_clear():
my_robot.move()
my_robot.turn_left()
while not my_robot.on_beeper():
go_straight()
if my_robot.right_is_clear():
turn_right_larger()
else:
my_robot.drop_beeper()
go_straight()
if my_robot.on_beeper():
pass
elif my_robot.left_is_clear():
turn_left_larger()
else:
my_robot.drop_beeper()
my_robot.pick_beeper() | 36 | 48 | code_explain | Originally, it would be good to solve the bias of avenues and streets, but it was not a form of entering the size, so I decided to use beeper.
First, I thought of running the while statement by looking at go_straight/turn_right_larger/go_straight/turn_left_larger as a repeat unit.
I made the beeper drop if the two functions didn't happen to prevent clogging in turn_right_larger and clogging in turn_left_larger depending on the avenues' dominance.
Then, in the whole while statement, you can escape the while statement when it is blocked, so on_beeper is a condition, and when turn_right_larger is blocked, a pass part is written to exclude the case that turn_left_larger is executed immediately. | cs1qa | null | null | null | null | null | Question:
Please explain how you checked the termination condition of task5
Code:
from cs1robots import *
# 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)
# ...
my_robot = Robot(beepers=1)
my_robot.set_trace('blue')
my_robot.set_pause(0.01)
def turn_right():
for i in range(3):
my_robot.turn_left()
def turn_left_larger():
my_robot.turn_left()
my_robot.move()
my_robot.turn_left()
def turn_right_larger():
turn_right()
my_robot.move()
turn_right()
def go_straight():
while my_robot.front_is_clear():
my_robot.move()
my_robot.turn_left()
while not my_robot.on_beeper():
go_straight()
if my_robot.right_is_clear():
turn_right_larger()
else:
my_robot.drop_beeper()
go_straight()
if my_robot.on_beeper():
pass
elif my_robot.left_is_clear():
turn_left_larger()
else:
my_robot.drop_beeper()
my_robot.pick_beeper() |
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)
###########################################################################
|
8 | 1 | TA | And why did you add the 18th line of the 13th ministry in task2? | f=open("average-latitude-longitude-countries.csv", "r")
c=0
List_all_value=[]
for line in f:
if c==0:
c+=1
else:
lstrip=line.strip()
l=lstrip.split(",")
if len(l)==5:
l[1]=l[1]+","+l[2]
del l[2]
for i in range(2):
s=l[i]
new_s=""
for j in range(len(s)-2):
new_s=new_s+s[j+1]
l[i]=new_s
List_all_value.append(l)
code_name=[]
code_coordinate=[]
south_countries=[]
for i in range(len(List_all_value)):
code_name.append((List_all_value[i][0], List_all_value[i][1]))
code_coordinate.append((List_all_value[i][0], (List_all_value[i][2], List_all_value[i][3])))
if(float(List_all_value[i][2])<0):
south_countries.append(List_all_value[i][1])
print(code_name)
print(code_coordinate)
for k in range(len(south_countries)):
print(south_countries[k])
Code=input("Enter country code: ")
for i in range(len(List_all_value)):
if List_all_value[i][0]==Code:
print(List_all_value[i][1])
break
f.close() | 12 | 17 | reasoning | I removed the original files because "" was added to the code or country name. | cs1qa | null | null | null | null | null | Question:
And why did you add the 18th line of the 13th ministry in task2?
Code:
f=open("average-latitude-longitude-countries.csv", "r")
c=0
List_all_value=[]
for line in f:
if c==0:
c+=1
else:
lstrip=line.strip()
l=lstrip.split(",")
if len(l)==5:
l[1]=l[1]+","+l[2]
del l[2]
for i in range(2):
s=l[i]
new_s=""
for j in range(len(s)-2):
new_s=new_s+s[j+1]
l[i]=new_s
List_all_value.append(l)
code_name=[]
code_coordinate=[]
south_countries=[]
for i in range(len(List_all_value)):
code_name.append((List_all_value[i][0], List_all_value[i][1]))
code_coordinate.append((List_all_value[i][0], (List_all_value[i][2], List_all_value[i][3])))
if(float(List_all_value[i][2])<0):
south_countries.append(List_all_value[i][1])
print(code_name)
print(code_coordinate)
for k in range(len(south_countries)):
print(south_countries[k])
Code=input("Enter country code: ")
for i in range(len(List_all_value)):
if List_all_value[i][0]==Code:
print(List_all_value[i][1])
break
f.close() |
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()
|
9 | 1 | student | What do true and false mean in state? | 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]
decks=[]
bj_board = Canvas(600, 400, 'dark green', 'Black Jack 101')
"""
Define the Card class
"""
class Card():
def __init__(self,suit,face,value,img,state):
self.suit=suit
self.face=face
self.value=value
self.img=img
self.state=state
def create_deck(number = 1):
for i in range(4):
for k in range(13):
temp=Card(suit_names[i],face_names[k],value[k],img_path+suit_names[i]+'_'+face_names[k]+'.png',False)
# temp.__init__()
decks.append(temp)
random.shuffle(decks)
return decks
"""
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'
"""
def hand_value(hand):
"""
hand is a list including card objects
Compute the value of the cards in the list "hand"
"""
sum=0
for i in range(len(hand)):
sum+=hand[i].value
return 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")
"""
a=card.face+" of "+card.suit
return a
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.
"""
a=input()
if a=='y':
return True
elif a=='n':
return False
else:
print("I beg your pardon!")
return ask_yesno("Would you like another card? (y/n) ")
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()
a=Image('./images/Back.png')
for i in range(len(dealer)):
if dealer[i].state==False:
a.moveTo(x0+20*i,y0)
a.setDepth(30-i)
bj_board.add(a)
elif dealer[i].state==True:
dealer[i].img.moveTo(x0+20*i,y0)
dealer[i].img.setDepth(30-i)
bj_board.add(dealer[i].img)
for i in range(len(player)):
if player[i].state==False:
a.moveTo(x1,y1)
a.setDepth(30-i)
bj_board.add(a)
elif player[i].state==True:
player[i].img.moveTo(x0+20*i,y0)
player[i].img.setDepth(30-i)
bj_board.add(player[i].img)
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()
| 23 | 23 | code_understanding | Is it to evaluate whether to turn over or show the front side based on that?
is | cs1qa | null | null | null | null | null | Question:
What do true and false mean in state?
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]
decks=[]
bj_board = Canvas(600, 400, 'dark green', 'Black Jack 101')
"""
Define the Card class
"""
class Card():
def __init__(self,suit,face,value,img,state):
self.suit=suit
self.face=face
self.value=value
self.img=img
self.state=state
def create_deck(number = 1):
for i in range(4):
for k in range(13):
temp=Card(suit_names[i],face_names[k],value[k],img_path+suit_names[i]+'_'+face_names[k]+'.png',False)
# temp.__init__()
decks.append(temp)
random.shuffle(decks)
return decks
"""
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'
"""
def hand_value(hand):
"""
hand is a list including card objects
Compute the value of the cards in the list "hand"
"""
sum=0
for i in range(len(hand)):
sum+=hand[i].value
return 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")
"""
a=card.face+" of "+card.suit
return a
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.
"""
a=input()
if a=='y':
return True
elif a=='n':
return False
else:
print("I beg your pardon!")
return ask_yesno("Would you like another card? (y/n) ")
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()
a=Image('./images/Back.png')
for i in range(len(dealer)):
if dealer[i].state==False:
a.moveTo(x0+20*i,y0)
a.setDepth(30-i)
bj_board.add(a)
elif dealer[i].state==True:
dealer[i].img.moveTo(x0+20*i,y0)
dealer[i].img.setDepth(30-i)
bj_board.add(dealer[i].img)
for i in range(len(player)):
if player[i].state==False:
a.moveTo(x1,y1)
a.setDepth(30-i)
bj_board.add(a)
elif player[i].state==True:
player[i].img.moveTo(x0+20*i,y0)
player[i].img.setDepth(30-i)
bj_board.add(player[i].img)
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()
|
1 | 0 | TA | You wrote well with the for statement in Task1, but is there any reason you couldn't put lines 29~34 below in the for statement? | from cs1robots import*
create_world()
a=Robot()
def stride():
for i in range(9):
a.move()
def turn_right():
for i in range(3):
a.turn_left()
a.set_trace('blue')
for i in range(4):
a.turn_left()
stride()
turn_right()
a.move()
turn_right()
stride()
a.turn_left()
a.move()
a.turn_left()
stride()
turn_right()
a.move()
turn_right()
stride() | 28 | 33 | reasoning | If I try to do 5 repetitions, I hit the wall in the last step and cut it. | cs1qa | null | null | null | null | null | Question:
You wrote well with the for statement in Task1, but is there any reason you couldn't put lines 29~34 below in the for statement?
Code:
from cs1robots import*
create_world()
a=Robot()
def stride():
for i in range(9):
a.move()
def turn_right():
for i in range(3):
a.turn_left()
a.set_trace('blue')
for i in range(4):
a.turn_left()
stride()
turn_right()
a.move()
turn_right()
stride()
a.turn_left()
a.move()
a.turn_left()
stride()
turn_right()
a.move()
turn_right()
stride() |
1 | 1 | TA | Briefly explain the variable count in task 2! | from cs1robots import *
load_world('worlds/hurdles1.wld')
hubo=Robot()
hubo.set_trace('blue')
hubo.move()
hubo.turn_left()
def turn_right():
for i in range(3):
hubo.turn_left()
def r_uturn():
turn_right()
hubo.move()
turn_right()
def l_uturn():
hubo.turn_left()
hubo.move()
hubo.turn_left()
count=0
while 1:
if count==7:
hubo.move()
hubo.turn_left()
hubo.move()
break
if count%2==0:
hubo.move()
r_uturn()
count+=1
else:
hubo.move()
l_uturn()
count+=1
hubo.pick_beeper() | 19 | 33 | variable | The variable called count in task 2 is
As a variable that makes the condition for exiting the while statement
acts like a flag
If a certain function is repeatedly executed and executed 9 times, the while statement can be exited. | cs1qa | null | null | null | null | null | Question:
Briefly explain the variable count in task 2!
Code:
from cs1robots import *
load_world('worlds/hurdles1.wld')
hubo=Robot()
hubo.set_trace('blue')
hubo.move()
hubo.turn_left()
def turn_right():
for i in range(3):
hubo.turn_left()
def r_uturn():
turn_right()
hubo.move()
turn_right()
def l_uturn():
hubo.turn_left()
hubo.move()
hubo.turn_left()
count=0
while 1:
if count==7:
hubo.move()
hubo.turn_left()
hubo.move()
break
if count%2==0:
hubo.move()
r_uturn()
count+=1
else:
hubo.move()
l_uturn()
count+=1
hubo.pick_beeper() |
4 | 3 | TA | Task 4: Why do you need +1 and *40 in line 8? | import math
sin = math.sin
pi = math.pi
for i in range(41) :
x = float(i) / 40.0 * 2 * pi
character_count_per_line = int((sin(x)+1)*40) # Change this line to print out sine curve correctly.
output_str = '#' * character_count_per_line
print (output_str) | 7 | 7 | reasoning | Task 4: Since we used a method of expressing # by plotting positive integer values, it was necessary to change the expressed values so that they are all positive and meaningful integers. | cs1qa | null | null | null | null | null | Question:
Task 4: Why do you need +1 and *40 in line 8?
Code:
import math
sin = math.sin
pi = math.pi
for i in range(41) :
x = float(i) / 40.0 * 2 * pi
character_count_per_line = int((sin(x)+1)*40) # Change this line to print out sine curve correctly.
output_str = '#' * character_count_per_line
print (output_str) |
1 | 4 | TA | There was a way to pick diagonally, but why would you let them pick beepers while walking vertically? | 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()
def harvest(x):
for i in range(x):
hubo.pick_beeper()
hubo.move()
hubo.move()
hubo.pick_beeper()
def up_right():
for i in range(2):
hubo.move()
turn_right()
def down_right():
for i in range(2):
hubo.move()
hubo.turn_left()
def right_up():
for i in range(2):
hubo.turn_left()
hubo.move()
def right_down():
for i in range(2):
turn_right()
hubo.move()
hubo.turn_left()
for i in range (6):
hubo.move()
hubo.pick_beeper()
up_right()
harvest(1)
down_right()
harvest(2)
up_right()
harvest(3)
down_right()
harvest(4)
up_right()
harvest(5)
right_up()
harvest(4)
right_down()
harvest(3)
right_up()
harvest(2)
right_down()
harvest(1)
right_up()
hubo.pick_beeper() | 35 | 53 | reasoning | because I counted the steps of robot walking diagonally and realize that they are the same as this method walking vertically | cs1qa | null | null | null | null | null | Question:
There was a way to pick diagonally, but why would you let them pick beepers while walking vertically?
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()
def harvest(x):
for i in range(x):
hubo.pick_beeper()
hubo.move()
hubo.move()
hubo.pick_beeper()
def up_right():
for i in range(2):
hubo.move()
turn_right()
def down_right():
for i in range(2):
hubo.move()
hubo.turn_left()
def right_up():
for i in range(2):
hubo.turn_left()
hubo.move()
def right_down():
for i in range(2):
turn_right()
hubo.move()
hubo.turn_left()
for i in range (6):
hubo.move()
hubo.pick_beeper()
up_right()
harvest(1)
down_right()
harvest(2)
up_right()
harvest(3)
down_right()
harvest(4)
up_right()
harvest(5)
right_up()
harvest(4)
right_down()
harvest(3)
right_up()
harvest(2)
right_down()
harvest(1)
right_up()
hubo.pick_beeper() |
2 | 0 | TA | What does the zigzag function in task1 do? | 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():
if hubo.on_beeper():
hubo.pick_beeper()
hubo.move()
def zigzag():
for i in range(5):
harvest()
hubo.turn_left()
harvest()
hubo.turn_left()
for i in range(5):
harvest()
#
hubo.move()
zigzag()
turn_right()
harvest()
turn_right()
zigzag()
turn_right()
harvest()
turn_right()
zigzag()
#harvest_more() | 14 | 21 | variable | Going all the time, picking up all the beepers
Picking up the beeper
It comes back all the time and picks up the beeper
Is a function | cs1qa | null | null | null | null | null | Question:
What does the zigzag function in task1 do?
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():
if hubo.on_beeper():
hubo.pick_beeper()
hubo.move()
def zigzag():
for i in range(5):
harvest()
hubo.turn_left()
harvest()
hubo.turn_left()
for i in range(5):
harvest()
#
hubo.move()
zigzag()
turn_right()
harvest()
turn_right()
zigzag()
turn_right()
harvest()
turn_right()
zigzag()
#harvest_more() |
2 | 3 | TA | What is task4's one_cycle function? | from cs1robots import *
load_world('worlds/harvest4.wld')
hubo = Robot()
hubo.set_trace('blue')
def turn_right():
for i in range(3):
hubo.turn_left()
def one_length():
for i in range(5):
while hubo.on_beeper():
hubo.pick_beeper()
hubo.move()
while hubo.on_beeper():
hubo.pick_beeper()
def one_cycle():
one_length()
hubo.turn_left()
hubo.move()
hubo.turn_left()
one_length()
hubo.move()
for i in range(2):
one_cycle()
turn_right()
hubo.move()
turn_right()
one_cycle() | 18 | 23 | variable | This is a function that makes it (back and forth) twice horizontally | cs1qa | null | null | null | null | null | Question:
What is task4's one_cycle function?
Code:
from cs1robots import *
load_world('worlds/harvest4.wld')
hubo = Robot()
hubo.set_trace('blue')
def turn_right():
for i in range(3):
hubo.turn_left()
def one_length():
for i in range(5):
while hubo.on_beeper():
hubo.pick_beeper()
hubo.move()
while hubo.on_beeper():
hubo.pick_beeper()
def one_cycle():
one_length()
hubo.turn_left()
hubo.move()
hubo.turn_left()
one_length()
hubo.move()
for i in range(2):
one_cycle()
turn_right()
hubo.move()
turn_right()
one_cycle() |
9 | 0 | student | what are s and v for? | # 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
correct_list = range(24)
class Card:
def _init_(self):
pass
def initialize():
# initialize cards
for i in range(6):
for k in range(4):
ncard = Card()
ncard.img = Image(path + names[i])
ncard.name = names[i]
# img = Image(path + names[i])
# temp_tuple = (img, names[i])
cards.append(ncard)
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)):
################################################################
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 != num2:
if num2 not in correct_list:
if num1 not in correct_list:
if 0 <= num1 <= 23:
if 0 <= num2 <= 23:
return True
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.
###########################################################################
correct_list.append(num1)
correct_list.append(num2)
print_cards()
if cards[num1][1] == cards[num2][1]:
print_cards()
return True
correct_list.remove(num2)
correct_list.remove(num1)
print_cards()
return False
initialize()
print_cards()
time.sleep(3)
correct_list = []
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):
tries = tries + 1
continue
if check(num1, num2):
print("Correct!")
else:
print("Wrong!")
tries = tries + 1
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
##################################################################
| null | null | code_understanding | that is just sample like name
you should change according to your codes | cs1qa | null | null | null | null | null | Question:
what are s and v for?
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
correct_list = range(24)
class Card:
def _init_(self):
pass
def initialize():
# initialize cards
for i in range(6):
for k in range(4):
ncard = Card()
ncard.img = Image(path + names[i])
ncard.name = names[i]
# img = Image(path + names[i])
# temp_tuple = (img, names[i])
cards.append(ncard)
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)):
################################################################
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 != num2:
if num2 not in correct_list:
if num1 not in correct_list:
if 0 <= num1 <= 23:
if 0 <= num2 <= 23:
return True
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.
###########################################################################
correct_list.append(num1)
correct_list.append(num2)
print_cards()
if cards[num1][1] == cards[num2][1]:
print_cards()
return True
correct_list.remove(num2)
correct_list.remove(num1)
print_cards()
return False
initialize()
print_cards()
time.sleep(3)
correct_list = []
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):
tries = tries + 1
continue
if check(num1, num2):
print("Correct!")
else:
print("Wrong!")
tries = tries + 1
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
##################################################################
|
5 | 1 | TA | Then in task2
Which two objects operate separately in animation? | from cs1graphics import *
from time import sleep
canvas=Canvas(800,800)
canvas.setBackgroundColor('light blue')
boat=Layer()
row1=Rectangle(10,70,Point(60,0))
row2=Rectangle(10,70,Point(-20,0))
def draw_animal():
# Implement this function.
body=Polygon(Point(-100,-60),Point(140,-60),Point(100,0),Point(-100,0))
body.setFillColor('darkgray')
boat.add(body)
pole=Rectangle(10,70,Point(20,-95))
pole.setFillColor('brown')
flag=Rectangle(40,20,Point(0,-120))
flag.setFillColor('blue')
boat.add(flag)
boat.add(pole)
row1.setFillColor('brown')
row2.setFillColor('brown')
boat.add(row1)
boat.add(row2)
boat.moveTo(100,700)
canvas.add(boat)
pass
def show_animation():
# Implement this function.
for i in range(90):
boat.move(5,0)
for j in range(45):
row1.rotate(1)
row2.rotate(1)
sleep(0.01)
row1.rotate(-45)
row2.rotate(-45)
sleep(0.001)
pass
draw_animal()
show_animation() | 26 | 36 | code_explain | The whole boat and the rowing motion when the boat is moving were made to move separately | cs1qa | null | null | null | null | null | Question:
Then in task2
Which two objects operate separately in animation?
Code:
from cs1graphics import *
from time import sleep
canvas=Canvas(800,800)
canvas.setBackgroundColor('light blue')
boat=Layer()
row1=Rectangle(10,70,Point(60,0))
row2=Rectangle(10,70,Point(-20,0))
def draw_animal():
# Implement this function.
body=Polygon(Point(-100,-60),Point(140,-60),Point(100,0),Point(-100,0))
body.setFillColor('darkgray')
boat.add(body)
pole=Rectangle(10,70,Point(20,-95))
pole.setFillColor('brown')
flag=Rectangle(40,20,Point(0,-120))
flag.setFillColor('blue')
boat.add(flag)
boat.add(pole)
row1.setFillColor('brown')
row2.setFillColor('brown')
boat.add(row1)
boat.add(row2)
boat.moveTo(100,700)
canvas.add(boat)
pass
def show_animation():
# Implement this function.
for i in range(90):
boat.move(5,0)
for j in range(45):
row1.rotate(1)
row2.rotate(1)
sleep(0.01)
row1.rotate(-45)
row2.rotate(-45)
sleep(0.001)
pass
draw_animal()
show_animation() |
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() |
6 | 2 | TA | How did you implement the two cards to show a picture when checking two cards? | 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(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)):
################################################################
if correct_list.count(i) != 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):
n = 0
if 0<= num1 <len(num_pads) and 0<= num2 <len(num_pads):
n +=1
if num1 != num2:
n +=1
if correct_list.count(num1) == 0 and correct_list.count(num2) == 0:
n +=1
###########################################################################
# 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 n == 3:
return True
else:
return False
def check(num1, num2):
a=len(correct_list)
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
################################################################
if correct_list.count(i) != 0 or i == num1 or i == num2: # 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)
if cards[num1][1] == cards[num2][1]:
correct_list.append(num1)
correct_list.append(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 a+2 == len(correct_list):
return True
else:
return False
initialize()
print_cards()
print("### Welcome to the Python Memento game!!! ###")
canvas.clear()
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.add(cards[i][0])
w += 100
if w % 600 == 0:
w = 0
h += 130
time.sleep(1)
print_cards()
###############################################################################
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!")
if len(correct_list)==24:
break
else:
tries =tries+1
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
###########################################################################
| 88 | 101 | code_explain | I modified the code of the print_cards function, so that the photos in the correct_list and or when num1 and num2 are displayed in the condition that the photos are visible! | cs1qa | null | null | null | null | null | Question:
How did you implement the two cards to show a picture when checking two cards?
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(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)):
################################################################
if correct_list.count(i) != 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):
n = 0
if 0<= num1 <len(num_pads) and 0<= num2 <len(num_pads):
n +=1
if num1 != num2:
n +=1
if correct_list.count(num1) == 0 and correct_list.count(num2) == 0:
n +=1
###########################################################################
# 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 n == 3:
return True
else:
return False
def check(num1, num2):
a=len(correct_list)
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
################################################################
if correct_list.count(i) != 0 or i == num1 or i == num2: # 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)
if cards[num1][1] == cards[num2][1]:
correct_list.append(num1)
correct_list.append(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 a+2 == len(correct_list):
return True
else:
return False
initialize()
print_cards()
print("### Welcome to the Python Memento game!!! ###")
canvas.clear()
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.add(cards[i][0])
w += 100
if w % 600 == 0:
w = 0
h += 130
time.sleep(1)
print_cards()
###############################################################################
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!")
if len(correct_list)==24:
break
else:
tries =tries+1
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
###########################################################################
|
2 | 0 | TA | What does Task 1's move_pick function do? | 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 move_pick():
if hubo.on_beeper():
hubo.pick_beeper()
hubo.move()
else:
hubo.move()
def zig_zag():
for i in range(5):
move_pick()
hubo.turn_left()
move_pick()
hubo.turn_left()
for i in range(5):
move_pick()
turn_right()
move_pick()
turn_right()
for i in range(3):
zig_zag()
| 8 | 13 | variable | Where there is no beeper, it just goes away, and where there is a beeper, it picks up the beeper. | cs1qa | null | null | null | null | null | Question:
What does Task 1's move_pick function do?
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 move_pick():
if hubo.on_beeper():
hubo.pick_beeper()
hubo.move()
else:
hubo.move()
def zig_zag():
for i in range(5):
move_pick()
hubo.turn_left()
move_pick()
hubo.turn_left()
for i in range(5):
move_pick()
turn_right()
move_pick()
turn_right()
for i in range(3):
zig_zag()
|
5 | 0 | TA | Can you explain the function of the 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
global balance
balance = balance + money
#################
### implement ###
#################
# Do something on here !
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
global balance
if balance >= money:
balance = balance - money
else:
print("But you only have",balance,"won")
#################
### implement ###
#################
# Do something on here !
pass
#################
def bank() :
# Input : (None) No Input
# Output : (None) No Output
balance = 0
while True:
process = input("Deposit(d) or withdrawal(w) or balance check(c)? ")
if process == '':
break
elif process == 'd':
money_deposit = int(input("How much do you want to deposit? "))
print("You deposited",money_deposit,"won")
deposit(money_deposit)
elif process == 'w':
money_withdraw = int(input("how much do you want to withdraw? "))
print("You've withdraw",money_withdraw,"won")
withdrawal(money_withdraw)
elif process == 'c':
print("Your current balance is", balance,"won")
else:
print("Please, press d or w 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()
| 2 | 31 | variable | In the framework of the problem, the balance is defined outside.
In order to modify the variable inside the function, it is not a local variable, so you need to modify the global variable using global
So I used the global keyword to modify the global variable defined outside as a local variable in the inner function. | cs1qa | null | null | null | null | null | Question:
Can you explain the function of the 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
global balance
balance = balance + money
#################
### implement ###
#################
# Do something on here !
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
global balance
if balance >= money:
balance = balance - money
else:
print("But you only have",balance,"won")
#################
### implement ###
#################
# Do something on here !
pass
#################
def bank() :
# Input : (None) No Input
# Output : (None) No Output
balance = 0
while True:
process = input("Deposit(d) or withdrawal(w) or balance check(c)? ")
if process == '':
break
elif process == 'd':
money_deposit = int(input("How much do you want to deposit? "))
print("You deposited",money_deposit,"won")
deposit(money_deposit)
elif process == 'w':
money_withdraw = int(input("how much do you want to withdraw? "))
print("You've withdraw",money_withdraw,"won")
withdrawal(money_withdraw)
elif process == 'c':
print("Your current balance is", balance,"won")
else:
print("Please, press d or w 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()
|
4 | 1 | TA | Explain the is_triangle function! | def is_triangle(a, b, c):
if (a+b)<=c or (a+c)<=b or (b+c)<=a:
return False
else:
return True
a = float(input('Side a: '))
print('Value of a is', a)
b = float(input('Side b: '))
print('Value of b is', b)
c = float(input('Side c: '))
print('Value of c is', c)
if is_triangle(a, b, c)==False:
print('NO')
else:
print('YES') | 0 | 4 | variable | is_triangle function is a function that returns the lengths of the sides of the input float value according to the triangle test method to return True when a triangle is established, and False when not. | cs1qa | null | null | null | null | null | Question:
Explain the is_triangle function!
Code:
def is_triangle(a, b, c):
if (a+b)<=c or (a+c)<=b or (b+c)<=a:
return False
else:
return True
a = float(input('Side a: '))
print('Value of a is', a)
b = float(input('Side b: '))
print('Value of b is', b)
c = float(input('Side c: '))
print('Value of c is', c)
if is_triangle(a, b, c)==False:
print('NO')
else:
print('YES') |
4 | 0 | TA | How did you implement the addition in step 1? | import cs1robots
def main():
cs1robots.load_world("worlds/add34.wld")
hubo = cs1robots.Robot(beepers=100)
def turn_right():
for _ in range(3):
hubo.turn_left()
return None
def back():
for _ in range(2):
hubo.turn_left()
return None
def get():
cnt = 0
while(hubo.on_beeper()):
cnt+=1
hubo.pick_beeper()
return cnt
def read():
sum = 0
while(True):
sum = 10 * sum + get()
if(not hubo.front_is_clear()):
break
hubo.move()
back()
while(hubo.front_is_clear()):
hubo.move()
return sum
def drop(cnt):
for _ in range(cnt):
hubo.drop_beeper()
def write(x):
while(hubo.front_is_clear()):
hubo.move()
back()
while(hubo.front_is_clear()):
drop(x%10)
x//=10
hubo.move()
x=read()
turn_right()
hubo.move()
turn_right()
y=read()
x += y
hubo.turn_left()
hubo.move()
hubo.turn_left()
write(x)
main() | 48 | 60 | code_explain | First, we searched for the numbers in the same line through the read() function and found how many numbers were written in this line.
I wrote a code that read() for line 1 and line 2, and then writes the sum of the two numbers in line 1 through write() | cs1qa | null | null | null | null | null | Question:
How did you implement the addition in step 1?
Code:
import cs1robots
def main():
cs1robots.load_world("worlds/add34.wld")
hubo = cs1robots.Robot(beepers=100)
def turn_right():
for _ in range(3):
hubo.turn_left()
return None
def back():
for _ in range(2):
hubo.turn_left()
return None
def get():
cnt = 0
while(hubo.on_beeper()):
cnt+=1
hubo.pick_beeper()
return cnt
def read():
sum = 0
while(True):
sum = 10 * sum + get()
if(not hubo.front_is_clear()):
break
hubo.move()
back()
while(hubo.front_is_clear()):
hubo.move()
return sum
def drop(cnt):
for _ in range(cnt):
hubo.drop_beeper()
def write(x):
while(hubo.front_is_clear()):
hubo.move()
back()
while(hubo.front_is_clear()):
drop(x%10)
x//=10
hubo.move()
x=read()
turn_right()
hubo.move()
turn_right()
y=read()
x += y
hubo.turn_left()
hubo.move()
hubo.turn_left()
write(x)
main() |
2 | 0 | TA | Please explain task1 go function | 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 go():
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
for i in range(6):
go()
hubo.turn_left()
def right():
go()
turn_right()
for i in range(5):
go()
hubo.turn_left()
def left():
go()
hubo.turn_left()
for i in range(5):
go()
turn_right()
left()
right()
left()
right()
left()
hubo.turn_left() | 9 | 12 | variable | In task1, the go function is a function to proceed forward and if there is a coin, give it together. | cs1qa | null | null | null | null | null | Question:
Please explain task1 go function
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 go():
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
for i in range(6):
go()
hubo.turn_left()
def right():
go()
turn_right()
for i in range(5):
go()
hubo.turn_left()
def left():
go()
hubo.turn_left()
for i in range(5):
go()
turn_right()
left()
right()
left()
right()
left()
hubo.turn_left() |
3 | 4 | TA | In the case of Task 5, if average_brightness is 150, what color is the corresponding pixel? | from cs1media import *
# This code converts an image into a black & white poster.
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 > 150:
image.set(x, y, yellow)
elif average_brightness < 150 and average_brightness >100:
image.set(x,y, green)
else:
image.set(x, y, blue)
image.show() | 15 | 20 | variable | In Task 5, it was modified to be yellow at 150. | cs1qa | null | null | null | null | null | Question:
In the case of Task 5, if average_brightness is 150, what color is the corresponding pixel?
Code:
from cs1media import *
# This code converts an image into a black & white poster.
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 > 150:
image.set(x, y, yellow)
elif average_brightness < 150 and average_brightness >100:
image.set(x,y, green)
else:
image.set(x, y, blue)
image.show() |
6 | 2 | student | On top of return False in the check of the original code
With print_cards()
Does it mean to share the printouts in some cases? | 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
random.suffle(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%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.
###########################################################################
if int(num1) == int(num2):
return False
elif int(num1) > 23 or int(num2) > 23 :
return False
elif int(num1) < 0 or int(num2) < 0 :
return False
elif int(num1) in correct_list or int(num2) in correct_list :
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.
###########################################################################
n1 = int(num1)
n2 = int(num2)
if cards[n1] == cards[n2] :
correct_list.append(n1)
correct_list.append(n2)
return True
else :
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)
global tries
tries = tries + 1
###########################################################################
| 45 | 51 | code_understanding | Yes, it seems like that, when it was wrong and when it was correct
Because I have to show a different screen
According to the conditions of showing photos in `print_cards`
Separate cases appropriately and call `print_cards` for each. | cs1qa | null | null | null | null | null | Question:
On top of return False in the check of the original code
With print_cards()
Does it mean to share the printouts in some cases?
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
random.suffle(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%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.
###########################################################################
if int(num1) == int(num2):
return False
elif int(num1) > 23 or int(num2) > 23 :
return False
elif int(num1) < 0 or int(num2) < 0 :
return False
elif int(num1) in correct_list or int(num2) in correct_list :
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.
###########################################################################
n1 = int(num1)
n2 = int(num2)
if cards[n1] == cards[n2] :
correct_list.append(n1)
correct_list.append(n2)
return True
else :
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)
global tries
tries = tries + 1
###########################################################################
|
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]) | 17 | 18 | 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]) |
10 | 0 | student | Why attach (object) when creating a class? | 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(800, 600)
_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)
"""
_scene.setBackgroundColor('light blue')
road=Rectangle(805, 305)
_scene.add(road)
road.setFillColor('gray')
road.setBorderColor('yellow')
road.setBorderWidth(5)
road.moveTo(400, 550)
tree=Layer()
trunk1=Rectangle(80, 150)
trunk1.moveTo(150, 325)
trunk1.setFillColor('brown')
trunk1.setBorderColor('brown')
tree.add(trunk1)
leaf1=Ellipse(175, 200)
leaf1.moveTo(150, 200)
leaf1.setFillColor('light green')
leaf1.setBorderColor('light green')
tree.add(leaf1)
trunk2=Rectangle(80, 200)
trunk2.moveTo(600, 300)
trunk2.setFillColor('brown')
trunk2.setBorderColor('brown')
tree.add(trunk2)
leaf2=Ellipse(175, 180)
leaf2.moveTo(600, 175)
leaf2.setFillColor('green')
leaf2.setBorderColor('green')
tree.add(leaf2)
_scene.add(tree)
"""
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 Car(object):
def __init__(self, color):
car=Layer()
car1=Rectangle(200, 100)
car1.setFillColor(color)
car1.setBorderColor(color)
car1.moveTo(400, 300)
car.add(car1)
car2=Rectangle(400, 100)
car2.setFillColor(color)
car2.setBorderColor(color)
car2.moveTo(400, 400)
car.add(car2)
tire1=Circle(50)
tire1.setFillColor('black')
tire1.moveTo(300, 450)
car.add(tire1)
tire2=tire1.clone()
tire2.moveTo(500, 450)
car.add(tire2)
w1=Rectangle(160, 1)
w1.setFillColor('light blue')
w1.moveTo(400, 260)
car.add(w1)
body=Rectangle(25, 40)
body.moveTo(425, 320)
body.setFillColor('white')
car.add(body)
head=Circle(25)
head.moveTo(425, 300)
head.setFillColor('white')
car.add(head)
w2=Rectangle(160, 80)
w2.setFillColor('black')
w2.moveTo(400, 300)
car.add(w2)
self.layer = car
_scene.add(self.layer)
def window()
# write your animation scenario here
| 15 | 15 | code_understanding | Because of the difference in style, I don't think the existence of objects is important at the cs101 level.
If you want to know specifically, it would be nice to refer to the docs in the link. | cs1qa | null | null | null | null | null | Question:
Why attach (object) when creating a class?
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(800, 600)
_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)
"""
_scene.setBackgroundColor('light blue')
road=Rectangle(805, 305)
_scene.add(road)
road.setFillColor('gray')
road.setBorderColor('yellow')
road.setBorderWidth(5)
road.moveTo(400, 550)
tree=Layer()
trunk1=Rectangle(80, 150)
trunk1.moveTo(150, 325)
trunk1.setFillColor('brown')
trunk1.setBorderColor('brown')
tree.add(trunk1)
leaf1=Ellipse(175, 200)
leaf1.moveTo(150, 200)
leaf1.setFillColor('light green')
leaf1.setBorderColor('light green')
tree.add(leaf1)
trunk2=Rectangle(80, 200)
trunk2.moveTo(600, 300)
trunk2.setFillColor('brown')
trunk2.setBorderColor('brown')
tree.add(trunk2)
leaf2=Ellipse(175, 180)
leaf2.moveTo(600, 175)
leaf2.setFillColor('green')
leaf2.setBorderColor('green')
tree.add(leaf2)
_scene.add(tree)
"""
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 Car(object):
def __init__(self, color):
car=Layer()
car1=Rectangle(200, 100)
car1.setFillColor(color)
car1.setBorderColor(color)
car1.moveTo(400, 300)
car.add(car1)
car2=Rectangle(400, 100)
car2.setFillColor(color)
car2.setBorderColor(color)
car2.moveTo(400, 400)
car.add(car2)
tire1=Circle(50)
tire1.setFillColor('black')
tire1.moveTo(300, 450)
car.add(tire1)
tire2=tire1.clone()
tire2.moveTo(500, 450)
car.add(tire2)
w1=Rectangle(160, 1)
w1.setFillColor('light blue')
w1.moveTo(400, 260)
car.add(w1)
body=Rectangle(25, 40)
body.moveTo(425, 320)
body.setFillColor('white')
car.add(body)
head=Circle(25)
head.moveTo(425, 300)
head.setFillColor('white')
car.add(head)
w2=Rectangle(160, 80)
w2.setFillColor('black')
w2.moveTo(400, 300)
car.add(w2)
self.layer = car
_scene.add(self.layer)
def window()
# write your animation scenario here
|
3 | 1 | TA | What is move_and_drop in Task 2? | 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()
my_robot.set_trace('blue')
def turn_right():
for i in range(3):
my_robot.turn_left()
def turn_around():
for i in range(2):
my_robot.turn_left()
def move_and_pick():
my_robot.move()
if my_robot.on_beeper():
while my_robot.on_beeper():
my_robot.pick_beeper()
def move_and_drop():
my_robot.move()
while my_robot.carries_beepers():
my_robot.drop_beeper()
for i in range(9):
move_and_pick()
turn_around()
for i in range(9):
my_robot.move()
turn_right()
move_and_drop()
turn_around()
my_robot.move()
my_robot.turn_left() | 22 | 25 | variable | This function moves the robot one space and drops all the beepers it has. | cs1qa | null | null | null | null | null | Question:
What is move_and_drop in Task 2?
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()
my_robot.set_trace('blue')
def turn_right():
for i in range(3):
my_robot.turn_left()
def turn_around():
for i in range(2):
my_robot.turn_left()
def move_and_pick():
my_robot.move()
if my_robot.on_beeper():
while my_robot.on_beeper():
my_robot.pick_beeper()
def move_and_drop():
my_robot.move()
while my_robot.carries_beepers():
my_robot.drop_beeper()
for i in range(9):
move_and_pick()
turn_around()
for i in range(9):
my_robot.move()
turn_right()
move_and_drop()
turn_around()
my_robot.move()
my_robot.turn_left() |
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() |
4 | 3 | TA | Why did you put int? | import math
sin = math.sin
pi = math.pi
for i in range(41):
x = float(i) / 40.0 * 2 * pi
character_count_per_line = int(40 + 40*sin(x)) # Change this line to print out sine curve correctly.
output_str = '#' * character_count_per_line
print(output_str) | 7 | 7 | reasoning | This is because the number of stars is an integer number, so if the sin value is not an integer, an error occurs. | cs1qa | null | null | null | null | null | Question:
Why did you put int?
Code:
import math
sin = math.sin
pi = math.pi
for i in range(41):
x = float(i) / 40.0 * 2 * pi
character_count_per_line = int(40 + 40*sin(x)) # Change this line to print out sine curve correctly.
output_str = '#' * character_count_per_line
print(output_str) |
4 | 2 | TA | Task 3: Is the parameter of the sine function degree or radian? | import math
sin = math.sin
pi = math.pi
a= int(input('How many steps? '))
for i in range(a):
x = float(i) / float(a-1) * 2 * pi
print (sin(x)) | 2 | 2 | variable | Task 3: The argument of the sine function is converted to radians by multiplying by 2*pi. | cs1qa | null | null | null | null | null | Question:
Task 3: Is the parameter of the sine function degree or radian?
Code:
import math
sin = math.sin
pi = math.pi
a= int(input('How many steps? '))
for i in range(a):
x = float(i) / float(a-1) * 2 * pi
print (sin(x)) |
8 | 0 | TA | Please explain code 1 | from time import sleep
import elice_utils
def merge(input_filenames, output_filename):
# Implement here
output_file = open(output_filename,'w')
for file_name in input_filenames:
file = open(file_name, 'r')
for line in file:
output_file.write(line)
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') | 0 | 18 | code_explain | Code #1 creates a new file named output_filename in the merge function, opens the files in the input_filenames list, and writes them line by line to the new file. | cs1qa | null | null | null | null | null | Question:
Please explain code 1
Code:
from time import sleep
import elice_utils
def merge(input_filenames, output_filename):
# Implement here
output_file = open(output_filename,'w')
for file_name in input_filenames:
file = open(file_name, 'r')
for line in file:
output_file.write(line)
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 | 0 | TA | What is the role of the move1() function 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 move1():
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
def lap():
for i in range(5):
move1()
hubo.turn_left()
move1()
hubo.turn_left()
for i in range(5):
move1()
move1()
lap()
for i in range(2):
turn_right()
move1()
turn_right()
lap() | 9 | 12 | variable | The move1() function is to pick up the beeper if the robot moves and there is a beeper at that location. | cs1qa | null | null | null | null | null | Question:
What is the role of the move1() function 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 move1():
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
def lap():
for i in range(5):
move1()
hubo.turn_left()
move1()
hubo.turn_left()
for i in range(5):
move1()
move1()
lap()
for i in range(2):
turn_right()
move1()
turn_right()
lap() |
6 | 2 | TA | What does initialize do? | 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 tries==1: # 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.
tf=0
for i in range(len(correct_list)):
if correct_list[i]==num1 or correct_list[i]==num2:
tf=1
if num1==num2:
tf=1
if num1>23 or num2>23 or num1<0 or num2<0:
tf=1
if tf==1:
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.
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
if i==num1 or i==num2 or i in correct_list:
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)
if cards[num1][1]==cards[num2][1]:
correct_list.append(num1)
correct_list.append(num2)
return True
else:
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
if i in correct_list:
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)
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%10==1:
print(str(tries) + "st try. You got " + str(len(correct_list)//2) + " pairs.")
elif tries%10==2:
print(str(tries) + "nd try. You got " + str(len(correct_list)//2) + " pairs.")
elif tries%10==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!")
else:
print("Wrong!")
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
tries=tries+1
###########################################################################
| 16 | 34 | variable | initialize is a function that randomly mixes the faces and backs of cards to make a game | cs1qa | null | null | null | null | null | Question:
What does initialize do?
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 tries==1: # 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.
tf=0
for i in range(len(correct_list)):
if correct_list[i]==num1 or correct_list[i]==num2:
tf=1
if num1==num2:
tf=1
if num1>23 or num2>23 or num1<0 or num2<0:
tf=1
if tf==1:
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.
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
if i==num1 or i==num2 or i in correct_list:
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)
if cards[num1][1]==cards[num2][1]:
correct_list.append(num1)
correct_list.append(num2)
return True
else:
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
if i in correct_list:
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)
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%10==1:
print(str(tries) + "st try. You got " + str(len(correct_list)//2) + " pairs.")
elif tries%10==2:
print(str(tries) + "nd try. You got " + str(len(correct_list)//2) + " pairs.")
elif tries%10==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!")
else:
print("Wrong!")
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
tries=tries+1
###########################################################################
|
5 | 0 | TA | Can you briefly explain the task1 input 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()
| 42 | 42 | variable | The input function always exports the value as a string type, and adds a process of converting it to an integer type so that it can be calculated using the input value. | cs1qa | null | null | null | null | null | Question:
Can you briefly explain the task1 input 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()
|
4 | 2 | TA | What are the termination conditions? | 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
global 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
sequence = []
for i in range(24):
sequence.append(i)
random.shuffle(sequence)
temp_cards = []
for i in range(24):
temp_cards.insert(sequence[i], cards[i])
cards = temp_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.
for value in correct_list:
if num1 == value or num2 == value:
return False
if num1 == num2:
return False
if type(num1) != int or type(num2) != int:
return False
if not ((num1 <=23 and num1 >= 0) and (num2 <=23 and num2 >= 0)):
return False
return True
###########################################################################
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.
###########################################################################
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
# for i in range(len(num_pads)):
# ################################################################
# if i == num1 or i == num2 or 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
correct_list.extend((num1, num2))
print_cards()
time.sleep(1)
if cards[num1][1] == cards[num2][1]:
# correct_list.extend((num1, num2))
return True
# canvas.clear()
# 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.add(cards[i][0])#
#w += 100
# if w % 600 == 0:
# w = 0
# h += 130
# time.sleep(1)
del correct_list[-1]
del correct_list[-1]
print_cards()
return False
initialize()
canvas.clear()
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.add(cards[i][0])
w += 100
if w % 600 == 0:
w = 0
h += 130
time.sleep(1)
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.")
tries = tries + 1
###########################################################################
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!")
if len(correct_list) == 24:
print("You cleared this game")
break
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
###########################################################################
| 181 | 183 | code_explain | The end condition is when the length of the list of correct answers is 24. | cs1qa | null | null | null | null | null | Question:
What are the termination conditions?
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
global 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
sequence = []
for i in range(24):
sequence.append(i)
random.shuffle(sequence)
temp_cards = []
for i in range(24):
temp_cards.insert(sequence[i], cards[i])
cards = temp_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.
for value in correct_list:
if num1 == value or num2 == value:
return False
if num1 == num2:
return False
if type(num1) != int or type(num2) != int:
return False
if not ((num1 <=23 and num1 >= 0) and (num2 <=23 and num2 >= 0)):
return False
return True
###########################################################################
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.
###########################################################################
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
# for i in range(len(num_pads)):
# ################################################################
# if i == num1 or i == num2 or 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
correct_list.extend((num1, num2))
print_cards()
time.sleep(1)
if cards[num1][1] == cards[num2][1]:
# correct_list.extend((num1, num2))
return True
# canvas.clear()
# 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.add(cards[i][0])#
#w += 100
# if w % 600 == 0:
# w = 0
# h += 130
# time.sleep(1)
del correct_list[-1]
del correct_list[-1]
print_cards()
return False
initialize()
canvas.clear()
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.add(cards[i][0])
w += 100
if w % 600 == 0:
w = 0
h += 130
time.sleep(1)
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.")
tries = tries + 1
###########################################################################
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!")
if len(correct_list) == 24:
print("You cleared this game")
break
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
###########################################################################
|
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
global balance
# Add the money to the current balance
balance = balance + int(money)
print("You deposited "+ str(money) + " won")
#################
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 int(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")
#################
### implement ###
#################
# Do something on here !
#################
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 == 'd':
dep = int(input("How much do you want to deposit?"))
deposit(dep)
elif process == 'w':
wit = int(input('How much do you want to withdraw?'))
withdrawal(wit)
elif process == 'c':
print("Your current balance is "+str(balance)+" won")
elif process == 'return' or process == '':
return
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()
| 2 | 9 | variable | Since the functions used in this task are to add, subtract, or check a value from the global variable balance, he said that each function would use the global variable balance. | 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
global balance
# Add the money to the current balance
balance = balance + int(money)
print("You deposited "+ str(money) + " won")
#################
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 int(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")
#################
### implement ###
#################
# Do something on here !
#################
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 == 'd':
dep = int(input("How much do you want to deposit?"))
deposit(dep)
elif process == 'w':
wit = int(input('How much do you want to withdraw?'))
withdrawal(wit)
elif process == 'c':
print("Your current balance is "+str(balance)+" won")
elif process == 'return' or process == '':
return
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()
|
4 | 0 | TA | Please briefly explain the algorithm written in Task 1! | from cs1robots import *
load_world('worlds/add34.wld')
hubo = Robot(street = 2, beepers = 100)
def num(n):
if hubo.front_is_clear():
hubo.move()
n*=10
while hubo.on_beeper():
hubo.pick_beeper()
n+=1
else: return n
return num(n)
def turn_back():
hubo.turn_left()
hubo.turn_left()
while hubo.front_is_clear():
hubo.move()
hubo.turn_left()
hubo.move()
hubo.turn_left()
def print_num(n):
if n==0:
return
for i in range(n%10):
hubo.drop_beeper()
hubo.move()
n//=10
print_num(n)
a = num(0)
turn_back()
b = num(0)
hubo.turn_left()
hubo.turn_left()
print_num(a+b)
print(a+b) | 34 | 40 | code_explain | Whenever I went forward, I multiplied the number by 10 and added it when I met Beeper.
Then, going all the way to the end, the number is returned. | cs1qa | null | null | null | null | null | Question:
Please briefly explain the algorithm written in Task 1!
Code:
from cs1robots import *
load_world('worlds/add34.wld')
hubo = Robot(street = 2, beepers = 100)
def num(n):
if hubo.front_is_clear():
hubo.move()
n*=10
while hubo.on_beeper():
hubo.pick_beeper()
n+=1
else: return n
return num(n)
def turn_back():
hubo.turn_left()
hubo.turn_left()
while hubo.front_is_clear():
hubo.move()
hubo.turn_left()
hubo.move()
hubo.turn_left()
def print_num(n):
if n==0:
return
for i in range(n%10):
hubo.drop_beeper()
hubo.move()
n//=10
print_num(n)
a = num(0)
turn_back()
b = num(0)
hubo.turn_left()
hubo.turn_left()
print_num(a+b)
print(a+b) |
4 | 0 | TA | Can you explain how you solved the rounding of addition in Task 1? | from cs1robots import *
# Your code must work for all world files below.
load_world( "worlds/add34.wld" )
# load_world( "worlds/trash2.wld" )
hubo= Robot()
pocket = []
def turn_right():
for i in range(3):
hubo.turn_left()
def back():
turn_right()
turn_right()
def ini_pick():
n=0
while hubo.on_beeper() == bool(True):
hubo.pick_beeper()
n += 1
pocket.append(n)
def moveallpick():
hubo.move()
n=0
while hubo.on_beeper() == bool(True):
hubo.pick_beeper()
n += 1
pocket.append(n)
def straight():
while hubo.front_is_clear() == bool(True):
moveallpick()
def northfacing():
while hubo.facing_north() == bool(False):
hubo.turn_left()
def gountilend():
while hubo.front_is_clear() == bool(True):
hubo.move()
def returnn():
northfacing()
hubo.turn_left()
gountilend()
hubo.turn_left()
gountilend()
hubo.turn_left()
def dropall():
if pocket[0] == 0:
del pocket[0]
else:
for i in range(pocket[0]):
hubo.drop_beeper()
pocket[0] == pocket[0]-1
del pocket[0]
def movedrop():
dropall()
hubo.move()
def straight1():
while hubo.front_is_clear() == bool(True):
movedrop()
def round_up():
n=0
while hubo.on_beeper() == bool(True):
n +=1
hubo.pick_beeper()
p = n // 10
if (n // 10) >= 1:
for i in range(n%10):
hubo.drop_beeper()
hubo.move()
for i in range(n//10):
hubo.drop_beeper()
back()
hubo.move()
back()
else:
for i in range(n):
hubo.drop_beeper()
hubo.move()
def addition():
while hubo.front_is_clear() == bool(True):
round_up()
hubo.turn_left()
hubo.move()
turn_right()
ini_pick()
straight()
returnn()
straight1()
dropall()
back()
addition()
#print(pocket)
#print(len(pocket))
#print(hubo._beeper_bag) | 73 | 94 | code_explain | The round-up process of the addition itself created a function called round-up, so if the number of beepers stored in the picked up list is greater than 10, go one space next to it, drop the quotient divided by 10, and come back and drop the remainder divided by 10. | cs1qa | null | null | null | null | null | Question:
Can you explain how you solved the rounding of addition in Task 1?
Code:
from cs1robots import *
# Your code must work for all world files below.
load_world( "worlds/add34.wld" )
# load_world( "worlds/trash2.wld" )
hubo= Robot()
pocket = []
def turn_right():
for i in range(3):
hubo.turn_left()
def back():
turn_right()
turn_right()
def ini_pick():
n=0
while hubo.on_beeper() == bool(True):
hubo.pick_beeper()
n += 1
pocket.append(n)
def moveallpick():
hubo.move()
n=0
while hubo.on_beeper() == bool(True):
hubo.pick_beeper()
n += 1
pocket.append(n)
def straight():
while hubo.front_is_clear() == bool(True):
moveallpick()
def northfacing():
while hubo.facing_north() == bool(False):
hubo.turn_left()
def gountilend():
while hubo.front_is_clear() == bool(True):
hubo.move()
def returnn():
northfacing()
hubo.turn_left()
gountilend()
hubo.turn_left()
gountilend()
hubo.turn_left()
def dropall():
if pocket[0] == 0:
del pocket[0]
else:
for i in range(pocket[0]):
hubo.drop_beeper()
pocket[0] == pocket[0]-1
del pocket[0]
def movedrop():
dropall()
hubo.move()
def straight1():
while hubo.front_is_clear() == bool(True):
movedrop()
def round_up():
n=0
while hubo.on_beeper() == bool(True):
n +=1
hubo.pick_beeper()
p = n // 10
if (n // 10) >= 1:
for i in range(n%10):
hubo.drop_beeper()
hubo.move()
for i in range(n//10):
hubo.drop_beeper()
back()
hubo.move()
back()
else:
for i in range(n):
hubo.drop_beeper()
hubo.move()
def addition():
while hubo.front_is_clear() == bool(True):
round_up()
hubo.turn_left()
hubo.move()
turn_right()
ini_pick()
straight()
returnn()
straight1()
dropall()
back()
addition()
#print(pocket)
#print(len(pocket))
#print(hubo._beeper_bag) |
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
global balance
balance=balance+money
print("You deposited %d won"%balance)
# Add the money to the current balance
#################
### implement ###
#################
# Do something on here !
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
global balance
if balance<money:
print("You've withdrawn %d won"%money)
print("But you only have %d won"%balance)
return None
balance=balance-money
print("You've withdrawn %d won"%money)
#################
### implement ###
#################
# Do something on here !
pass
#################
def check():
global balance
print("Your current balance is %d won"%balance)
def bank() :
# Input : (None) No Input
# Output : (None) No Output
while True:
process = input("Deposit(d) or withdrawal(w) or balance check(c)? ")
if process=='':
break
elif process== 'd':
money=input("How much do you want to deposit?")
deposit(int(money))
elif process== 'w':
money=input("How much do you want to withdraw?")
withdrawal(int(money))
elif process== 'c':
check()
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()
| 5 | 5 | reasoning | The balance variable is a variable that is commonly used for deposit, withdrawal, and check functions. It must be a global variable because it must always represent the amount in the account regardless of the type of function. | 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
global balance
balance=balance+money
print("You deposited %d won"%balance)
# Add the money to the current balance
#################
### implement ###
#################
# Do something on here !
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
global balance
if balance<money:
print("You've withdrawn %d won"%money)
print("But you only have %d won"%balance)
return None
balance=balance-money
print("You've withdrawn %d won"%money)
#################
### implement ###
#################
# Do something on here !
pass
#################
def check():
global balance
print("Your current balance is %d won"%balance)
def bank() :
# Input : (None) No Input
# Output : (None) No Output
while True:
process = input("Deposit(d) or withdrawal(w) or balance check(c)? ")
if process=='':
break
elif process== 'd':
money=input("How much do you want to deposit?")
deposit(int(money))
elif process== 'w':
money=input("How much do you want to withdraw?")
withdrawal(int(money))
elif process== 'c':
check()
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()
|
6 | 0 | TA | Please explain what you are doing inside the while statement! | def fibonacci(upper_bound):
list = [0, 1]
while (list[-1] + list[-2]) < upper_bound:
list.append(list[-1]+list[-2])
return list
print(fibonacci(1000))
| 2 | 3 | code_explain | Add the last two terms of the list with Fibonacci numbers, and if less than the upper bound, add the sum of the two numbers to the list. | cs1qa | null | null | null | null | null | Question:
Please explain what you are doing inside the while statement!
Code:
def fibonacci(upper_bound):
list = [0, 1]
while (list[-1] + list[-2]) < upper_bound:
list.append(list[-1]+list[-2])
return list
print(fibonacci(1000))
|
3 | 0 | TA | Please explain what the harvest_more() function does and does! | 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 check_beeper():
if hubo.on_beeper():
hubo.pick_beeper()
# Scans 2 floors(rows) which have {num} columns
def scan_two_floor(num):
for k in range(num - 1):
check_beeper()
hubo.move()
check_beeper()
hubo.turn_left()
if hubo.front_is_clear():
hubo.move()
hubo.turn_left()
for k in range(num - 1):
check_beeper()
hubo.move()
check_beeper()
# Input the number of row and column of check area,{row},{col} each
def harvest_more(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):
check_beeper()
hubo.move()
check_beeper()
hubo.move()
harvest_more(6,6)
| 29 | 44 | variable | This is the code that harvests the area by inserting the row and col values of the area to be harvested. | cs1qa | null | null | null | null | null | Question:
Please explain what the harvest_more() function does and does!
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 check_beeper():
if hubo.on_beeper():
hubo.pick_beeper()
# Scans 2 floors(rows) which have {num} columns
def scan_two_floor(num):
for k in range(num - 1):
check_beeper()
hubo.move()
check_beeper()
hubo.turn_left()
if hubo.front_is_clear():
hubo.move()
hubo.turn_left()
for k in range(num - 1):
check_beeper()
hubo.move()
check_beeper()
# Input the number of row and column of check area,{row},{col} each
def harvest_more(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):
check_beeper()
hubo.move()
check_beeper()
hubo.move()
harvest_more(6,6)
|
8 | 2 | TA | H = True
year = 1722 #start from 1723
for line in f:
if H:
H = False
continue
I wonder why you use this H | import elice_utils
f = open("tpmon.txt", 'r')
H = True
year = 1722 #start from 1723
for line in f:
if H:
H = False #to avoid header
continue
year += 1
l = line
winter = (float(l[0:6].lstrip()) + float(l[6:12].lstrip()))/2
summer = (float(l[36:42].lstrip()) + float(l[42:48].lstrip()))/2
print("%d: %6.1f / %4.1f"%(year, winter, summer))
f.close()
f = open("tpmon.txt", 'r')
g = open("tpmon.csv", 'w')
H = True
year = 1722 #start from 1723
for line in f:
if H:
H = False
continue
year += 1
total = str(year)
l = line
for i in range(12):
total += ','
total += l[i*6:i*6+6].lstrip()
total += '\n'
g.write(total)
g.close()
elice_utils.send_file("tpmon.csv") | 19 | 24 | reasoning | To read the first line of the document and skip right away.
The for line in f: statement takes the first line of f and then exits with continue immediately. | cs1qa | null | null | null | null | null | Question:
H = True
year = 1722 #start from 1723
for line in f:
if H:
H = False
continue
I wonder why you use this H
Code:
import elice_utils
f = open("tpmon.txt", 'r')
H = True
year = 1722 #start from 1723
for line in f:
if H:
H = False #to avoid header
continue
year += 1
l = line
winter = (float(l[0:6].lstrip()) + float(l[6:12].lstrip()))/2
summer = (float(l[36:42].lstrip()) + float(l[42:48].lstrip()))/2
print("%d: %6.1f / %4.1f"%(year, winter, summer))
f.close()
f = open("tpmon.txt", 'r')
g = open("tpmon.csv", 'w')
H = True
year = 1722 #start from 1723
for line in f:
if H:
H = False
continue
year += 1
total = str(year)
l = line
for i in range(12):
total += ','
total += l[i*6:i*6+6].lstrip()
total += '\n'
g.write(total)
g.close()
elice_utils.send_file("tpmon.csv") |
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))
| 34 | 36 | 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))
|
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()
| null | null | 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()
|
1 | 0 | TA | Briefly explain f and m among the functions you have implemented | from cs1robots import *
create_world()
hubo=Robot()
hubo.set_trace('blue')
def turn_right():
for i in range(3):
hubo.turn_left()
def f():
for i in range(9):
hubo.move()
turn_right()
hubo.move()
turn_right()
for i in range(9):
hubo.move()
def m():
hubo.turn_left()
hubo.move()
hubo.turn_left()
hubo.turn_left()
for i in range(4):
f()
m()
f()
| 9 | 21 | variable | f() is a function that rearranges the direction so that it goes up and down as if it is turned over, and m() is a function that moves it one space to the right and re-orients it up again. | cs1qa | null | null | null | null | null | Question:
Briefly explain f and m among the functions you have implemented
Code:
from cs1robots import *
create_world()
hubo=Robot()
hubo.set_trace('blue')
def turn_right():
for i in range(3):
hubo.turn_left()
def f():
for i in range(9):
hubo.move()
turn_right()
hubo.move()
turn_right()
for i in range(9):
hubo.move()
def m():
hubo.turn_left()
hubo.move()
hubo.turn_left()
hubo.turn_left()
for i in range(4):
f()
m()
f()
|
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() |
6 | 2 | TA | Why did you do num1-=1 and num2-=1 at the 138th and 139th? | 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 = []
global num1
global num2
num1 = -1
num2 = -1
first = 0
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(cards)
################################################################
# 3-2-1. shuffle the card list
################################################################
def print_cards():
# global num1
# global num2
global first
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
if first == 0:
for i in range(len(num_pads)):
cards[i][0].moveTo(i_w + w, i_h+h)
canvas.add(cards[i][0])
w+=100
if w % 600 == 0:
w = 0
h += 130
time.sleep(2)
first += 1
canvas.clear()
w = 0
h = 0
for i in range(len(num_pads)):
################################################################
if i==num1 or i==num2 or 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.
###########################################################################
for i in range(len(correct_list)):
if correct_list[i]==num1 or correct_list[i]==num2:
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.
###########################################################################
print_cards()
if cards[num1][1] == cards[num2][1]:
correct_list.append(num1)
correct_list.append(num2)
return True
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.")
###########################################################################
# global num1
# global num2
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!")
num1 = -1
num2 = -1
print_cards()
tries+=1
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
###########################################################################
| 137 | 138 | reasoning | The reason for substituting -1 for num1 and num2 was to print only the correct list when an incorrect answer was answered. | cs1qa | null | null | null | null | null | Question:
Why did you do num1-=1 and num2-=1 at the 138th and 139th?
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 = []
global num1
global num2
num1 = -1
num2 = -1
first = 0
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(cards)
################################################################
# 3-2-1. shuffle the card list
################################################################
def print_cards():
# global num1
# global num2
global first
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
if first == 0:
for i in range(len(num_pads)):
cards[i][0].moveTo(i_w + w, i_h+h)
canvas.add(cards[i][0])
w+=100
if w % 600 == 0:
w = 0
h += 130
time.sleep(2)
first += 1
canvas.clear()
w = 0
h = 0
for i in range(len(num_pads)):
################################################################
if i==num1 or i==num2 or 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.
###########################################################################
for i in range(len(correct_list)):
if correct_list[i]==num1 or correct_list[i]==num2:
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.
###########################################################################
print_cards()
if cards[num1][1] == cards[num2][1]:
correct_list.append(num1)
correct_list.append(num2)
return True
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.")
###########################################################################
# global num1
# global num2
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!")
num1 = -1
num2 = -1
print_cards()
tries+=1
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
###########################################################################
|
9 | 0 | TA | What elements is the cards list in? | 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:
'''Memento cards'''
def __init__(self,img,name):
global names
assert name in names
self.img=img
self.name=name
self.state=False
def flip(self):
self.state=not self.state
for i in range(6):
for k in range(4):
card1=Card((Image(path+names[i])),names[i])
cards.append(card1)
def initialize():
# initialize cards
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)):
################################################################
# 3-2-2. rewrite the condition for visualization.
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(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
for i in range(len(cards)):
if cards[num1].state==True:
return False
elif cards[num2].state==True:
return False
if num1==num2:
return False
if num1<0 or num1>23:
return False
if num2<0 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.
###########################################################################
cards[num1].flip()
cards[num2].flip()
print_cards()
if cards[num1].name==cards[num2].name:
return True
else:
cards[num1].flip()
cards[num2].flip()
print_cards()
return False
initialize()
print_cards()
for i in range(len(cards)):
cards[i].flip()
print_cards()
time.sleep(1)
for i in range(len(cards)):
cards[i].flip()
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
listbool=[]
for i in range(len(cards)):
listbool.append(cards[i].state)
if tries%10==2:
print(str(tries) + "nd try. You got " + str(len(listbool)//2) + " pairs.")
else:
print(str(tries) + "th try. You got " + str(len(listbool)//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)
tries =tries+1
###########################################################################
listbool=[]
for i in range(len(cards)):
listbool.append(cards[i].state)
if listbool==[True]*len(listbool):
break
| 29 | 30 | variable | The cards list is a list of Card objects. | cs1qa | null | null | null | null | null | Question:
What elements is the cards list in?
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:
'''Memento cards'''
def __init__(self,img,name):
global names
assert name in names
self.img=img
self.name=name
self.state=False
def flip(self):
self.state=not self.state
for i in range(6):
for k in range(4):
card1=Card((Image(path+names[i])),names[i])
cards.append(card1)
def initialize():
# initialize cards
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)):
################################################################
# 3-2-2. rewrite the condition for visualization.
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(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
for i in range(len(cards)):
if cards[num1].state==True:
return False
elif cards[num2].state==True:
return False
if num1==num2:
return False
if num1<0 or num1>23:
return False
if num2<0 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.
###########################################################################
cards[num1].flip()
cards[num2].flip()
print_cards()
if cards[num1].name==cards[num2].name:
return True
else:
cards[num1].flip()
cards[num2].flip()
print_cards()
return False
initialize()
print_cards()
for i in range(len(cards)):
cards[i].flip()
print_cards()
time.sleep(1)
for i in range(len(cards)):
cards[i].flip()
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
listbool=[]
for i in range(len(cards)):
listbool.append(cards[i].state)
if tries%10==2:
print(str(tries) + "nd try. You got " + str(len(listbool)//2) + " pairs.")
else:
print(str(tries) + "th try. You got " + str(len(listbool)//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)
tries =tries+1
###########################################################################
listbool=[]
for i in range(len(cards)):
listbool.append(cards[i].state)
if listbool==[True]*len(listbool):
break
|
5 | 1 | TA | Can you explain what animation you used to make the objects sound in Task2? | from cs1graphics import *
from time import sleep
def draw_animal():
canvas = Canvas(800,500)
canvas.setBackgroundColor('blue')
global sq
sq = Square(120)
canvas.add(sq)
sq.setFillColor('yellow')
sq.moveTo(400,200)
global cir1
global cir2
cir1 = Circle(10)
cir2 = Circle(10)
cir1.setFillColor('black')
cir2.setFillColor('black')
canvas.add(cir1)
canvas.add(cir2)
cir1.moveTo(370,180)
cir2.moveTo(430,180)
global cir3
cir3 = Circle(20)
canvas.add(cir3)
cir3.setFillColor('pink')
cir3.moveTo(400,230)
global rec1
global rec2
rec1 = Rectangle(10,100)
rec2 = Rectangle(10,100)
canvas.add(rec1)
canvas.add(rec2)
rec1.moveTo(340,200)
rec2.moveTo(460,200)
rec1.setFillColor('yellow')
rec2.setFillColor('yellow')
rec1.setBorderColor('yellow')
rec2.setBorderColor('yellow')
sq.setBorderColor('yellow')
cir3.setBorderColor('pink')
global d
d=Layer()
d.add(sq)
d.add(cir1)
d.add(cir2)
d.add(cir3)
d.add(rec1)
d.add(rec2)
# Implement this function.
pass
def show_animation():
for i in range(45):
sq.move(1,0)
cir1.move(1,0)
cir2.move(1,0)
cir3.move(1,0)
rec1.move(1,0)
rec2.move(1,0)
rec1.rotate(-1)
rec2.rotate(1)
sleep(0.1)
# Implement this function.
pass
draw_animal()
show_animation() | 53 | 60 | code_explain | I used move and rotate | cs1qa | null | null | null | null | null | Question:
Can you explain what animation you used to make the objects sound in Task2?
Code:
from cs1graphics import *
from time import sleep
def draw_animal():
canvas = Canvas(800,500)
canvas.setBackgroundColor('blue')
global sq
sq = Square(120)
canvas.add(sq)
sq.setFillColor('yellow')
sq.moveTo(400,200)
global cir1
global cir2
cir1 = Circle(10)
cir2 = Circle(10)
cir1.setFillColor('black')
cir2.setFillColor('black')
canvas.add(cir1)
canvas.add(cir2)
cir1.moveTo(370,180)
cir2.moveTo(430,180)
global cir3
cir3 = Circle(20)
canvas.add(cir3)
cir3.setFillColor('pink')
cir3.moveTo(400,230)
global rec1
global rec2
rec1 = Rectangle(10,100)
rec2 = Rectangle(10,100)
canvas.add(rec1)
canvas.add(rec2)
rec1.moveTo(340,200)
rec2.moveTo(460,200)
rec1.setFillColor('yellow')
rec2.setFillColor('yellow')
rec1.setBorderColor('yellow')
rec2.setBorderColor('yellow')
sq.setBorderColor('yellow')
cir3.setBorderColor('pink')
global d
d=Layer()
d.add(sq)
d.add(cir1)
d.add(cir2)
d.add(cir3)
d.add(rec1)
d.add(rec2)
# Implement this function.
pass
def show_animation():
for i in range(45):
sq.move(1,0)
cir1.move(1,0)
cir2.move(1,0)
cir3.move(1,0)
rec1.move(1,0)
rec2.move(1,0)
rec1.rotate(-1)
rec2.rotate(1)
sleep(0.1)
# Implement this function.
pass
draw_animal()
show_animation() |
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 | 16 | 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 | 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() |
6 | 1 | TA | What does task 2's count do? | 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]
"""
numbers=[]
for i in range(trials):
numbers.append(random.randint(lb, ub))
return numbers
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)/len(num_list)
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
"""
freq=[]
for num in set(num_list):
freq.append((num,num_list.count(num)))
return freq
# 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))
| 34 | 34 | variable | It returns the number of elements in the list. | cs1qa | null | null | null | null | null | Question:
What does task 2's count do?
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]
"""
numbers=[]
for i in range(trials):
numbers.append(random.randint(lb, ub))
return numbers
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)/len(num_list)
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
"""
freq=[]
for num in set(num_list):
freq.append((num,num_list.count(num)))
return freq
# 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))
|
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)) | 1 | 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)) |
6 | 2 | TA | How did you check that the cards match 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 = []
list1=[]
for i in range(24):
list1.append(i)
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(cards)
################################################################
# 3-2-1. shuffle the cards list
################################################################
def print_cards(num1, num2, correct_list1):
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
################################################################
if i in correct_list1 or i==num1 or i==num2: # 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 type(num1)!=int or type(num2)!=int:
return False
elif num1==num2:
return False
elif num1>23 or num2>23:
return False
for i in correct_list:
if i==num1 or i==num2:
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.
###########################################################################
print_cards(num1, num2, correct_list)
a=cards[num1]
b=cards[num2]
if a[1]==b[1]:
correct_list.append(num1)
correct_list.append(num2)
print_cards(-1, -1, correct_list)
return True
print_cards(-1, -1, correct_list)
return False
initialize()
print_cards(-1, -1, list1)
time.sleep(3)
print_cards(-1, -1, correct_list)
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 is_valid(num1, num2):
if check(num1, num2):
print("Correct!")
tries+=1
else:
print("Wrong!")
tries+=1
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
###########################################################################
| 90 | 92 | code_explain | from cards
The index value of 1 in the tuples was the name of the picture
Compare it | cs1qa | null | null | null | null | null | Question:
How did you check that the cards match 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 = []
list1=[]
for i in range(24):
list1.append(i)
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(cards)
################################################################
# 3-2-1. shuffle the cards list
################################################################
def print_cards(num1, num2, correct_list1):
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
################################################################
if i in correct_list1 or i==num1 or i==num2: # 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 type(num1)!=int or type(num2)!=int:
return False
elif num1==num2:
return False
elif num1>23 or num2>23:
return False
for i in correct_list:
if i==num1 or i==num2:
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.
###########################################################################
print_cards(num1, num2, correct_list)
a=cards[num1]
b=cards[num2]
if a[1]==b[1]:
correct_list.append(num1)
correct_list.append(num2)
print_cards(-1, -1, correct_list)
return True
print_cards(-1, -1, correct_list)
return False
initialize()
print_cards(-1, -1, list1)
time.sleep(3)
print_cards(-1, -1, correct_list)
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 is_valid(num1, num2):
if check(num1, num2):
print("Correct!")
tries+=1
else:
print("Wrong!")
tries+=1
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
###########################################################################
|
6 | 2 | TA | Can you explain what a list a does in the third task? | 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 = []
a = []
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 show_cards():
canvas.clear()
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.add(cards[i][0])
w += 100
if w % 600 == 0:
w = 0
h += 130
time.sleep(3)
def show_cards2():
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
################################################################
if i in a or 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 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 or num1==num2 or not (0<=num1, 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.
if cards[num1][1]==cards[num2][1]:
return True
else:
return False
###########################################################################
initialize()
show_cards()
print_cards()
print("### Welcome to the Python Memento game!!! ###")
###############################################################################
while not len(correct_list)==24:
###############################################################################
###########################################################################
# 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!")
correct_list.append(num1)
correct_list.append(num2)
print_cards()
else:
print("Wrong!")
a.append(num1)
a.append(num2)
show_cards2()
a=[]
print_cards()
###########################################################################
tries = tries+1
###########################################################################
| 58 | 71 | variable | a is introduced to identify middle-chosen pairs | cs1qa | null | null | null | null | null | Question:
Can you explain what a list a does in the third task?
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 = []
a = []
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 show_cards():
canvas.clear()
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.add(cards[i][0])
w += 100
if w % 600 == 0:
w = 0
h += 130
time.sleep(3)
def show_cards2():
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
################################################################
if i in a or 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 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 or num1==num2 or not (0<=num1, 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.
if cards[num1][1]==cards[num2][1]:
return True
else:
return False
###########################################################################
initialize()
show_cards()
print_cards()
print("### Welcome to the Python Memento game!!! ###")
###############################################################################
while not len(correct_list)==24:
###############################################################################
###########################################################################
# 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!")
correct_list.append(num1)
correct_list.append(num2)
print_cards()
else:
print("Wrong!")
a.append(num1)
a.append(num2)
show_cards2()
a=[]
print_cards()
###########################################################################
tries = tries+1
###########################################################################
|
8 | 1 | TA | How did you write the code to print the country name when you input the country code at the end? | f=open("average-latitude-longitude-countries.csv","r")
r=[]
r1=[]
r2=[]
for l in f:
r.append(l)
r=r[1:]
for i in range(len(r)):
a=r[i].split(",")
if len(a)>4:
code=a[0][1:-1]
name=a[1]+","+a[2]
name=name[1:-1]
lat=a[-2]
lon=a[-1]
else:
code=a[0][1:-1]
name=a[1][1:-1]
lat=a[2]
lon=a[3]
r1.append((str(code),str(name)))
r2.append((str(code),(float(lat),float(lon))))
print(r1)
print(r2)
for i in range(len(r2)):
if r2[i][1][0]<0:
print(r1[i][1])
a=input('Enter country code: ')
for i in range(len(r1)):
if r1[i][0]==a:
print(r1[i][1]) | 34 | 37 | code_explain | Since the country name and code are stored in the r1 list, if the code is the same, the country name corresponding to it is displayed. | cs1qa | null | null | null | null | null | Question:
How did you write the code to print the country name when you input the country code at the end?
Code:
f=open("average-latitude-longitude-countries.csv","r")
r=[]
r1=[]
r2=[]
for l in f:
r.append(l)
r=r[1:]
for i in range(len(r)):
a=r[i].split(",")
if len(a)>4:
code=a[0][1:-1]
name=a[1]+","+a[2]
name=name[1:-1]
lat=a[-2]
lon=a[-1]
else:
code=a[0][1:-1]
name=a[1][1:-1]
lat=a[2]
lon=a[3]
r1.append((str(code),str(name)))
r2.append((str(code),(float(lat),float(lon))))
print(r1)
print(r2)
for i in range(len(r2)):
if r2[i][1][0]<0:
print(r1[i][1])
a=input('Enter country code: ')
for i in range(len(r1)):
if r1[i][0]==a:
print(r1[i][1]) |
8 | 2 | TA | Why do you add 1 in every loop in the for function? | import elice_utils | null | null | reasoning | Each time a line is read, we add 1 to increase the year by 1. | cs1qa | null | null | null | null | null | Question:
Why do you add 1 in every loop in the for function?
Code:
import elice_utils |
1 | 0 | TA | In task1, you set the variables a, b, and c differently in the for statement. Did you intentionally do it differently? | from cs1robots import*
create_world()
hubo=Robot()
hubo.set_trace("blue")
def turn_right():
for a in range(3):
hubo.turn_left()
def charge():
for b in range(9):
hubo.move()
hubo.turn_left()
charge()
turn_right()
hubo.move()
turn_right()
charge()
for c in range(4):
hubo.turn_left()
hubo.move()
hubo.turn_left()
charge()
turn_right()
hubo.move()
turn_right()
charge() | 4 | 26 | reasoning | Yes, I did it differently to differentiate | cs1qa | null | null | null | null | null | Question:
In task1, you set the variables a, b, and c differently in the for statement. Did you intentionally do it differently?
Code:
from cs1robots import*
create_world()
hubo=Robot()
hubo.set_trace("blue")
def turn_right():
for a in range(3):
hubo.turn_left()
def charge():
for b in range(9):
hubo.move()
hubo.turn_left()
charge()
turn_right()
hubo.move()
turn_right()
charge()
for c in range(4):
hubo.turn_left()
hubo.move()
hubo.turn_left()
charge()
turn_right()
hubo.move()
turn_right()
charge() |
5 | 0 | TA | Please explain how withdrawal works 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
global balance
balance = balance + money
#################
### implement ###
#################
# Do something on here !
print('You deposited',money,'won')
return balance
#################
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 money > balance:
print("You've withdrawn",money,'won')
print('But you only have',balance,'won')
else:
balance = balance - money
print("You've widthdraw",money,'won')
#################
### implement ###
#################
# Do something on here !
return balance
#################
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 process == '':
return
# If a user's input is 'd', then ask the amount of money to deposit and deposit it.
elif 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', balance, 'won')
else:
print('Please, press d or w or c to return')
#################
### implement ###
#################
# Do something on here !
#################
bank()
| 18 | 35 | variable | Withdrawal is a function that withdraws when the amount you want to withdraw is deposited and the balance is greater than that amount. | cs1qa | null | null | null | null | null | Question:
Please explain how withdrawal works 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
global balance
balance = balance + money
#################
### implement ###
#################
# Do something on here !
print('You deposited',money,'won')
return balance
#################
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 money > balance:
print("You've withdrawn",money,'won')
print('But you only have',balance,'won')
else:
balance = balance - money
print("You've widthdraw",money,'won')
#################
### implement ###
#################
# Do something on here !
return balance
#################
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 process == '':
return
# If a user's input is 'd', then ask the amount of money to deposit and deposit it.
elif 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', balance, 'won')
else:
print('Please, press d or w or c to return')
#################
### implement ###
#################
# Do something on here !
#################
bank()
|
3 | 1 | TA | How did you know when you didn't have a beeper? | 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()
my_robot.set_trace("red")
def turn_right():
for i in range(3):
my_robot.turn_left()
def line():
while my_robot.front_is_clear():
my_robot.move()
while my_robot.on_beeper():
my_robot.pick_beeper()
def turn_around():
for i in range(2):
my_robot.turn_left()
line()
turn_around()
line()
turn_right()
my_robot.move()
while my_robot.carries_beepers():
my_robot.drop_beeper()
turn_around()
my_robot.move()
my_robot.turn_left()
| 28 | 29 | code_explain | my_robot.carries_beepers()
To leave the beeper only when the stomach is true | cs1qa | null | null | null | null | null | Question:
How did you know when you didn't have a beeper?
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()
my_robot.set_trace("red")
def turn_right():
for i in range(3):
my_robot.turn_left()
def line():
while my_robot.front_is_clear():
my_robot.move()
while my_robot.on_beeper():
my_robot.pick_beeper()
def turn_around():
for i in range(2):
my_robot.turn_left()
line()
turn_around()
line()
turn_right()
my_robot.move()
while my_robot.carries_beepers():
my_robot.drop_beeper()
turn_around()
my_robot.move()
my_robot.turn_left()
|
1 | 1 | TA | In #2, please explain the function one_cycle and how you used it as a for statement! | from cs1robots import *
load_world("worlds/hurdles1.wld")
hubo=Robot()
hubo.set_trace("blue")
def turn_right():
hubo.turn_left()
hubo.turn_left()
hubo.turn_left()
def one_cycle():
hubo.move()
hubo.turn_left()
hubo.move()
turn_right()
hubo.move()
turn_right()
hubo.move()
hubo.turn_left()
for i in range(4):
one_cycle()
hubo.move()
hubo.pick_beeper() | 9 | 20 | variable | First, one_cycle is a function that shows the behavior of the robot moving one space and crossing the wall, and since this behavior was repeated 4 times, the code was written using a for statement. | cs1qa | null | null | null | null | null | Question:
In #2, please explain the function one_cycle and how you used it as a for statement!
Code:
from cs1robots import *
load_world("worlds/hurdles1.wld")
hubo=Robot()
hubo.set_trace("blue")
def turn_right():
hubo.turn_left()
hubo.turn_left()
hubo.turn_left()
def one_cycle():
hubo.move()
hubo.turn_left()
hubo.move()
turn_right()
hubo.move()
turn_right()
hubo.move()
hubo.turn_left()
for i in range(4):
one_cycle()
hubo.move()
hubo.pick_beeper() |
4 | 2 | TA | task 3: Why did you put i in each of the for statements like that? | import math
sin = math.sin
pi = math.pi
raw_steps=input("How many steps? ")
steps=int(raw_steps)
for i in range(steps+1):
x = float(i) / steps * 2 * pi
print (sin(x)) | 9 | 10 | reasoning | In this way, 0,1/40pi, 2/40pi changes the numerator value. | cs1qa | null | null | null | null | null | Question:
task 3: Why did you put i in each of the for statements like that?
Code:
import math
sin = math.sin
pi = math.pi
raw_steps=input("How many steps? ")
steps=int(raw_steps)
for i in range(steps+1):
x = float(i) / steps * 2 * pi
print (sin(x)) |
8 | 2 | TA | line 27 in task3
output.write(',')
Why do I need it? | import elice_utils
f=open("tpmon.txt","r")
data=[]
data2=[]
counts=0
for line in f:
data.append(line.strip())
count1=0
for i in range(1,len(data)):
data2.append(1722+i)
temp=data[i].split(" ")
temp2=[]
for i in range(len(temp)):
if temp[i]!='':
data2.append(float(temp[i]))
print(data2)
for i in range(int(len(data2)/13)):
winter_avg=(data2[13*i+1]+data2[13*i+2])/2
summer_avg=(data2[13*i+7]+data2[13*i+8])/2
print('%d: %6.1f / %4.1f' % (data2[i*13], winter_avg, summer_avg))
output=open("tpmon.csv","w")
for i in range(int(len(data2)/13)):
for j in range(13):
output.write(str(data2[13*i+j]))
output.write(',')
output.write('\n')
elice_utils.send_file('tpmon.csv') | 17 | 27 | reasoning | In the problem, I asked for, in the output file, but since there is no, in the list, I put it. | cs1qa | null | null | null | null | null | Question:
line 27 in task3
output.write(',')
Why do I need it?
Code:
import elice_utils
f=open("tpmon.txt","r")
data=[]
data2=[]
counts=0
for line in f:
data.append(line.strip())
count1=0
for i in range(1,len(data)):
data2.append(1722+i)
temp=data[i].split(" ")
temp2=[]
for i in range(len(temp)):
if temp[i]!='':
data2.append(float(temp[i]))
print(data2)
for i in range(int(len(data2)/13)):
winter_avg=(data2[13*i+1]+data2[13*i+2])/2
summer_avg=(data2[13*i+7]+data2[13*i+8])/2
print('%d: %6.1f / %4.1f' % (data2[i*13], winter_avg, summer_avg))
output=open("tpmon.csv","w")
for i in range(int(len(data2)/13)):
for j in range(13):
output.write(str(data2[13*i+j]))
output.write(',')
output.write('\n')
elice_utils.send_file('tpmon.csv') |
1 | 0 | TA | Can you see why it was so squeezed?
Why did you write to come back | from cs1robots import *
create_world ()
hubo = Robot ()
hubo.set_trace ( 'blue' )
def straight ():
for i in range (9):
hubo.move ()
def turn_right():
for i in range (3):
hubo.turn_left ()
def updown ():
straight ()
turn_right ()
hubo.move ()
turn_right ()
straight ()
def turnup ():
hubo.turn_left ()
hubo.move ()
hubo.turn_left ()
hubo.turn_left()
for i in range (4):
updown ()
turnup ()
updown ()
| null | null | reasoning | If you don’t come back, you have to change direction and then eat one line again.
I made it come back to use only one function for redirection. | cs1qa | null | null | null | null | null | Question:
Can you see why it was so squeezed?
Why did you write to come back
Code:
from cs1robots import *
create_world ()
hubo = Robot ()
hubo.set_trace ( 'blue' )
def straight ():
for i in range (9):
hubo.move ()
def turn_right():
for i in range (3):
hubo.turn_left ()
def updown ():
straight ()
turn_right ()
hubo.move ()
turn_right ()
straight ()
def turnup ():
hubo.turn_left ()
hubo.move ()
hubo.turn_left ()
hubo.turn_left()
for i in range (4):
updown ()
turnup ()
updown ()
|
4 | 2 | TA | Is there a reason to copy the contents of print_card as it is? | 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
global 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
sequence = []
for i in range(24):
sequence.append(i)
random.shuffle(sequence)
temp_cards = []
for i in range(24):
temp_cards.insert(sequence[i], cards[i])
cards = temp_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.
for value in correct_list:
if num1 == value or num2 == value:
return False
if num1 == num2:
return False
if type(num1) != int or type(num2) != int:
return False
if not ((num1 <=23 and num1 >= 0) and (num2 <=23 and num2 >= 0)):
return False
return True
###########################################################################
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.
###########################################################################
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
################################################################
if i == num1 or i == num2 or 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)
if cards[num1][1] == cards[num2][1]:
correct_list.extend((num1, num2))
return True
canvas.clear()
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.add(cards[i][0])
w += 100
if w % 600 == 0:
w = 0
h += 130
time.sleep(1)
print_cards()
return False
initialize()
canvas.clear()
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.add(cards[i][0])
w += 100
if w % 600 == 0:
w = 0
h += 130
time.sleep(1)
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.")
tries = tries + 1
###########################################################################
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!")
if len(correct_list) == 24:
print("You cleared this game")
break
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
###########################################################################
| 136 | 136 | reasoning | If it is just print_card(), the input card cannot be displayed, and changing the print_card() function became too complicated, so I did this | cs1qa | null | null | null | null | null | Question:
Is there a reason to copy the contents of print_card as it is?
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
global 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
sequence = []
for i in range(24):
sequence.append(i)
random.shuffle(sequence)
temp_cards = []
for i in range(24):
temp_cards.insert(sequence[i], cards[i])
cards = temp_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.
for value in correct_list:
if num1 == value or num2 == value:
return False
if num1 == num2:
return False
if type(num1) != int or type(num2) != int:
return False
if not ((num1 <=23 and num1 >= 0) and (num2 <=23 and num2 >= 0)):
return False
return True
###########################################################################
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.
###########################################################################
canvas.clear()
w = 0
h = 0
i_w = 70
i_h = 90
for i in range(len(num_pads)):
################################################################
if i == num1 or i == num2 or 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)
if cards[num1][1] == cards[num2][1]:
correct_list.extend((num1, num2))
return True
canvas.clear()
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.add(cards[i][0])
w += 100
if w % 600 == 0:
w = 0
h += 130
time.sleep(1)
print_cards()
return False
initialize()
canvas.clear()
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.add(cards[i][0])
w += 100
if w % 600 == 0:
w = 0
h += 130
time.sleep(1)
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.")
tries = tries + 1
###########################################################################
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!")
if len(correct_list) == 24:
print("You cleared this game")
break
###########################################################################
# 3-2-5. Update number of tries (global variable, tries)
###########################################################################
|
2 | 0 | TA | I was wondering why you inserted this part | from cs1robots import *
load_world('worlds/harvest3.wld')
hubo = Robot()
hubo.set_trace('blue')
def right():
hubo.turn_left()
hubo.turn_left()
hubo.turn_left()
def move_and_pick():
if hubo.on_beeper():
hubo.pick_beeper()
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
for i in range(7):
move_and_pick()
if not hubo.front_is_clear():
hubo.turn_left()
hubo.turn_left()
for t in range(2):
for i in range(5):
move_and_pick()
right()
hubo.move()
right()
for j in range(5):
move_and_pick()
hubo.turn_left()
hubo.move()
hubo.turn_left()
for i in range(5):
move_and_pick()
| null | null | reasoning | I see now
I don't think I have to use the if statement... | cs1qa | null | null | null | null | null | Question:
I was wondering why you inserted this part
Code:
from cs1robots import *
load_world('worlds/harvest3.wld')
hubo = Robot()
hubo.set_trace('blue')
def right():
hubo.turn_left()
hubo.turn_left()
hubo.turn_left()
def move_and_pick():
if hubo.on_beeper():
hubo.pick_beeper()
hubo.move()
if hubo.on_beeper():
hubo.pick_beeper()
for i in range(7):
move_and_pick()
if not hubo.front_is_clear():
hubo.turn_left()
hubo.turn_left()
for t in range(2):
for i in range(5):
move_and_pick()
right()
hubo.move()
right()
for j in range(5):
move_and_pick()
hubo.turn_left()
hubo.move()
hubo.turn_left()
for i in range(5):
move_and_pick()
|
6 | 0 | TA | Why did you float(upper_bound) in task1? | def fibonacci(upper_bound):
pass
A=[0,1]
C = True
while A[-1] < float(upper_bound):
a= A[-1]+A[-2]
A.append(a)
A.pop()
return A
print(fibonacci(1000))
| 4 | 4 | reasoning | When writing the code, I think I used a float because I thought it was a string because I was confused with the input function. | cs1qa | null | null | null | null | null | Question:
Why did you float(upper_bound) in task1?
Code:
def fibonacci(upper_bound):
pass
A=[0,1]
C = True
while A[-1] < float(upper_bound):
a= A[-1]+A[-2]
A.append(a)
A.pop()
return A
print(fibonacci(1000))
|
1 | 4 | TA | Is there any reason why you put in sleep?? | from cs1robots import*
import time
load_world("worlds/harvest2.wld")
hubo = Robot(beepers=1)
hubo.set_trace("blue")
time_speed = 0.05
def turn_right() :
for i in range(3) :
hubo.turn_left()
def diamond_pick(count) :
for i in range(count) :
hubo.pick_beeper()
turn_right()
time.sleep(time_speed)
hubo.move()
time.sleep(time_speed)
hubo.turn_left()
time.sleep(time_speed)
hubo.move()
time.sleep(time_speed)
def harvest() :
for i in range(5,0,-2) :
for j in range(4) :
diamond_pick(i)
hubo.turn_left()
for i in range(2) :
hubo.move()
time.sleep(time_speed)
for i in range(5) :
hubo.move()
time.sleep(time_speed)
hubo.turn_left()
hubo.move()
time.sleep(time_speed)
harvest() | 22 | 22 | reasoning | Oh, the speed was too frustrating, so I just adjusted it as a variable at once | cs1qa | null | null | null | null | null | Question:
Is there any reason why you put in sleep??
Code:
from cs1robots import*
import time
load_world("worlds/harvest2.wld")
hubo = Robot(beepers=1)
hubo.set_trace("blue")
time_speed = 0.05
def turn_right() :
for i in range(3) :
hubo.turn_left()
def diamond_pick(count) :
for i in range(count) :
hubo.pick_beeper()
turn_right()
time.sleep(time_speed)
hubo.move()
time.sleep(time_speed)
hubo.turn_left()
time.sleep(time_speed)
hubo.move()
time.sleep(time_speed)
def harvest() :
for i in range(5,0,-2) :
for j in range(4) :
diamond_pick(i)
hubo.turn_left()
for i in range(2) :
hubo.move()
time.sleep(time_speed)
for i in range(5) :
hubo.move()
time.sleep(time_speed)
hubo.turn_left()
hubo.move()
time.sleep(time_speed)
harvest() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.