Python Programming Puzzle: Median Finder

This is a Python puzzle from Codecademy. It involves writing a function to find the median in a list of numbers. Here’s the code:

array = []
x = raw_input(“Enter a number.”)

while x != “”:
array.append(x)
x = raw_input(“Anything else?”)

def median(list):
list2 = sorted(list)
length = len(list)
length2 = length/2
median = 0
if length == 1:
median = list[0]
elif length % 2 != 0:
for i in range(length):
if len(list2[0:i]) == len(list2[i+1:]):
median = list2[i]
elif length % 2 == 0:
sub_list1 = list2[0:length2]
sub_list2 = list2[length2:]
a = float(sub_list1[len(sub_list1)-1])
b = float(sub_list2[0])
median = (a + b) / 2
return median

print “The median of your list is”, median(array)

 

First thing to do is sort the list. Then, in a list with an odd number of items, the median, m, is the element in which the number elements before it is equal to the number of elements that it. For example,  in a list [1,2,3,4,5], the median is 3 because there are two numbers before 3 and two numbers after 3.  My program does that with the following code:

elif length % 2 != 0:
for i in range(length):
if len(list2[0:i]) == len(list2[i+1:]):
median = list2[i]

In a list with an even number of items. You simply divide the list into two halves, sub-list #1 and sub-list #2. Then the median is simply the sum of the last number in sub-list #1 and the first number in sub-list#2, divided by two. This is illustrated by the  following code:

elif length % 2 == 0:
sub_list1 = list2[0:length2]
sub_list2 = list2[length2:]
a = float(sub_list1[len(sub_list1)-1])
b = float(sub_list2[0])
median = (a + b) / 2

 

That’s it for today as I’m fairly tired from learning new stuff like Django and SQL.

Codility Puzzle: Equilibrium Element Array

This is a puzzle I read about that was once offered by Codility. The puzzle involves creating a function that will calculate the equilibrium element of an array. The equilibrium element of an array is the element in which the sum of all elements before it is equal to the sum of all the elements after it. For example, in an array x = [1,2,8,1,2], the equilibrium element is 8 because the sum of all numbers before 8 is (1+2) = 3 and the sum of all numbers after 8 is (1+2) = 3. If there is no equilibrium element, the function returns -1.

Anyway, here’s my attempt at it (code in Ruby):

def equi(a)
b = []
for i in (0…a.length)
sum1 = 0
sum2 = 0

for j in (0…i)
sum1 = sum1 + a[j]
end

for k in (i+1…a.length)
sum2 = sum2 + a[k]
end

if sum1 == sum2
b.push(a[i])
end
end

if b.length > 0
return b
else
return “-1″
end
end

Basically, you create a for-loop that has 2 nested for-loops within it. One of the nested for-loops scans for all numbers that came before the current element and finds their sum. The other nested for-loop scans all numbers that comes after the current element and finds their sum. If the sum from the two nested for-loops are equal, then the current element is an equilibrium element. If we don’t get an equilibrium index, we return -1.

Learning Web Development: Rails or Django or other?

Well, I’ve decided to learn some web development. Rails seems to be the hot topic so I tried it out first. Man did I get stumped. I tried going through Michael Hartl’s tutorial and also Agile Web Development with Rails but after following along for a few chapters, my rails app would not work. I would get some sort of error even though I’m pretty damn sure I followed every single instruction down to the letter. Heck I actually went through some examples 3-4 times to make sure I didn’t miss anything. Maybe it’s just me, or maybe it’s my outdated laptop. But in any case, I decided to ditch Rails for now and return later.  Besides, I also found that a lot of Rails tutorials just tell you to type this code and that code inside this file and that file. Yes, there are attempts to explain the reasoning and the concepts but it was all lost on me. Most likely because I’m a complete newb when it comes to web development. I just don’t think Rails is a good fit for a newbie like me. I decided I would try something else.

Enter Django. Well, so far, everything seems to be going alright with only a few tiny bumps along the road. But what I really liked about Django over Rails is the documentation: it’s far more newbie-friendly than Rails’. I’m not saying Django is better than Rails nor do I want to turn this into a Django vs. Rails post. But for MY current situation, Django just seems like a better fit. We’ll see if this continues to hold true as I progress deeper into the Django Book tutorial or if I will inevitably run into some sort of error sh!+show. As my computer science teacher from high school used to tell us: “Plug and Pray!” XD

Lotto 649 in Javascript – Part 3

This will be the final post in the Lotto 649 in Javascript series. Let’s analyze the ticket generator and ticket comparison functions. Here’s the code:

/* Generate user ticket. Quick pick is an option
to have your numbers randomly selected by a machine. */
choice = prompt (“Would you like quick pick?”);
if (choice === “yes”){
ticket_maker(user_ticket);
}
else if (choice === “no”){
for (var i = 0; i < 6; i++){
user_number = prompt (“Pick a number between 1 and 50″);
user_ticket[i] = user_number;

/* Following if-conditional checks for duplicate
numbers, which are not allowed */
if (i > 0){
for (var k = 0; k < i; k++){
if (user_ticket[i] === user_ticket[k]){
console.log(“Can’t pick the same number more than once.”);
i–;
}
}
}
}
}

//Generate winning ticket.
ticket_maker(win_ticket);

//Compare tickets.
for (var i = 0; i < user_ticket.length; i ++){
for(var k = 0; k < win_ticket.length; k++){
if (user_ticket[i] === win_ticket[k]){
match += win_ticket[k] + ” “;
count++;
}
}
}

