You're responsible for providing a demographic report for your local school district based on age.
To do this, you're going determine which 'category' each person fits into based on their age.

The person's age will determine which category they should be in:

If they're from 0 to 2 the child should be with parents print : 'Still in Mama's arms'
If they're 3 or 4 and should be in preschool print : 'Preschool Maniac'
If they're from 5 to 11 and should be in elementary school print : 'Elementary school'
From 12 to 14: 'Middle school'
From 15 to 18: 'High school'
From 19 to 22: 'College'
From 23 to 65: 'Working for the man'
From 66 to 100: 'The Golden Years'
If the age of the person less than 0 or more than 100 - it might be an alien - print: "This program is for humans"

Input sample:

Your program should accept as its first argument a path to a filename.
Each line of input contains one integer - age of the person:

0
19

Output sample:

For each line of input print out where the person is:

Still in Mama's arms
College

Penultimate Word

Challenge Description:

Write a program which finds the next-to-last word in a string.

Input sample:

Your program should accept as its first argument a path to a filename. Input example is the following

some line with text
another line

Each line has more than one word.

Output sample:

Print the next-to-last word in the following way.

with
another

Even Numbers

Challenge Description:

Write a program which checks input numbers and determines
whether a number is even or not.

Input sample:

Your program should accept as its first argument a path to a filename.
Input example is the following

701
4123
2936

Output sample:

Print 1 if the number is even or 0 if the number is odd.

0
0
1

All numbers in input are integers > 0 and < 5000.

Panacea - truth or lie

Challenge Description:

There are many computer and human viruses nowadays. Scientists are scratching their heads over antiviruses that
could stop a particular virus and, in most cases, they find right solutions.
So, virologists need to know which antiviruses can protect us from viruses, and what they still have to work on
to secure against the remaining viruses. Let’s help them out!

Input sample:

The first argument is a path to a file. Each line includes a test case with virus components in the hexadecimal
numeral system (HEX) and antivirus components in the binary number system (BIN). Virus and antivirus components
are separated by a pipeline '|'.

64 6e 78 | 100101100 11110
5e 7d 59 | 1101100 10010101 1100111
93 75 | 1000111 1011010 1100010

Output sample:

Your task is to calculate the sum of all virus components and compare it with the sum of antivirus components.
If the numbers are the same or the sum of antivirus components is greater than the sum of virus components,
this means that the virus was stopped. So, print True. Otherwise, print False.

True
True
False

Constraints:

The sum of components can be from 60 to 1500.

The number of components in virus and antivirus can be from 1 to 8.

The number of test cases is 40.

Swap Case

Challenge Description:

Write a program which swaps letters' case in a sentence.
All non-letter characters should remain the same.

Input sample:

Your program should accept as its first argument a path to a filename. Input example is the following

Hello world!
JavaScript language 1.8
A letter

Output sample:

Print results in the following way.

hELLO WORLD!
jAVAsCRIPT LANGUAGE 1.8
a LETTER

Simple Sorting

Challenge Description:

Write a program which sorts numbers.

Input sample:

Your program should accept as its first argument a path to a filename. Input example is the following

The goal of this challenge is to design a cash register program.
You will be given two float numbers. The first is the purchase price (PP) of the item.
The second is the cash (CH) given by the customer.
Your register currently has the following bills/coins within it:

The aim of the program is to calculate the change that has to be returned to the customer.

Input sample:

Your program should accept as its first argument a path to a filename.
The input file contains several lines. Each line is one test case.
Each line contains two numbers which are separated by a semicolon.
The first is the Purchase price (PP) and the second is the cash(CH) given by the customer. eg.

15.94;16.00
17;16
35;35
45;50

Output sample:

For each set of input produce a single line of output which is the change to be returned to the customer.
In case the CH < PP, print out ERROR. If CH == PP, print out ZERO.
For all other cases print the amount that needs to be returned, in terms of the currency values provided.
The output should be sorted in highest-to-lowest order (DIME,NICKEL,PENNY). eg.

NICKEL,PENNY
ERROR
ZERO
FIVE

Armstrong Numbers

Challenge Description:

An Armstrong number is an n-digit number that is equal to the sum of
the n'th powers of its digits. Determine if the input numbers
are Armstrong numbers.

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file has a positive integer. E.g.

6
153
351

Output sample:

Print out True/False if the number is an Armstrong number or not. E.g.

True
True
False

Hex to Decimal

Challenge Description:

You will be given a hexadecimal (base 16) number.
Convert it into decimal (base 10).

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file contains a hex number. You may assume that
the hex number does not have the leading 'Ox'. Also all alpha
characters (a through f) in the input will be in lowercase.
E.g.

9f
11

Output sample:

Print out the equivalent decimal number. E.g.

159
17

N Mod M

Challenge Description:

Given two integers N and M, calculate N Mod M
(without using any inbuilt modulus operator).

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file contains two comma separated positive integers.
E.g.

20,6
2,3

You may assume M will never be zero.

Output sample:

Print out the value of N Mod M

Query Board

Challenge Description:

There is a board (matrix). Every cell of the board contains one integer,
which is 0 initially.

The next operations can be applied to the Query Board:
SetRow i x: it means that all values in the cells on row "i" have been changed to value "x" after this operation.
SetCol j x: it means that all values in the cells on column "j" have been changed to value "x" after this operation.
QueryRow i: it means that you should output the sum of values
on row "i".
QueryCol j: it means that you should output the sum of values on column "j".

The board's dimensions are 256x256
"i" and "j" are integers from 0 to 255
"x" is an integer from 0 to 31

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file contains an operation of a query. E.g.

For each query, output the answer of the query. E.g.

5118
34
1792
3571

Beautiful Strings

Challenge Description:

Credits: This problem appeared in the Facebook Hacker Cup 2013 Hackathon.

When John was a little kid he didn't have much to do. There was no
internet, no Facebook, and no programs to hack on. So he did the only
thing he could... he evaluated the beauty of strings in a quest to
discover the most beautiful string in the world.

Given a string s, little Johnny defined the beauty of the string as the
sum of the beauty of the letters in it. The beauty of each letter is an
integer between 1 and 26, inclusive, and no two letters have the
same beauty. Johnny doesn't care about whether letters are uppercase
or lowercase, so that doesn't affect the beauty of a letter.
(Uppercase 'F' is exactly as beautiful as lowercase 'f', for example.)

You're a student writing a report on the youth of this famous hacker.
You found the string that Johnny considered most beautiful. What is the
maximum possible beauty of this string?

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file has a sentence. E.g.

ABbCcc
Good luck in the Facebook Hacker Cup this year!
Ignore punctuation, please :)
Sometimes test cases are hard to make up.
So I just go consult Professor Dalves

Output sample:

Print out the maximum beauty for the string. E.g.

152
754
491
729
646

Decode Numbers

Challenge Description:

You are given an encoded message containing only numbers. You are also
provided with the following mapping:

A : 1
B : 2
C : 3
...
Z : 26

Given an encoded message, count the number of ways it can be decoded.

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file is a test-case and contains an encoded message of
numbers. E.g.

12
123

You may assume that the test cases contain only numbers.

Output sample:

Print out the different number of ways it can be decoded. E.g.

2
3

NOTE: 12 could be decoded as AB(1 2) or L(12). Hence the number of ways to decode 12 is 2.

Counting Primes

Challenge Description:

Given two integers N and M, count the number of prime numbers
between N and M (both inclusive)

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file contains two comma separated positive integers. E.g.

2,10
20,30

Output sample:

Print out the number of primes between N and M (both inclusive)

4
2

Sum to Zero

Challenge Description:

You are given an array of integers. Count the numbers of ways in which the
sum of 4 elements in this array results in zero.

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file consist of comma separated positive and negative
integers. E.g.

2,3,1,0,-4,-1
0,-1,3,-2

Output sample:

Print out the count of the different number of ways that 4 elements
sum to zero. E.g.

2
1

Spiral Printing

Challenge Description:

Write a program to print a 2D array (n x m) in spiral order (clockwise)

Input sample:

Your program should accept as its first argument a path to a filename.
The input file contains several lines. Each line is one test case.
Each line contains three items (semicolon delimited). The first
is 'n'(rows), the second is 'm'(columns) and the third is a single
space separated list of characters/numbers in row major
order. E.g.

3;3;1 2 3 4 5 6 7 8 9

Output sample:

Print out the matrix in clockwise fashion, one per line,
space delimited. E.g.

1 2 3 6 9 8 7 4 5

URI Comparison

Challenge Description:

Determine if two URIs match. For the purpose of this challenge, you should
use a case-sensitive octet-by-octet comparison of the entire URIs,
with these exceptions:

