Array Handling
Python uses a list as an array and has a large library of functions for list processing.
An array is a mechanism of using the one variable name to access many instances of data of the one data type by using an index.
An example of this is the result of the spin of a poker machine. One of many instances of a given prize range may be the output. In the example below, there are 6 possible results of a spin - Plum, Apple, Apricot, Orange, Banana or Pineapple.
You have been contracted by Lucky Dot Casinos to produce a simulation program that will allow a customer to "roll" two dice. When each die has the same value, the customer wins a prize. The values of each die are Plum, Apple, Apricot, Orange, Banana and Pineapple.
#Poker machine written in Python
#import the random number generator library
import random
print 'Poker machine' #program heading
#instatiate the list
dice = ['Apricot', 'Apple', 'Orange', 'Banana', 'Plum', 'Pinapple']
#determine two random numbers (throw)
#and use this to select a fruit value from the list
throw = random.randint(0,5)
fruit1 = dice[throw]
throw = random.randint(0,5)
fruit2 = dice[throw]
#Display the selected fruit types
print fruit1, fruit2
#Display a win or loose statement
if fruit1 == fruit2:
print 'You Win'
else:
print 'You Loose'
print 'You have finished.'
Note
Using dice = ['Apricot', 'Apple', 'Orange', 'Banana', 'Plum', 'Pinapple'] will set the list index from 0-5
random.randint(0,5) returns a random number between 0 and 5 inclusive
Exercises
-
Mendez fish supply has 10 boats that catch fish. Each day, the weight of the biggest fish caught (in kgs) is sent to the head office. Your task is to write a program that will allow the weight of each fish and name of the boat to be recorded (in arrays). The weight of the largest fish is then to be determined by searching the array (of weights) and displayed along with the name of the boat that caught it.
Note: This requires two arrays - one for the weight of the fish and one for the name of the boat.
-
Palindromes are sentences that say the same thing in either direction - madam i'm adam - is an example (omitting spaces and other punctuation). Your task is to write a program that will take a sentence - excluding spaces and other punctuation - that will determine if the text makes a palindrome.
Note 1: You may need to use functions to disassemble into characters and reassemble characters into strings
Note 2: make all test data without spaces and punctuation ie madam i'm adam becomes madamimadam
-
Write a program that will multiply 2 arrays (3x3) of numbers.
[Python_Tutorial] [Sequence_Python] [Interation_Python] [Decision_Making_Python] [Arrays_Python] [Files_Python]
Comments (0)
You don't have permission to comment on this page.