CSCE 110: Programming IMore Examples of Using Lists and StringsSeptember 25, 20111. Below, we show a program that gives an example of how to use lists to compute the sum ofdifferent values in a list.Listing 1: list-example.py1 # Playing with list indices to compute the sums of numbers .23 import random45 # Create a list of random numbers6 num_vals = int ( raw_input (" How many integers ?: " ))7 numbers = [0] * num_vals8 for i in range (0 , num_vals ):9 numbers [ i] = random . randint ( -100 , 100)10 print " The list of numbers is :" , numbers1112 # Compute numbers [0] + numbers [ -1] , numbers [1] + numbers [ -2] , etc .13 if num_vals % 2 == 0:14 sums = [0] * ( num_vals / 2)15 else :16 sums = [0] * (( num_vals / 2) + 1)1718 for i in range (0 , num_vals /2 ):19 sums [i] = numbers [i ] + numbers [ -( i +1)]2021 if num_vals % 2 == 1:22 sums [ num_vals / 2] = numbers [ num_vals / 2]23 print " The sums are :" , sums 12. Here is a program to determine whether a word is a palindrome. For those students wantingan extra challenge, come up with a few different ways of solving this problem.Listing 2: palindrome.py1 # Checks to see whether a user entered a word that is a palindrome . A2 # palindrome is a word that reads the same forwards and backwa rds .3 # There are many ways to solve this problem . I ’m just showing you one4 # of the many possible solutions .56 phrase = raw_input (" Please enter a word : ")78 p a l indrome = True9 index = 010 while ( palindrome == True ) and ( index <= len ( phrase )/2):11 if phrase [ index ] != phrase [ -( index +1)]:12 palindrome = False13 index = index + 11415 if palindrome == True :16 print phrase , "is a pa l indrome !"17 else :18 print phrase , "is NOT a palind r o m e !"
View Full Document