Sign InCoursewareNuggetsTutorials CoursesCodePad

Sort the Colorful Balls

You have seven balls with different sizes and colors. Sort them to make them increase in size. Here is a sample drawing before and after the balls are sorted. You may choose either selection sort or insertion sort. Have fun!

import turtle import random class Ball: def __init__(self, radius, color): self.radius = radius self.color = color def draw(self, t): t.begin_fill() t.color(self.color) t.circle(self.radius) t.end_fill() def draw_balls(balls, t): for b in balls: t.forward(b.radius) t.down() b.draw(t) t.up() t.forward(b.radius + 10) def sort_balls(balls): for unsorted_start in range(len(balls)): min_index = unsorted_start for i in range(unsorted_start+1, len(balls)): if balls[i].radius < balls[min_index].radius: min_index = i balls[unsorted_start], balls[min_index] = balls[min_index], balls[unsorted_start] def main(): screen = turtle.Screen() screen.setup(600, 350) t = turtle.Turtle() t.speed(0) t.hideturtle() t.up() t.goto(-280, 60) radius_array = [40, 35, 30, 25, 20, 15, 10] color_array = ['red', 'orange', 'yellow', 'green', 'blue', 'violet', 'purple'] balls = [] for i in range(7): balls.append(Ball(radius_array[i], color_array[i])) random.shuffle(balls) draw_balls(balls, t) sort_balls(balls) t.up() t.goto(-280, -60) draw_balls(balls, t) main()

import turtle import random class Ball: def __init__(self, radius, color): self.radius = radius self.color = color def draw(self, t): t.begin_fill() t.color(self.color) t.circle(self.radius) t.end_fill() def draw_balls(balls, t): for b in balls: t.forward(b.radius) t.down() b.draw(t) t.up() t.forward(b.radius + 10) def sort_balls(balls): # TODO: Sort the balls in accending order of radius. Use selection sort or insertion sort. def main(): screen = turtle.Screen() screen.setup(600, 350) t = turtle.Turtle() t.speed(0) t.hideturtle() t.up() t.goto(-280, 60) radius_array = [40, 35, 30, 25, 20, 15, 10] color_array = ['red', 'orange', 'yellow', 'green', 'blue', 'violet', 'purple'] balls = [] for i in range(7): balls.append(Ball(radius_array[i], color_array[i])) random.shuffle(balls) draw_balls(balls, t) sort_balls(balls) t.up() t.goto(-280, -60) draw_balls(balls, t) main()

© CS Wonders·About·Gallery·Fun Facts·Cheatsheet