Mimir:Draft4 Answer Key

From Openitware
Jump to: navigation, search

Contents

Answer Key

Chapter 1

Chapter 2

Chapter 3

Perl

#first answer
print "Enter your input:\n";
my $N = <STDIN>;
chomp($N);
if ($N % 2 == 0) {
    print "The number is even\n";
} else {
    print "The number is odd\n";
}

#second answer
@words;
while (true) {
    print "Enter a word or enter nothing to stop: ";
    my $userword = <STDIN>; 
    chomp $userword;
    if ($userword eq "")
    {
        foreach (@words) {
          print "$_\n";
        }
        last;
    }
    else
    {
        push (@words, $userword);
    }
        
}

#third answer
print"Welcome to guess my number!\n";
    $compNumber=int rand 20;
    while(true){
        print"Guess a number between 1 and 20: ";
        chomp($userNumber=<STDIN>);
        if($compNumber>$userNumber){
            print"Your guess was too low, try again.\n";
        }
        if($compNumber<$userNumber){
            print"Your guess was too  high, try again.\n";
        }
        if($compNumber==$userNumber){
            print"Well done, $compNumber was my number!";
            last;
        }
    }
	
#fourth answer
sub fibonacci {
    my $n = shift;

    return undef if $n < 0;

    my $f;
    if ($n == 0) {
        $f = 0;
    } elsif ($n == 1) {
        $f = 1;
    } else {
        $f = fibonacci($n-1) + fibonacci($n-2);
    }
    
    return $f;
}

#fifth answer
sub factorial
{
   my $number = shift;  

   if ( $number <= 1 ) { 
      return 1;
   }
   else {               
      return $number * factorial( $number - 1 );
   }
}

#sixth answer
print "Type a message to be reversed: \n";
my $str = <STDIN>;
my $rev = reverse $str;
print $rev . "\n";

Python

#first answer
print("Enter your input: ")
number = input()
if (int(number) % 2 == 0): 
	print("Number is even")
else:
	print("Number is odd")

# second answer
words = []
while True:
    print('Enter word: ' + str(len(words) + 1) +
    ' (Or enter nothing to stop.):')
    name = input()
    if name == '':
        break
    words = words + [name] 
print('The words are:')
for name in words:
    print(' ' + name)

#third answers
import random

number = random.randint(1, 20)
while True:
    print ("Guess a number between 1 and 20: ")
    guess = input()
    guess = int(guess)
    
    if guess < number:
        print('Your guess is too low.')
        
    if guess > number:
        print('Your guess is too high.')
            
    if guess == number:
        print ("Well done, " + str(number) + " was my number!")
        break

#fourth answer
def fib(n):
 if n==1 or n==2:
  return 1
 return fib(n-1)+fib(n-2)

#fifth answer
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

#sixth answer
print("Type a message to be reversed: ")
word = input()
message = ''
for b in word:
    message = b+message
print (message)