

InterviewSolution
1. |
Examine the following code :numlist =eval(input(" Enter list:")) pos = 0 odds = evens = 0 length=len(numlist ) while pos< length: if numlist [ pos ]%2== 0evens = evens + 1 else: odds = odds + 1 pos = pos + 1 If odds> evens :print ("Balanced oddity )1-: What is this program calculating ? 2-: What does the program for the list [1, 5, 2, 3, 6, 6, 9] ? 3-:What does the program print for the list [2, 5, 2, 3, 6, 6, 9] ? How can we fix this? |
Answer» Answer: A list is an ordered SET of values, where each value is identified by an index. The values that make up a list are called its elements. LISTS are similar to strings, which are ordered sets of characters, except that the elements of a list can have any type. Lists and strings — and other things that behave like ordered sets — are called sequences. 9.1. List values There are several ways to create a new list; the simplest is to enclose the elements in square brackets ( [ and ]): [10, 20, 30, 40] ["spam", "bungee", "swallow"] The first example is a list of four integers. The second is a list of three strings. The elements of a list don’t have to be the same type. The following list CONTAINS a string, a float, an integer, and (mirabile dictu) another list: ["hello", 2.0, 5, [10, 20]] A list within another list is said to be nested. Finally, there is a special list that contains no elements. It is called the empty list, and is denoted []. Like numeric 0 values and the empty string, the empty list is false in a boolean expression: >>> if []: ... print 'This is true.' ... else: ... print 'This is false.' ... This is false. >>> With all these ways to create lists, it would be disappointing if we couldn’t assign list values to variables or pass lists as parameters to functions. We can: >>> vocabulary = ["ameliorate", "castigate", "defenestrate"] >>> NUMBERS = [17, 123] >>> empty = [] >>> print vocabulary, numbers, empty ['ameliorate', 'castigate', 'defenestrate'] [17, 123] [] 9.2. Accessing elements The syntax for accessing the elements of a list is the same as the syntax for accessing the characters of a string—the bracket operator ( [] – not to be confused with an empty list). The expression inside the brackets specifies the index. Remember that the indices start at 0: |
|