1. A port that is empty or not given is equivalent to the default port of 80
2. Comparisons of host names MUST be case-insensitive
3. Comparisons of scheme names MUST be case-insensitive
4. Characters are equivalent to their % HEX HEX encodings. (Other than typical reserved characters in urls like , / ? : @ & = + $ #)

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file contains two urls delimited by a semicolon. E.g.

You are given two strings. Determine if the second string is a rotation
of the first string.

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file contains two comma separated strings. E.g.

Hello,lloHe
Basefont,tBasefon

Output sample:

Print out True/False if the second string is a rotation of the first. E.g.

True
True

String Substitution

Challenge Description:

Credits: This challenge was contributed by Sam McCoy

Given a string S, and a list of strings of positive length,
F1,R1,F2,R2,...,FN,RN, proceed to find in order the occurrences
(left-to-right) of Fi in S and replace them with Ri. All strings are
over alphabet { 0, 1 }. Searching should consider only contiguous pieces
of S that have not been subject to replacements on prior iterations.
An iteration of the algorithm should not write over any
previous replacement by the algorithm.

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file is one test case. Each test case will contain
a string, then a semicolon and then a list of comma separated strings. E.g.

10011011001;0110,1001,1001,0,10,11

Output sample:

For each line of input, print out the string after substitutions have
been made.eg.

11100110

For the curious, here are the transitions for the above example:
10011011001 => 10100111001 [replacing 0110 with 1001] =>
10100110 [replacing 1001 with 0] =>
11100110 [replacing 10 with 11]. So the answer is 11100110

Telephone Words

Challenge Description:

Given a 7 digit telephone number, print out all the possible sequences of letters that can represent
the given telephone number. Note that in a standard 12 key pad, 0 and 1 do not have any letters associated
with them. They are to be treated as such, i.e. a 0/1 in the telephone number will be retained in the final
word as well. You may use the following mapping between numbers and characters:

Credits: Programming Challenges by Steven S. Skiena and Miguel A. Revilla

A sequence of n > 0 integers is called a jolly jumper if the absolute values of the differences
between successive elements take on all possible values 1 through n - 1. eg.

1 4 2 3

is a jolly jumper, because the absolute differences are 3, 2, and 1, respectively.
The definition implies that any sequence of a single integer is a jolly jumper. Write a program to determine
whether each of a number of sequences is a jolly jumper.

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file is one test case. Each test case will contain an integer n < 3000 followed by n integers
representing the sequence. The integers are space delimited.

For example:

4 1 4 2 3
3 7 7 8
9 8 9 7 10 6 12 17 24 38

Output sample:

For each line of input generate a line of output saying 'Jolly' or 'Not jolly'.

For example:

Jolly
Not jolly
Not jolly

Following Integer

Challenge Description:

Credits: This challenge has appeared in a past google competition

You are writing out a list of numbers.Your list contains all numbers with exactly
Di digits in its decimal representation which are equal to i, for each i between 1 and 9, inclusive.
You are writing them out in ascending order. For example, you might be writing every number with
two '1's and one '5'. Your list would begin 115, 151, 511, 1015, 1051. Given N,
the last number you wrote, compute what the next number in the list will be.
The number of 1s, 2s, ..., 9s is fixed but the number of 0s is arbitrary.

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file is one test case. Each test case will contain an integer n < 10^6. E.g.

115
842
8000

Output sample:

For each line of input, generate a line of output which is the next integer in the list. E.g.

151
2048
80000

Ugly Numbers

Challenge Description:

Credits: This challenge has appeared in a google competition before.

Once upon a time in a strange situation, people called a number ugly
if it was divisible by any of the one-digit primes (2, 3, 5 or 7).
Thus, 14 is ugly, but 13 is fine. 39 is ugly, but 121 is not.
Note that 0 is ugly. Also note that negative numbers can also be ugly:
-14 and -39 are examples of such numbers.

One day on your free time, you are gazing at a string of digits,
something like:

123456

You are amused by how many possibilities there are if you are allowed
to insert plus or minus signs between the digits. For example you
can make:

1 + 234 - 5 + 6 = 236

which is ugly. Or

123 + 4 - 56 = 71

which is not ugly.

It is easy to count the number of different ways you can play with the
digits: Between each two adjacent digits you may choose put a plus sign,
a minus sign, or nothing. Therefore, if you start with D digits there
are 3^(D-1) expressions you can make. Note that it is fine to have
leading zeros for a number. If the string is '01023', then '01023',
'0+1-02+3' and '01-023' are legal expressions.

Your task is simple: Among the 3^(D-1) expressions, count how many of
them evaluate to an ugly number.

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file is one test case. Each test case will be a single
line containing a non-empty string of decimal digits. The string in
each test case will be non-empty and will contain only characters '0'
through '9'. Each string is no more than 13 characters long. E.g.

1
9
011
12345

Output sample:

Print out the number of expressions that evaluate to an ugly number for
each test case, each one on a new line. E.g.

0
1
6
64

Peak Traffic

Challenge Description:

Credits: This challenge is from the facebook engineering puzzles

Facebook is looking for ways to help users find out which friends they interact with the most on the site.
Towards that end, you have collected data from your friends regarding who they interacted with on the site.
Each piece of data represents a desirable but one-way interaction between one user of Facebook towards another
user of Facebook. By finding groups of users who regularly interact with one another, you hope to help users
determine who among their friends they spend the most time with online.

Being a popular user, you have collected a lot of data; so much that you cannot possibly process it by hand.
But being a programmer of no small repute, you believe you can write a program to do the analysis for you. You
are interested in finding clusters of users within your data pool; in other words, groups of users who interact
among one another. A cluster is defined as a set of at least three users, where every possible permutation of two
users within the cluster have both received and sent some kind of interaction between the two.

With your program, you wish to analyze the collected data and find out all clusters within.

Input sample:

Your program should accept as its first argument a path to a filename. The input file consists of multiple lines
of aggregated log data. Each line starts with a date entry, whose constituent parts are separated by single white
spaces. The exact format of the date always follows the examples given below. Following the date is a single tab,
and then the email address of the user who is performing the action. Following that email is another single tab and
then finally the email of the Facebook user who receives the action. The last line of the file may or may not have
a newline at its end.

Thu Dec 11 17:53:01 PST 2008 a@facebook.com b@facebook.com
Thu Dec 11 17:53:02 PST 2008 b@facebook.com a@facebook.com
Thu Dec 11 17:53:03 PST 2008 a@facebook.com c@facebook.com
Thu Dec 11 17:53:04 PST 2008 c@facebook.com a@facebook.com
Thu Dec 11 17:53:05 PST 2008 b@facebook.com c@facebook.com
Thu Dec 11 17:53:06 PST 2008 c@facebook.com b@facebook.com
Thu Dec 11 17:53:07 PST 2008 d@facebook.com e@facebook.com
Thu Dec 11 17:53:08 PST 2008 e@facebook.com d@facebook.com
Thu Dec 11 17:53:09 PST 2008 d@facebook.com f@facebook.com
Thu Dec 11 17:53:10 PST 2008 f@facebook.com d@facebook.com
Thu Dec 11 17:53:11 PST 2008 e@facebook.com f@facebook.com
Thu Dec 11 17:53:12 PST 2008 f@facebook.com e@facebook.com

Every line in the input file will follow this format, you are guaranteed that your submission will run against
well formed input files.

Output sample:

You must output all clusters detected from the input log file with size of at least 3 members.
A cluster is defined as N >= 3 users on Facebook that have send and received actions between all possible
permutations of any two members within the cluster.

Your program should print to standard out, exactly one cluster per line. Each cluster must have its member user
emails in alphabetical order, separated by a comma and a single space character each. There must not be a comma
(or white space) after the final email in the cluster; instead print a single new line character at the end of
every line. The clusters themselves must be printed to standard out also in alphabetical order; treat each cluster
as a whole string for purposes of alphabetical comparisons. Do not sort the clusters by size or any other criteria.

Finally, any cluster that is a sub-cluster (in other words, all users within one cluster are also present in another)
must be removed from the output. For this case, your program should only print the largest super-cluster that
includes the other clusters. Your program must be fast, efficient, and able to handle extremely large input files.

Message Decoding

Challenge Description:

Credits: This challenge has appeared in a past ACM competition.

Some message encoding schemes require that an encoded message be sent in two parts. The first part,
called the header, contains the characters of the message. The second part contains a pattern that
represents the message.You must write a program that can decode messages under such a scheme.

The heart of the encoding scheme for your program is a sequence of "key" strings of 0's and 1's as follows:
0,00,01,10,000,001,010,011,100,101,110,0000,0001,. . .,1011,1110,00000, . . .

The first key in the sequence is of length 1, the next 3 are of length 2, the next 7 of length 3, the next 15
of length 4, etc. If two adjacent keys have the same length, the second can be obtained from the first by adding 1
(base 2). Notice that there are no keys in the sequence that consist only of 1's.

The keys are mapped to the characters in the header in order. That is, the first key (0) is mapped to the first
character in the header, the second key (00) to the second character in the header, the kth key is mapped to the
kth character in the header. For example, suppose the header is:

AB#TANCnrtXc

Then 0 is mapped to A, 00 to B, 01 to #, 10 to T, 000 to A, ..., 110 to X, and 0000 to c.

The encoded message contains only 0's and 1's and possibly carriage returns, which are to be ignored.
The message is divided into segments. The first 3 digits of a segment give the binary representation of the
length of the keys in the segment. For example, if the first 3 digits are 010, then the remainder of the segment
consists of keys of length 2 (00, 01, or 10). The end of the segment is a string of 1's which is the same length
as the length of the keys in the segment. So a segment of keys of length 2 is terminated by 11. The entire encoded
message is terminated by 000 (which would signify a segment in which the keys have length 0). The message is
decoded by translating the keys in the segments one-at-a-time into the header characters to which they have
been mapped.

Input sample:

The input file contains several data sets. Each data set consists of a header and a message.
These will all be on one line. The length of the header is limited only by the fact that key strings have a maximum
length of 7 (111 in binary). If there are multiple copies of a character in a header, then several keys will map to
that character. The encoded message contains only 0's and 1's, and it is a legitimate encoding according to the
described scheme. That is, the message segments begin with the 3-digit length sequence and end with the appropriate
sequence of 1's. The keys in any given segment are all of the same length, and they all correspond to characters in
the header. The message is terminated by 000.
Your program should accept the first argument as the filename and read the contents of this file as the test data,
according to the conditions above. E.g.

$#**\0100000101101100011100101000

Output sample:

For each data set, your program must write its decoded message on a separate line.
There should not be blank lines between messages. E.g.

##*\$

Longest Common Subsequence

Challenge Description:

You are given two sequences. Write a program to determine the longest
common subsequence between the two strings (each string can have
a maximum length of 50 characters).
NOTE: This subsequence need not be contiguous.
The input file may contain empty lines,
these need to be ignored.

Input sample:

The first argument will be a path to a filename that contains two strings per line,
semicolon delimited. You can assume that there is only
one unique subsequence per test case. E.g.

XMJYAUZ;MZJAWXU

Output sample:

The longest common subsequence. Ensure that there are no trailing empty spaces on each line you print. E.g.

MJAU

Stack Implementation

Challenge Description:

Write a program which implements a stack interface for integers. The interface should have ‘push’ and ‘pop’
functions. Your task is to ‘push’ a series of integers and then ‘pop’ and print every alternate integer.

Input sample:

Your program should accept a file as its first argument. The file contains a series of space delimited integers, one per line.

For example:

1 2 3 4
10 -2 3 4

Output sample:

Print to stdout every alternate space delimited integer, one per line.

For example:

4 2
4 -2

Number of Ones

Challenge Description:

Write a program which determines the number of 1 bits in the internal representation of a given integer.

Input sample:

The first argument is a path to a file. The file contains integers, one per line.

For example:

10
22
56

Output sample:

Print to stdout the number of ones in the binary form of each number.

For example:

2
3
3

Double Squares

Challenge Description:

Credits: This challenge appeared in the Facebook Hacker Cup 2011.

A double-square number is an integer X which can be expressed as the sum
of two perfect squares. For example, 10 is a double-square because
10 = 3^2 + 1^2. Your task in this problem is, given X, determine the
number of ways in which it can be written as the sum of two squares.

For example, 10 can only be written as 3^2 + 1^2
(we don't count 1^2 + 3^2 as being different).
On the other hand, 25 can be written as 5^2 + 0^2 or as 4^2 + 3^2.
NOTE: Do NOT attempt a brute force approach. It will not work.
The following constraints hold:
0 <= X <= 2147483647
1 <= N <= 100

Input sample:

Your program should accept as its first argument a path to a filename.
You should first read an integer N, the number of test cases.
The next N lines will contain N values of X.

5
10
25
3
0
1

Output sample:

E.g.

1
2
0
1
1

Lowest Common Ancestor

Challenge Description:

Write a program to determine the lowest common ancestor of two nodes in a binary search tree. You may hardcode the
following binary search tree in your program:

The first argument is a path to a file that contains two values. These values represent two nodes within the tree,
one per line. E.g.:

8 52
3 29

Output sample:

Print to stdout the lowest common ancestor, one per line. Lowest means the lowest depth in the tree,
not the lowest value. E.g.:

30
8

Set Intersection

Challenge Description:

You are given two sorted list of numbers (ascending order). The lists
themselves are comma delimited and the two lists are semicolon
delimited. Print out the intersection of these two sets.

Input sample:

File containing two lists of ascending order sorted integers, comma
delimited, one per line. E.g.

Print out the ascending order sorted intersection of the two lists,
one per line. Print empty new line in case the lists have
no intersection. E.g.

4
8,9

Trailing String

Challenge Description:

There are two strings: A and B. Print 1 if string B occurs at the end of string
A. Otherwise, print 0.

Input sample:

The first argument is a path to the input filename containing two comma-delimited strings, one per line.
Ignore all empty lines in the input file.

For example:

Hello World,World
Hello CodeEval,CodeEval
San Francisco,San Jose

Output sample:

Print 1 if the second string occurs at the end of the first string. Otherwise, print 0.

For example:

1
1
0

String List

Challenge Description:

Credits: Challenge contributed by Max Demian.

You are given a number N and a string S. Print all of the possible ways to write a string of length N from the
characters in string S, comma delimited in alphabetical order.

Input sample:

The first argument will be the path to the input filename containing the test data.
Each line in this file is a separate test case. Each line is in the format: N,S i.e.
a positive integer, followed by a string (comma separated). E.g.

1,aa
2,ab
3,pop

Output sample:

Print all of the possible ways to write a string of length N from the characters in string S comma
delimited in alphabetical order, with no duplicates. E.g.

a
aa,ab,ba,bb
ooo,oop,opo,opp,poo,pop,ppo,ppp

String Searching

Challenge Description:

You are given two strings. Determine if the second string is a substring of the first
(Do NOT use any substr type library function). The second string may contain an asterisk(*)
which should be treated as a regular expression i.e. matches zero or more characters. The asterisk can be escaped
by a \ char in which case it should be interpreted as a regular '*' character. To summarize: the strings can contain
alphabets, numbers, * and \ characters.

Input sample:

Your program should accept as its first argument a path to a filename.
The input file contains two comma delimited strings per line. E.g.

Hello,ell
This is good, is
CodeEval,C*Eval
Old,Young

Output sample:

If the second string is indeed a substring of the first, print out a 'true'(lowercase), else print out a
'false'(lowercase), one per line. E.g.

true
true
true
false

String Permutations

Challenge Description:

Write a program which prints all the permutations of a string in alphabetical order. We consider that digits < upper
case letters < lower case letters. The sorting should be performed in ascending order.

Input sample:

Your program should accept a file as its first argument. The file contains input strings, one per line.

For example:

hat
abc
Zu6

Output sample:

Print to stdout the permutations of the string separated by comma, in alphabetical order.

You are given a prefix expression. Write a program which evaluates it.

Input sample:

Your program should accept a file as its first argument. The file contains one prefix expression per line.

For example:

* + 2 3 4

Your program should read this file and insert it into any data structure you like. Traverse this data structure
and evaluate the prefix expression. Each token is delimited by a whitespace. You may assume that sum ‘+’,
multiplication ‘*’ and division ‘/’ are the only valid operators appearing in the test data.

Output sample:

Print to stdout the output of the prefix expression, one per line.

For example:

20

Constraints:

The evaluation result will always be an integer ≥ 0.

The number of the test cases is ≤ 40.

Number Pairs

Challenge Description:

You are given a sorted array of positive integers and a number 'X'.
Print out all pairs of numbers whose sum is equal to X.
Print out only unique pairs and the pairs should be in ascending order

Input sample:

Your program should accept as its first argument a filename.
This file will contain a comma separated list of sorted numbers and then the sum 'X',
separated by semicolon. Ignore all empty lines. If no pair exists, print the string NULL e.g.

1,2,3,4,6;5
2,4,5,6,9,11,15;20
1,2,3,4;50

Output sample:

Print out the pairs of numbers that equal to the sum X.
The pairs should themselves be printed in sorted order i.e the first
number of each pair should be in ascending order. E.g.

1,4;2,3
5,15;9,11
NULL

Array Absurdity

Challenge Description:

Imagine we have an immutable array of size N which we know to be filled with integers ranging from 0 to N-2,
inclusive. Suppose we know that the array contains exactly one duplicated entry and that duplicate appears
exactly twice. Find the duplicated entry. (For bonus points, ensure your solution has constant space and
time proportional to N)

Input sample:

Your program should accept as its first argument a path to a filename. Each line in this file is one test case.
Ignore all empty lines. Each line begins with a positive integer(N) i.e. the size of the array, then a semicolon
followed by a comma separated list of positive numbers ranging from 0 to N-2, inclusive. i.e eg.

Print out the duplicated entry, each one on a new line eg

0
4

Sum of integers

Challenge Description:

Write a program to determine the largest sum of contiguous integers in a list.

Input sample:

The first argument is a path to a filename containing a comma-separated list of integers, one per line.

For example:

-10,2,3,-2,0,5,-15
2,3,-2,-1,10

Output sample:

Print to stdout the largest sum. In other words, of all the possible contiguous subarrays for a given array,
find the one with the largest sum, and print that sum.

For example:

8
12

Remove Characters

Challenge Description:

Write a program which removes specific characters from a string.

Input sample:

The first argument is a path to a file. The file contains the source strings and the characters that need to be
scrubbed. Each source string and characters you need to scrub are delimited by comma.

For example:

how are you, abc
hello world, def

Output sample:

Print to stdout the scrubbed strings, one per line. Ensure that there are no trailing empty spaces on each line
you print.

For example:

how re you
hllo worl

First Non-Repeated Character

Challenge Description:

Write a program which finds the first non-repeated character in a string.

Input sample:

The first argument is a path to a file. The file contains strings.

For example:

yellow
tooth

Output sample:

Print to stdout the first non-repeated character, one per line.

For example:

y
h

Pangrams

Challenge Description:

The sentence 'A quick brown fox jumps over the lazy dog' contains every single letter in the alphabet.
Such sentences are called pangrams. You are to write a program, which takes a sentence, and returns all the
letters it is missing (which prevent it from being a pangram). You should ignore the case of the letters in
sentence, and your return should be all lower case letters, in alphabetical order. You should also ignore all
non US-ASCII characters.In case the input sentence is already a pangram, print out the string NULL

Input sample:

Your program should accept as its first argument a path to a filename. This file will contain several text strings,
one per line. E.g.

A quick brown fox jumps over the lazy dog
A slow yellow fox crawls under the proactive dog

Output sample:

Print out all the letters each string is missing in lowercase, alphabetical order . E.g.

NULL
bjkmqz

Detecting Cycles

Challenge Description:

Given a sequence, write a program to detect cycles within it.

Input sample:

Your program should accept as its first argument a path to a filename
containing a sequence of numbers (space delimited). The file can have multiple such lines. E.g

Print to stdout the first cycle you find in each sequence. Ensure that there are no trailing empty
spaces on each line you print. E.g.

6 3 1
49
1 2 3

The cycle detection problem is explained more widely on wiki
Constrains:
The elements of the sequence are integers in range [0, 99]
The length of the sequence is in range [0, 50]

Bit Positions

Challenge Description:

Given a number n and two integers p1,p2 determine if the bits in
position p1 and p2 are the same or not. Positions p1 and p2 are 1 based.

Input sample:

The first argument will be a path to a filename containing a comma separated list
of 3 integers, one list per line. E.g.

86,2,3
125,1,2

Output sample:

Print to stdout, 'true'(lowercase) if the bits are the same,
else 'false'(lowercase). E.g.

true
false

Self Describing Numbers

Challenge Description:

A number is a self-describing number when (assuming digit positions
are labeled 0 to N-1), the digit in each position is equal to the
number of times that that digit appears in the number.

Input sample:

The first argument is the pathname to a file which contains test data,
one test case per line. Each line contains a positive integer.
E.g.

2020
22
1210

Output sample:

If the number is a self-describing number, print out 1. If not, print
out 0. E.g.

1
0
1

For the curious, here's how 2020 is a self-describing number:
Position '0' has value 2 and there is two 0 in the number.
Position '1' has value 0 because there are not 1's in the number.
Position '2' has value 2 and there is two 2.
And the position '3' has value 0 and there are zero 3's.

Happy Numbers

Challenge Description:

A happy number is defined by the following process. Starting with any
positive integer, replace the number by the sum of the squares of its
digits, and repeat the process until the number equals 1 (where it
will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy numbers, while
those that do not end in 1 are unhappy numbers.

Input sample:

The first argument is the pathname to a file which contains test data,
one test case per line. Each line contains a positive integer. E.g.

1
7
22

Output sample:

If the number is a happy number, print out 1. If not, print out 0. E.g

1
1
0

For the curious, here's why 7 is a happy number: 7->49->97->130->10->1.
Here's why 22 is NOT a happy number:
22->8->64->52->29->85->89->145->42->20->4->16->37->58->89 ...

Multiples of a Number

Challenge Description:

Given numbers x and n, where n is a power of 2, print out the smallest
multiple of n which is greater than or equal to x.
Do not use division or modulo operator.

Input sample:

The first argument will be a path to a filename containing a comma separated list
of two integers, one list per line. E.g.

13,8
17,16

Output sample:

Print to stdout, the smallest multiple of n which is greater than
or equal to x, one per line. E.g.

16
32

Decimal To Binary

Challenge Description:

You are given a decimal (base 10) number, print its binary representation.

Input sample:

Your program should accept as its first argument a path to a filename containing decimal numbers greater or equal to 0, one per line.

Ignore all empty lines.

For example:

2
10
67

Output sample:

Print the binary representation, one per line.

For example:

10
1010
1000011

Endianness

Challenge Description:

Write a program which prints the endianness of the system.

Input sample:

There is no input for this program.

Output sample:

Print to stdout the endianness, wheather it is LittleEndian or BigEndian.

For example:

BigEndian

Reverse and Add

Challenge Description:

Credits: Programming Challenges by Steven S. Skiena and
Miguel A. Revilla

The problem is as follows: choose a number, reverse its digits and
add it to the original. If the sum is not a palindrome (which means,
it is not the same number from left to right and right to left), repeat
this procedure.

In this particular case the palindrome 9339 appeared after the
4th addition. This method leads to palindromes in a few step for
almost all of the integers. But there are interesting exceptions.
196 is the first number for which no palindrome has been found.
It is not proven though, that there is no such a palindrome.

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file is one test case. Each test case will contain
an integer n < 10,000. Assume each test case will always have an answer
and that it is computable with less than 100 iterations (additions).

Output sample:

For each line of input, generate a line of output which is the number
of iterations (additions) to compute the palindrome and the
resulting palindrome. (they should be on one line and separated
by a single space character).

For example:

4 9339

Mth to last element

Challenge Description:

Write a program which determines the M^{th} to the last element in a list.

Input sample:

The first argument is a path to a file. The file contains the series of space delimited characters followed by
an integer. The integer represents an index in the list (1-based), one per line.

For example:

a b c d 4
e f g h 2

Output sample:

Print to stdout the M^{th} element from the end of the list, one per line. If the index is larger than
the number of elements in the list, ignore that input.

For example:

a
g

Multiplication Tables

Challenge Description:

Print out the grade school multiplication table upto 12*12.

Input sample:

There is no input for this program.

Output sample:

Print out the table in a matrix like fashion, each number formatted
to a width of 4 (The numbers are right-aligned and strip out
leading/trailing spaces on each line). The first 3 line will look like:

You are given several strings that may/may not be valid emails.
You should write a regular expression that determines if the email
id is a valid email id or not. You may assume all characters are
from the english language.

Input sample:

Your program should accept as its first argument a filename.
This file will contain several text strings, one per line.
Ignore all empty lines. E.g.

foo@bar.com
this is not an email id
admin#codeeval.com
good123@bad.com

Output sample:

Print out 'true' (all lowercase) if the string is a valid email.
Else print out 'false' (all lowercase). E.g.

true
false
false
true

Prime Numbers

Challenge Description:

Print out the prime numbers less than a given number N.
For bonus points your solution should run in N*(log(N)) time or better.
You may assume that N is always a positive integer.

Input sample:

Your program should accept as its first argument a path to a filename.
Each line in this file is one test case.
Each test case will contain an integer n < 4,294,967,295. E.g.

10
20
100

Output sample:

For each line of input, print out the prime numbers less than N,
in ascending order, comma delimited.
(There should not be any spaces between the comma and numbers) E.g.

Given a positive integer, find the sum of its constituent digits.

Input sample:

The first argument will be a path to a filename containing positive integers,
one per line. E.g.

23
496

Output sample:

Print to stdout, the sum of the numbers that make up the integer,
one per line. E.g.

5
19

Odd Numbers

Challenge Description:

Print the odd numbers from 1 to 99.

Input sample:

There is no input for this program.

Output sample:

Print the odd numbers from 1 to 99, one number per line.

Fibonacci Series

Challenge Description:

The Fibonacci series is defined as: F(0) = 0; F(1) = 1;
F(n) = F(n–1) + F(n–2) when n>1. Given an integer n≥0,
print out the F(n).

Input sample:

The first argument will be a path to a filename containing integer numbers,
one per line. E.g.

5
12

Output sample:

Print to stdout, the fibonacci number, F(n). E.g.

5
144

Unique Elements

Challenge Description:

You are given a sorted list of numbers with duplicates.
Print out the sorted list with duplicates removed.

Input sample:

File containing a list of sorted integers, comma delimited, one per line.
E.g.

1,1,1,2,2,3,3,4,4
2,3,4,5,5

Output sample:

Print out the sorted list with duplicates removed, one per line.
E.g.

1,2,3,4
2,3,4,5

Rightmost Char

Challenge Description:

You are given a string 'S' and a character 't'. Print out the position of
the rightmost occurrence of 't' (case matters) in 'S' or -1 if there is
none. The position to be printed out is zero based.

Input sample:

The first argument will ba a path to a filename, containing a string and a character, comma
delimited, one per line. Ignore all empty lines in the input file. E.g.

Hello World,r
Hello CodeEval,E

Output sample:

Print out the zero based position of the character 't' in string 'S',
one per line. Do NOT print out empty lines between your output.
E.g.

8
10

Sum of Integers from File

Challenge Description:

Print out the sum of integers read from a file.

Input sample:

The first argument to the program will be a path to a filename containing
a positive integer, one per line. E.g.

5
12

Output sample:

Print out the sum of all the integers read from the file. E.g.

17

File Size

Challenge Description:

Print the size of a file in bytes.

Input:

The first argument to your program has the path to the file you need to check the size of.

Output sample:

Print the size of the file in bytes.
E.g.

55

Longest Lines

Challenge Description:

Write a program which reads a file and prints to stdout the specified number of the longest lines that are sorted
based on their length in descending order.

Input sample:

Your program should accept a path to a file as its first argument. The file contains multiple lines. The first line
indicates the number of lines you should output, the other lines are of different length and are presented randomly.
You may assume that the input file is formatted correctly and the number in the first line is a valid positive
integer.

For example:

2
Hello World
CodeEval
Quick Fox
A
San Francisco

Output sample:

Print out the longest lines limited by specified number and sorted by their length in descending order.

For example:

San Francisco
Hello World

Lowercase

Challenge Description:

Given a string write a program to convert it into lowercase.

Input sample:

The first argument will be a path to a filename containing sentences, one per line.
You can assume all characters are from the english language. E.g.

HELLO CODEEVAL
This is some text

Output sample:

Print to stdout, the lowercase version of the sentence,
each on a new line. E.g.

hello codeeval
this is some text

Reverse words

Challenge Description:

Write a program which reverses the words in an input sentence.

Input sample:

The first argument is a file that contains multiple sentences, one per line. Empty lines are also possible.

For example:

Hello World
Hello CodeEval

Output sample:

Print to stdout each sentence with the reversed words in it, one per line. Empty lines in the input should
be ignored. Ensure that there are no trailing empty spaces in each line you print.

For example:

World Hello
CodeEval Hello

Sum of Primes

Challenge Description:

Write a program which determines the sum of the first 1000 prime numbers.

Input sample:

There is no input for this program.

Output sample:

Print to stdout the sum of the first 1000 prime numbers.

3682913

Prime Palindrome

Challenge Description:

Write a program which determines the largest prime palindrome less than 1000.

Input sample:

There is no input for this program.

Output sample:

Print to stdout the largest prime palindrome less than 1000.

929

Fizz Buzz

Challenge Description:

Players generally sit in a circle. The first player says the number “1”, and each player says next number in turn.
However, any number divisible by X (for example, three) is replaced by the word fizz, and any divisible
by Y (for example, five) by the word buzz. Numbers divisible by both become fizz buzz. A player
who hesitates, or makes a mistake is eliminated from the game.

Write a program that prints out the final series of numbers where those divisible by X, Y and both are replaced
by “F” for fizz, “B” for buzz and “FB” for fizz buzz.

Input sample:

Your program should accept a file as its first argument. The file contains multiple separated lines; each line
contains 3 numbers that are space delimited. The first number is the first divider (X), the second number is
the second divider (Y), and the third number is how far you should count (N). You may assume that the input file
is formatted correctly and the numbers are valid positive integers.

For example:

3 5 10
2 7 15

Output sample:

Print out the series 1 through N replacing numbers divisible by X with “F”, numbers divisible by Y with “B”
and numbers divisible by both with “FB”. Since the input file contains multiple sets of values, your output
should print out one line per set. Ensure that there are no trailing empty spaces in each line you print.

1 2 F 4 B F 7 8 F B
1 F 3 F 5 F B F 9 F 11 F 13 FB 15

Constraints:

The number of test cases ≤ 20

"X" is in range [1, 20]

"Y" is in range [1, 20]

"N" is in range [21, 100]

import sys
def det_age(age):
if 66 <= age <= 100:
return 'The Golden Years'
elif 23 <= age:
return 'Working for the man'
elif 19 <= age:
return 'College'
elif 15 <= age:
return 'High school'
elif 12 <= age:
return 'Middle school'
elif 5 <= age:
return 'Elementary school'
elif 3 <= age:
return 'Preschool Maniac'
elif 0 <= age:
return "Still in Mama's arms"
else:
return "This program is for humans"
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
print(det_age(int(test)))

import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
print(test.split()[-2])

import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
print(int(int(test.strip()) % 2 == 0))

import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
(hexs, bins) = test.rstrip().split(' | ')
hex_sum = 0
for h in hexs.split():
hex_sum += int(h, 16)
bin_sum = 0
for b in bins.split():
bin_sum += int(b, 2)
print(hex_sum <= bin_sum)

import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
for char in test:
if char.isupper():
char = char.lower()
else:
char = char.upper()
sys.stdout.write(char)

def simple_sorting(nums):
length = len(nums)
for i in xrange(length-1):
for j in xrange(i+1,length):
if nums[i] > nums[j]:
temp = nums[j]
nums[j] = nums[i]
nums[i] = temp
return nums
if __name__ == '__main__':
import sys
with open(sys.argv[1], "r") as inputfile:
for line in [line.strip() for line in inputfile]:
nums = simple_sorting([float(i) for i in line.split(' ')])
for num in nums:
print num,
print

import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
nums = [n for n in test.strip().split()]
print(' '.join(sorted(nums, key=float)))

import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
sys.stdout.write(' '.join(map(lambda x: x.capitalize(), test.rstrip().split())) + '\n')

import sys
CONV_MAP = {'one': '1', 'two':'2', 'three':'3', 'four': '4', 'five': '5',
'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', 'zero': '0' }
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
for word in test.rstrip().split(';'):
sys.stdout.write(CONV_MAP[word])
sys.stdout.write('\n')

# -*- coding: utf-8 -*-
MONEY = {
'PENNY': 0.01,
'NICKEL': 0.05,
'DIME': 0.10,
'QUARTER': 0.25,
'HALF DOLLAR': 0.50,
'ONE': 1.00,
'TWO': 2.00,
'FIVE': 5.00,
'TEN': 10.00,
'TWENTY': 20.00,
'FIFTY': 50.00,
'ONE HUNDRED': 100.00
}
MONEY = sorted(MONEY.items(), key=lambda x:x[1], reverse=True)
def get_change(prise, cash):
change = cash - prise
if change == 0:
return 'ZERO'
elif change < 0:
return 'ERROR'
result = []
for currency, value in MONEY:
while value <= change:
change -= value
result.append(currency)
if change == 0:
break
return ','.join(sorted(set(result)))
if __name__ == '__main__':
import sys
with open(sys.argv[1], "r") as inputfile:
for line in [line.strip() for line in inputfile]:
PP,CH = line.split(';')
print get_change(float(PP), float(CH))

# -*- coding: utf-8 -*-
def is_armstrong(num):
length = len(num)
total = 0
for i in num:
total += int(i)**length
return True if total == int(num) else False
if __name__ == '__main__':
import sys
with open(sys.argv[1], "r") as inputfile:
for line in [line.strip() for line in inputfile]:
print is_armstrong(line)

# -*- coding: utf-8 -*-
HEX_MAP = {'a':10,'b':11,'c':12,'d':13,'e':14,'f':15}
def hex2decimal(num):
result = 0
length = len(num)
for i in xrange(length-1, -1, -1):
n = HEX_MAP[num[i]] if num[i].isalpha() else int(num[i])
coefficient = 16 ** (length - (i+1))
coefficient = 1 if coefficient == 0 else coefficient
result += n * coefficient
return result
if __name__ == '__main__':
import sys
with open(sys.argv[1], "r") as inputfile:
for line in [line.strip() for line in inputfile]:
print hex2decimal(line)

# -*- coding: utf-8 -*-
def mod(n,m):
for i in xrange(1,n):
if (m * i) > n:
break
return n - m * (i - 1)
if __name__ == '__main__':
import sys
with open(sys.argv[1], "r") as inputfile:
for line in [line.strip() for line in inputfile]:
n,m = line.split(',')
print mod(int(n),int(m))

# -*- coding: utf-8 -*-
BOARD = []
SIZE = 256
for i in xrange(SIZE):
BOARD.append(list())
for j in xrange(SIZE):
BOARD[-1].append(0)
def operate_board(operator):
global BOARD
if len(operator) == 2:
operand,value = operator
value = int(value)
if operand == 'QueryRow':
print sum(BOARD[value])
return
if operand == 'QueryCol':
print sum([row[value] for row in BOARD])
return
else:
if operator[0] == 'SetRow':
operand,i,x = operator
i,x = int(i),int(x)
for n in xrange(len(BOARD[i])):
BOARD[i][n] = x
return
if operator[0] == 'SetCol':
operand,j,x = operator
j,x = int(j),int(x)
for n in xrange(len(BOARD)):
BOARD[n][j] = x
return
if __name__ == '__main__':
import sys
if len(sys.argv) <= 1:
sys.exit(__doc__)
with open(sys.argv[1], "r") as inputfile:
for line in [line.strip() for line in inputfile]:
if len(line) <= 0:
continue
operate_board(line.split(' '))

# -*- coding: utf-8 -*-
import re
re_not_char = re.compile('[^\w]')
def calc_beauty(string):
string = string.lower()
string = re_not_char.sub('',string)
char_count = {}
for char in string:
char_count[char] = char_count.get(char,0) + 1
value = 26
result = 0
for count in sorted(char_count.values(), reverse=True):
result += value * count
value -= 1
return result
if __name__ == '__main__':
import sys
if len(sys.argv) <= 1:
sys.exit(__doc__)
with open(sys.argv[1], "r") as inputfile:
for line in [line.strip() for line in inputfile]:
if len(line) <= 0:
continue
print calc_beauty(line)

# -*- coding: utf-8 -*-
def count_decodable(nums, history=[]):
global cache
if len(nums) <= 1:
if len(nums) == 1:
history.append(nums[0])
if all(is_decodable(int(i)) for i in history) and not ','.join(history) in cache:
cache.append(','.join(history))
return
for i in xrange(1,3):
history.append(''.join(nums[0:0+i]))
count_decodable(nums[0+i:],history)
for j in xrange(3, i if len(history) >= 2 else 2, -1):
history.pop(-1)
def is_decodable(num):
if num > 0 and num < 27:
return True
return False
if __name__ == '__main__':
import sys
if len(sys.argv) <= 1:
sys.exit(__doc__)
with open(sys.argv[1], "r") as inputfile:
for line in [line.strip() for line in inputfile]:
cache = []
if len(line) <= 0:
continue
count_decodable(line,[])
print len(cache)

# -*- coding: utf-8 -*-
cache = {}
max_prime = 2
def count_primes(nums):
start,end = nums
result = 0
for i in xrange(start,end+1):
if is_prime(i):
result += 1
return result
def is_prime(num):
global max_prime, cache
if num in cache:
return True
if max_prime > num:
return False
for i in sorted(cache.keys()):
if num % i == 0:
if num == i:
return True
return False
i = max_prime
while i < num:
if num % i == 0:
return False
if is_prime(i):
cache[i] = 1
i += 1
max_prime = num
cache[num] = 1
return True
if __name__ == '__main__':
import sys
if len(sys.argv) <= 1:
sys.exit(__doc__)
with open(sys.argv[1], "r") as inputfile:
for line in [line.strip() for line in inputfile]:
if len(line) <= 0:
continue
print count_primes([int(i) for i in line.split(',')])

# -*- coding: utf-8 -*-
cache = {}
def count_sum_to_zero(nums, history=[]):
global result, cache
if len(history) == 4 and sum(history) == 0:
total = ','.join([str(i) for i in sorted(history)])
if not total in cache:
cache[total] = 1
result += 1
return
for i in xrange(len(nums)):
other_nums = nums[:i]+nums[i+1:]
history.append(nums[i])
count_sum_to_zero(other_nums, history)
history.pop(-1)
if __name__ == '__main__':
import sys
if len(sys.argv) <= 1:
sys.exit(__doc__)
with open(sys.argv[1], "r") as inputfile:
for line in [line.strip() for line in inputfile]:
result = 0
if len(line) <= 0:
continue
count_sum_to_zero([int(i) for i in line.split(',')])
print result

# -*- coding: utf-8 -*-
def spiral_printing(column, row, nums):
lists = []
result = []
cnt = 0
for i in xrange(row):
lists.append(list())
for j in xrange(column):
lists[i].append(nums[cnt])
cnt += 1
for i in xrange(len(nums)):
for j in xrange(column):
try:
result.append(lists[0].pop(0))
except:
break
try:
lists.pop(0)
except:
continue
row -= 1
lists = transpose(lists, row, column)
row, column = swap(row, column)
print ' '.join(result)
def transpose(lists, column, row):
result = []
for i in xrange(row-1,-1,-1):
result.append(list())
for j in xrange(column):
result[-1].append(lists[j][i])
return result
def swap(a, b):
temp = a
a = b
b = temp
return a, b
if __name__ == '__main__':
import sys
if len(sys.argv) <= 1:
sys.exit(__doc__)
input = open(sys.argv[1], "r")
for line in input:
line = line.strip()
if len(line) <= 0:
continue
row,column,nums = line.split(';')
spiral_printing(int(column), int(row), nums.split(' '))

# -*- coding: utf-8 -*-
import re
re_scheme = re.compile('^([\w])+://')
re_host = re.compile('://([^/]+)')
re_hex = re.compile('%([\w\d]{2})')
def is_match_uri(uri_pair):
if len(uri_pair) != 2:
return False
for i in xrange(len(uri_pair)):
for substr in re_host.findall(uri_pair[i]):
scheme = re_scheme.search(uri_pair[i]).group(0)
uri_pair[i] = uri_pair[i].replace(scheme, scheme.lower())
if not ':' in substr or not ':80' in uri_pair[i]:
uri_pair[i] = re_host.sub('://'+substr.lower().replace(':','')+':80',uri_pair[i])
else:
uri_pair[i] = uri_pair[i].replace(substr, substr.lower())
for substr in set(re_hex.findall(uri_pair[i])):
uri_pair[i] = re_hex.sub(substr.decode('hex'),uri_pair[i])
if uri_pair[0] == uri_pair[1]:
return True
return False
if __name__ == '__main__':
import sys, codecs
if len(sys.argv) <= 1:
sys.exit(__doc__)
input = open(sys.argv[1], "r")
for line in input:
line = line.strip()
if len(line) <= 0:
continue
print is_match_uri(line.split(';'))

# -*- coding: utf-8 -*-
def is_rotate(string_pair):
if len(string_pair) != 2:
return False
for i in xrange(len(string_pair[1])):
if (string_pair[1][i:] + string_pair[1][:i]) == string_pair[0]:
return True
return False
if __name__ == '__main__':
import sys
if len(sys.argv) <= 1:
sys.exit(__doc__)
with open(sys.argv[1], "r") as inputfile:
for line in inputfile:
line = line.strip()
if len(line) <= 0:
continue
print is_rotate(line.split(','))

# -*- coding: utf-8 -*-
def sub_string(string, subs):
if string == "":
return ""
for j in xrange(0, len(subs), 2):
i = string.find(subs[j])
if i != -1:
return sub_string(string[:i], subs) + subs[j+1] + sub_string(string[i+len(subs[j]):], subs)
return string
if __name__ == '__main__':
import sys, codecs
if len(sys.argv) <= 1:
sys.exit(__doc__)
input = open(sys.argv[1], "r")
for line in input:
line = line.strip()
if len(line) <= 0:
continue
string, sub = line.split(';')
print sub_string(string, sub.split(','))

# -*- coding: utf-8 -*-
LETTERS = {
'0':['0'],
'1':['1'],
'2':['a','b','c'],
'3':['d','e','f'],
'4':['g','h','i'],
'5':['j','k','l'],
'6':['m','n','o'],
'7':['p','q','r','s'],
'8':['t','u','v'],
'9':['w','x','y','z'],
}
def addCombi(sequence, prefix=''):
global result
if len(sequence) > 1:
for character in LETTERS[sequence[0]]:
addCombi(sequence[1:], prefix + character)
else:
for character in LETTERS[sequence]:
result.append(prefix + character)
if __name__ == '__main__':
import sys
try:
input_file = open(sys.argv[1])
for line in [l.strip() for l in input_file]:
if len(line) > 7 or len(line) < 1:
continue
result = []
addCombi(line)
print ','.join(result)
except Exception, e:
sys.exit(e)
finally:
if input_file:
input_file.close()
sys.exit(0)

# -*- coding: utf-8 -*-
def isJolly(sequence):
n = sequence[0]
integers = [abs(sequence[i] - sequence[i+1]) for i in xrange(1,len(sequence[1:]))]
for integer in integers:
n -= 1
if integer != n:
return False
return True
if __name__ == '__main__':
import sys
try:
input_file = open(sys.argv[1])
for line in input_file:
sequence = [int(i) for i in line.split(" ")]
if isJolly(sequence):
print "Jolly"
else:
print "Not jolly"
except Exception, e:
sys.exit(e)
finally:
if input_file:
input_file.close()

def determinNextNumber(integers ,n):
integers = list(set(integers))
integers.sort()
nearest_num = 1000000
for i in integers:
if i <= n:
continue
else:
return i
def generateNumberList(integers):
global result
for base in integers:
i = 0
while i+1 <= len(integers):
integers[-i], integers[-(i+1)] = integers[-(i+1)], integers[-i]
temp = ""
for integer in integers:
temp += integer
result.append(int(temp))
i += 1
if __name__ == '__main__':
import sys, codecs, random
if len(sys.argv) <= 1:
sys.exit(__doc__)
f = lambda n: n and n * f(n - 1) or 1
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
if len(line) <= 0:
continue
digits,result = [],[]
out = ""
if line is "":
continue
for char in line:
digits.append(char)
generateNumberList(digits)
while len(result) < f(len(line)):
digits.sort()
generateNumberList(digits)
digits.reverse()
generateNumberList(digits)
random.shuffle(digits)
generateNumberList(digits)
digits.append("0")
while len(result) < f(len(line)+1):
digits.sort()
generateNumberList(digits)
digits.reverse()
generateNumberList(digits)
random.shuffle(digits)
generateNumberList(digits)
print determinNextNumber(result,int(line))

def Cluster():
global user_list,clusters
for user_x in user_list:
subcluster = [user_x]
if not user_list[user_x].get('perform') or not user_list[user_x].get('receive'):
continue
for receiver in user_list[user_x]['perform'].split(';'):
if receiver is "":
continue
if user_list[user_x]['receive'].count(receiver+';') > 0:
subcluster.append(receiver)
subcluster = list(set(subcluster))
subcluster.sort()
out = ""
for user in subcluster:
out += user+", "
clusters.append(out[:-2])
clusters = list(set(clusters))
clusters.sort(cmplen)
print clusters[-1]
def cmplen(x, y):
a, b = len(x), len(y)
if a == b:
return 0
elif a < b:
return -1
else:
return 1
if __name__ == '__main__':
import sys, codecs, re
if len(sys.argv) <= 1:
sys.exit(__doc__)
user_list = {}
clusters = []
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
if len(line) <= 0:
continue
users = line.split('\t')
if user_list.get(users[1]):
if user_list[users[1]].get('perform'):
user_list[users[1]]['perform'] += users[2]+";"
else:
user_list[users[1]]['perform'] = users[2]+";"
else:
user_list[users[1]] = {'perform' : users[2]+";"}
if user_list.get(users[2]):
if user_list[users[2]].get('receive'):
user_list[users[2]]['receive'] += users[1]+";"
else:
user_list[users[2]]['receive'] = users[1]+";"
else:
user_list[users[2]] = {'receive' : users[1]+";"}
Cluster()

def iterateString(string, temp, loop):
global prefix, result
loop -= 1
for char in string:
temp2 = temp + char
if loop > 0:
iterateString(string, temp2, loop)
else:
prefix = temp
if not one_only.search(prefix+char):
result.append(prefix+char)
if loop == 0:
prefix = ""
def cmplen(x, y):
a, b = len(x), len(y)
if a == b:
return 0
elif a < b:
return -1
else:
return 1
def char_map(string):
global char_list
for i in range(len(string)):
char_list[result[i]] = string[i]
if __name__ == '__main__':
import sys, codecs, re
if len(sys.argv) <= 1:
sys.exit(__doc__)
not_digit = re.compile('[^0-1]')
zero_one = re.compile('[0-1]')
one_only = re.compile('^1+$')
zero_only = re.compile('^0+$')
result = []
for i in range(1,7+1):
iterateString("01", "", i)
result = list(set(result))
result.sort()
result.sort(cmplen)
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
if len(line) <= 0:
continue
code, string = not_digit.sub("", line), zero_one.sub("", line)
char_list = {}
char_map(string)
out,key_bin,encoded_char,key_length = "","","",0
for digit in code:
if len(key_bin) < 3:
key_bin += digit
continue
elif key_length == 0:
key_length = int(key_bin,2)
if len(encoded_char) == key_length and key_length > 0:
if one_only.search(encoded_char):
key_bin,key_length,encoded_char = digit,0,""
else:
out += char_list[encoded_char]
encoded_char = digit
else:
encoded_char += digit
print out

import sys, codecs, re
def longestCommonSequence(s1, s2):
global words
s1,s2 = deleteAloneChar(s1, s2), deleteAloneChar(s2, s1)
if len(s1) < len(s2):
string1,string2 = s1,s2
else:
string1,string2 = s2,s1
for base in range(len(string1)):
for i in range(len(string1[base:])):
i += 1
word, j = "", 0
if base+i >= len(string1):
break
start = string2.index(string1[base])
for char in string1[base:base+i+1]:
k = 0
while start+j+k < len(string2):
if string2[start+j+k] is char:
word += char
j += k + 1
break
k += 1
words.append(word)
def deleteAloneChar(s1, s2):
out = ""
for char in s1:
if s2.count(char) > 0:
out += char
return out
def cmplen(x, y):
a, b = len(x), len(y)
if a == b:
return 0
elif a < b:
return -1
else:
return 1
space = re.compile(' ')
input = codecs.open(sys.argv[1], "r")
for line in input:
words = []
line = line.strip()
if len(line) > 0:
section = line.split(";")
longestCommonSequence(section[0], section[1])
words.sort(cmplen)
print words[-1]

class stack(object):
def __init__(self):
self.__stack = []
def push(self, value):
self.__stack.append(int(value))
def pop(self):
if len(self.__stack) == 0:
return None
return self.__stack.pop()
if __name__ == '__main__':
import sys
if len(sys.argv) <= 1:
sys.exit(__doc__)
dat = None
try:
dat = open(sys.argv[1])
for l in [l.strip() for l in dat.readlines() if l.strip()]:
integers = [int(i.strip()) for i in l.split(' ') if i.strip()]
res = []
s = stack()
for i in integers:
s.push(i)
v = s.pop()
while v is not None:
res.append(v)
v = s.pop()
v = s.pop()
if len(res) > 0:
print ' '.join(['%d' % i for i in res])
except Exception, e:
sys.exit(e)
finally:
if dat:
dat.close()

import sys, codecs
def count1bits(n):
binary = str(format(n,'b'))
return binary.count('1')
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
if line is '':
continue
print count1bits(int(line))

import sys, codecs, math, time
def isDoubleSquare(n):
global cnt
count = 0
bias = 0
sqr = math.sqrt(n)
end = int(math.ceil(sqr))
start = int(math.floor(math.sqrt(sqr)))*2
for i in range(start-1,end+1):
bias = 0
for j in range(start):
j += bias
if i < j:
break
result = i**2 + j**2
abso = (result - n) * -1
if abso < 0:
break
if result == n:
count += 1
break
if bias > 0:
continue
else:
bias = math.floor(math.sqrt(abso)) - 1
return count
input = codecs.open(sys.argv[1], "r")
n = 0
for line in input:
start = time.time()
line = line.strip()
if n == 0:
n = int(line)
continue
print isDoubleSquare(int(line))
n -= 1

import sys, codecs
def chkDepth(n):
if n == 8 or n == 52:
return 1
elif n == 3 or n == 20:
return 2
elif n == 10 or n == 29:
return 3
def lowestCommonAncestor(n1, n2):
depth = min(n1, n2) - 1
if depth == 0:
return 30
elif depth == 1:
return 8
elif depth == 2:
return 20
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
items = line.split(" ")
print lowestCommonAncestor(chkDepth(int(items[0])), chkDepth(int(items[1])))

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
output = ""
line = line.strip()
section = line.split(";")
items1 = section[0].split(",")
items2 = section[1].split(",")
for item in items1:
if items2.count(item):
output += item+','
if len(output) > 1:
print output[:-1]
else:
print "%d,%d" % (min(int(items1[-1]), int(items2[0])), max(int(items1[-1]), int(items2[0])))

import sys, codecs
def isSameEnd(section1, section2):
for n in range(len(section2)):
n = (n * -1) - 1
if not section1[n] is section2[n]:
return 0
return 1
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
if line is "":
continue
section = line.split(",")
if len(section[0]) < len(section[1]):
print 0
continue
print isSameEnd(section[0],section[1])

import sys, codecs
def iterateString(string, temp, loop):
global prefix, result
loop -= 1
for char in string:
temp2 = temp + char
if loop > 0:
iterateString(string, temp2, loop)
else:
prefix = temp
result.append(prefix+char)
if loop == 0:
prefix = ""
prefix = ""
input = codecs.open(sys.argv[1], "r")
for line in input:
result = []
output = ""
line = line.strip()
section = line.split(',')
n = int(section[0])
iterateString(section[1], "", n)
result = list(set(result))
result.sort()
for item in result:
output += item+','
print output[:-1]

import sys, codecs, re
asterisk = re.compile('\*')
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
section = line.split(',')
section[1] = asterisk.sub('.*', section[1])
if re.search(section[1], section[0]):
print "true"
else:
print "false"

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
items = []
result = []
out = ""
if line is "":
continue
for char in line:
items.append(char)
for base in items:
i = 0
while i+1 < len(items):
items[-i], items[-(i+1)] = items[-(i+1)], items[-i]
temp = ""
for item in items:
temp += item
result.append(temp)
i += 1
result.sort()
for item in result:
out += item+','
print out[:-1]

import sys, codecs, re
digit = re.compile("[0-9]")
input = codecs.open(sys.argv[1], "r")
for line in input:
num = []
operator = []
line = line.strip()
if line is "":
continue
items = line.split(' ')
for i in range(len(items)):
if digit.match(items[i]):
items[i] = int(items[i])
for item in items:
if isinstance(item, int):
num.append(item)
if len(num) > 1:
if operator[-1] is "+":
num.append(num.pop() + num.pop())
if operator[-1] is "*":
num.append(num.pop() * num.pop())
if operator[-1] is "/":
num.append(num.pop() / num.pop())
del operator[-1]
else:
operator.append(item)
print num[-1]

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
out = ""
line = line.strip()
if line is "":
continue
section = line.split(';')
items = section[0].split(',')
for i in range(len(items)):
items[i] = int(items[i])
x = int(section[1])
for base in range(len(items)):
if items[base] > x:
break
for p in range(len(items[base:])):
p += 1
if base+p == len(items):
break
if items[base] + items[base+p] == x:
out += str(items[base])+','+str(items[base+p])+';'
if len(out) > 1:
print out[:-1]
else:
print "NULL"

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
if line is "":
continue
section = line.split(';')
items = section[1].split(',')
for i in range(len(items)):
items[i] = int(items[i])
for item in items:
if items.count(item) > 1:
print item
break

import sys, codecs, re
space = re.compile(" ")
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
line = space.sub("", line)
items = line.split(",")
result = []
for i in range(len(items)):
items[i] = int(items[i])
for base in range(len(items)):
sum = items[base]
for n in range(len(items[base:])):
n += 1
if base+n < len(items):
sum += items[base+n]
result.append(sum)
print max(result)

import sys, codecs, re
space = re.compile(" ")
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
section = line.split(",")
search_word = space.sub("", section[1])
print re.sub("["+search_word+"]", "", section[0])

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
for char in line:
if line.count(char) == 1:
print char
break

import sys, codecs, re
valid_line = re.compile("^[0-z !\"#$%&'()*+,\-./:;<=>?@[\\]^_`{|}~]+$")
alphabet = "abcdefghijklmnopqrstuvwxyz"
input = codecs.open(sys.argv[1], "r")
for line in input:
out = ""
line = line.strip()
if not valid_line.search(line):
continue
for char in alphabet:
if not char in line:
out += char
if len(out) == 0:
print "NULL"
else:
print out

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
if line is "":
continue
items = line.split(' ')
for i in range(len(items)):
items[i] = int(items[i])
for base in range(len(items)):
if items.count(items[base]) < 2:
continue
for p in range(len(items[base:])):
result = []
p += 1
start = base+p
shift = 0
if start >= len(items):
break
while (start+shift) < len(items):
if (base+shift) == start:
break
if items[base+shift] == items[start+shift]:
result.append(items[base+shift])
shift += 1
else:
break
if len(result) > 1:
break
if len(result) > 1:
for num in result:
print num,
print ""
break

import sys, codecs
def isSamePosition(n, p1, p2):
n1 = str(n)[::-1]
if n1[p1-1] is n1[p2-1]:
return True
else:
return False
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
items = line.split(',')
if isSamePosition(format(int(items[0]), 'b'), int(items[1]), int(items[2])):
print "true"
else:
print "false"

import sys, codecs
def isSelfDescribingNumbers(n):
i = 0
for digit in n:
if int(digit) != line.count(str(i)):
return False
i += 1
return True
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
n = int(line)
if isSelfDescribingNumbers(line):
print 1
else:
print 0

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
n = int(line)
loop = 0
while(n != 1 and loop < 1000):
sum = 0
for digit in str(n):
sum += int(digit)**2
n = sum
loop += 1
if n == 1:
print 1
else:
print 0

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
items = line.split(',')
x = int(items[0])
n = int(items[1])
while(x > n):
n *= 2
print n

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.strip()
print format(int(line), 'b')

import sys
if "little" in str(sys.byteorder):
print "LittleEndian"
else:
print "BigEndian"

import sys, codecs
def isPalindrome(num):
if num == int(str(num)[::-1]):
return True
else:
return False
input = codecs.open(sys.argv[1], "r")
for line in input:
i = 0
line = line.strip()
num = int(line)
while(i <= 1000):
if isPalindrome(num):
break
num += int(str(num)[::-1])
i += 1
if isPalindrome(num):
print "%d %d" % (i, num)
else:
print False

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.lstrip()
line = line.rstrip()
words = line.split(" ")
if len(words) >= abs((int(words[-1]) * -1) - 1):
print words[(int(words[-1]) * -1) - 1]

def multiply12(n):
output = ""
for digit in range(12):
digit = digit + 1
result = digit * n
next_ = (digit +1) *n
if result < 10:
if next_ < 10:
separator = " "
elif next_ < 100:
separator = " "
elif result < 100:
if next_ < 100:
separator = " "
else:
separator = " "
else:
separator = " "
output += str(digit * n)+separator
return output
for i in range(12):
i = i + 1
print multiply12(i)

import sys, codecs, re
mail = re.compile("^[A-z0-9\-_\.\+]+\@[A-z0-9]+\.[A-z0-9\.]+[A-z]$")
def isValidMail(text):
if mail.match(text):
return True
else:
return False
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.rstrip()
if isValidMail(line):
print "true"
else:
print "false"

import sys, codecs
def find_lessthan_prime(n):
global primes
for i in range(n):
i = i + 1
if isPrime(i) and i > 1:
primes.append(i)
output = ""
for digit in primes:
output += str(digit)+","
return output[:-1]
def isPrime(n):
global primes
for d in primes:
if n < d:
break
if n % d is 0:
return False
return True
input = codecs.open(sys.argv[1], "r")
primes = []
for line in input:
line = line.rstrip()
print find_lessthan_prime(int(line))

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
sum_of_digits = 0
line = line.rstrip()
for digit in line:
sum_of_digits += int(digit)
print sum_of_digits

for n in range(100):
if n > 0:
if n % 2 > 0:
print n

import sys, codecs
def Fibonacci(n):
if n > 1:
return Fibonacci(n-1) + Fibonacci(n-2)
elif n is 1 or n is 0:
return n
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.rstrip()
print Fibonacci(int(line))

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
out = ""
line = line.rstrip()
items = line.split(",")
elementslist = list(set(items))
elementslist.sort()
for elements in elementslist:
out += elements+","
print out[:-1]+"\n",

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.rstrip()
items = line.split(",")
print items[0].rfind(items[1])

import sys, codecs
input = codecs.open(sys.argv[1], "r").readlines()
for i in range(len(input)):
input[i] = int(input[i])
print sum(input)

import sys, codecs, string
input = codecs.open(sys.argv[1], "r").readlines()
longlines = []
for line in input:
line = line.rstrip()
if len(longlines) != 0:
for i in range(len(longlines)):
if len(line) > len(longlines[i]):
longlines.insert(i, line)
break
else:
longlines.append(line)
for l in range(int(input[0])):
print longlines[l]

import sys, codecs, string
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.rstrip()
print line.translate(string.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'))

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
line = line.rstrip()
items = line.split(" ")
items.reverse()
out = ""
for item in items:
out += item+" "
print out

def isPrime(n):
global primes
for d in primes:
if n % d is 0:
return False
return True
primes = []
n = 0
while(len(primes) < 1000):
if n > 1:
if isPrime(n):
primes.append(n)
n += 1
print sum(primes)

def isPrime(n):
global primes
for d in primes:
if d > 1:
if n % d is 0:
return False
return True
def isPalindrome(n):
if (n / 100) is (n % 10):
return True
return False
primes = []
primepalindromes = []
for n in range(1000):
if isPrime(n):
primes.append(n)
if n >= 100:
if isPalindrome(n):
primepalindromes.append(n)
print primepalindromes[-1]

import sys, codecs
input = codecs.open(sys.argv[1], "r")
for line in input:
items = line.split(" ")
out = ""
for item in range(len(items)):
items[item] = int(items[item])
for l in range(items[2]+1):
if l is 0:
continue
elif l % items[0] is 0 and l % items[1] is 0:
out += "FB"
elif l % items[0] is 0:
out += "F"
elif l % items[1] is 0:
out += "B"
else:
out += str(l)
out += " "
print out