//Output messages and corresponding rewards, if any.
console.log(“Your numbers are: ” + user_ticket);
console.log(“Winning numbers are: ” + win_ticket);
console.log(“Number of matches: ” + count);
console.log(“Matching numbers are: ” + match);

switch (count){
case 1: console.log(“No rewards. Need a minimum of 2 matching numbers. Better luck next time!”); break;
case 2: console.log(“You win $5!”); break;
case 3: console.log(“You win $10!”); break;
case 4: console.log(“You win $1,000!”); break;
case 5: console.log(“You win $100,000!”); break;
case 6: console.log(“You win the jackpot for $50,000,000!!! CONGRATULATIONS!!!”);
}

Number 1: User ticket generator function.

Nothing fancy here. The only real work comes from the else-if part of the conditional, specifically the part where it checks for duplicate numbers. I created a for-loop that asks for user’s pick and nested within the for-loop, is a another for-loop that scans the user input against all previous user input. If a duplicate is found, the first for-loop incrementer is decreased by one so it replicates the effect of “scrapping” the most recent user number pick because it’s a duplicate.

 

Number 2: Ticket comparison function and results

Once again, I used two for-loops, one nested within another, to compare the user ticket and the winning ticket. The first for-loop scans through all user number picks. The second for-loop that’s nested within the first for-loop checks each user number pick against every single number generated by the winning ticket. If there is a match, the variable “count” is increased by 1. The “count” variable is used to help us determine the rewards, if any, the user will get. To determine the user’s prize, I simply used the “switch” syntax.

And that’s it  for Lotto 649 in Javascript!

 

 

Lotto 649 in Javascript – Part 2

As I mentioned in my first post of Javascript Lotto 649, I’m going to break down the code into sections and explain each of them. So here’s the ticket generator. It’s used for generating a winning ticket and also for the user if he/she decides to go with the automated quick-pick.

The for-loop – let’s call it For-Loop A – iterates 6 times. For each iteration, it generates a random number between 1 and 50. To prevent duplicates, I did a second for-loop – call it For-Loop B -  that’s nested within the first for-loop. For-Loop B gets executed if more than 1 random number has been generated. Then, For-Loop B scans over the previous numbers generated to see if the current number generated by For-Loop A is the same. If it is, it decrements the count on For-Loop A so that it “scraps” its most recent iteration and has to generate another random number.

/* Ticket maker function. The for-loop checks for
duplicate numbers, which are not allowed. */
var ticket_maker = function(ticket){
for (var i = 0; i < 6; i++){
ticket[i] = Math.floor(Math.random()*50+1);
if (i > 0){
for (var k = 0; k < i; k++){
if (ticket[i] === ticket[k]){
i = i – 1;
}
}
}
}
return ticket;
};

That’s it  for now, and on my next post, I will discuss the user input and ticket comparisons.

Lotto 649 in Javascript – Part 1

This is a program that simulates the Lotto 649 here in Canada. It’s written in Javascript and I simply did it for fun, and to sharpen my coding skills. Here’s the code for it:

//Declare variables and functions
var user_ticket = [];
var win_ticket = [];
var choice = “”;
var user_number = 0;
var count = 0;
var match = [];

/* Ticket maker function. The for-loop checks for
duplicate numbers, which are not allowed. */
var ticket_maker = function(ticket){
for (var i = 0; i < 6; i++){
ticket[i] = Math.floor(Math.random()*50+1);
if (i > 0){
for (var k = 0; k < i; k++){
if (ticket[i] === ticket[k]){
i = i – 1;
}
}
}
}
return ticket;
};

/* Step 1: Generate user ticket. Quick pick is an option
to have your numbers randomly selected by a machine. */
choice = prompt (“Would you like quick pick?”);
if (choice === “yes”){
ticket_maker(user_ticket);
}
else if (choice === “no”){
for (var i = 0; i < 6; i++){
user_number = prompt (“Pick a number between 1 and 50″);
user_ticket[i] = user_number;

/* Following if-conditional checks for duplicate
numbers, which are not allowed */
if (i > 0){
for (var k = 0; k < i; k++){
if (user_ticket[i] === user_ticket[k]){
console.log(“Can’t pick the same number more than once.”);
i = i – 1;
}
}
}
}
}

//Step 2: Generate winning ticket.
ticket_maker(win_ticket);

//Step 3: Compare tickets.
for (var i = 0; i < user_ticket.length; i ++){
for(var k = 0; k < win_ticket.length; k++){
if (user_ticket[i] === win_ticket[k]){
match += win_ticket[k] + ” “;
count++;
}
}
}

//Output messages and corresponding rewards, if any.
console.log(“Your numbers are: ” + user_ticket);
console.log(“Winning numbers are: ” + win_ticket);
console.log(“Number of matches: ” + count);
console.log(“Matching numbers are: ” + match);

switch (count){
case 1: console.log(“No rewards. Need a minimum of 2 matching numbers. Better luck next time!”); break;
case 2: console.log(“You win $5!”); break;
case 3: console.log(“You win $10!”); break;
case 4: console.log(“You win $1,000!”); break;
case 5: console.log(“You win $100,000!”); break;
case 6: console.log(“You win the jackpot for $50,000,000!!! CONGRATULATIONS!!!”);
}

On my following posts, I’ll break down the code and explain each section :)

My first blog post

Hi my name is Dex. I’m currently learning how to program with Codecademy and I’m enjoying the lessons immensely.  I’m familiar with the basics of Javascript, HTML, CSS, Ruby, and Python. This blog is intended to document my journey from beginner programmer to proficient programmer. I will post snippets of code, projects, and programming puzzles and share my thoughts on them. My coding projects are also available on github at github.com/dexx1220. More to come in the near future!