G; assign(L, index, val): Returns a new list identical to L, but in which the item at the index position in L is replaced by val.

From EECS 182
G; assign(L, index, val): Returns a new list identical to L, but in which the item at the index position in L is replaced by val.
Jump to: navigation, search
 
Line 1: Line 1:
# Thinking approach: Don't see an obvious base case. So, probably not a recursive solution.
+
<pre>
 +
# Thinking approach: Don't see an obvious base case. So, probably not a recursive solution
 
# Think of another way. Slicing is available to us. May be make use of that. Chop into
 
# Think of another way. Slicing is available to us. May be make use of that. Chop into
 
# three parts: items before the value, the value to be replaced, and the items after.  
 
# three parts: items before the value, the value to be replaced, and the items after.  
 +
 
#  replace the middle part with the new value, and reassemble the three parts. To
 
#  replace the middle part with the new value, and reassemble the three parts. To
 +
 
# reassemble, make use of the concat function that we already wrote.
 
# reassemble, make use of the concat function that we already wrote.
  
Line 12: Line 15:
 
     else:
 
     else:
 
         return "error"
 
         return "error"
 +
 +
# You can try doing this without indexing operation availability.
 +
</pre>

Latest revision as of 02:27, December 15, 2012

# Thinking approach: Don't see an obvious base case. So, probably not a recursive solution
# Think of another way. Slicing is available to us. May be make use of that. Chop into
# three parts: items before the value, the value to be replaced, and the items after. 

#  replace the middle part with the new value, and reassemble the three parts. To

# reassemble, make use of the concat function that we already wrote.

def assign(L, index, val):
    if (len(L) > index+1):
        return concat(L[0..index].append(val),  L[index+1:])
    elif (len(L) == index+1):
        return L[0..index].append(val)
    else:
        return "error"

# You can try doing this without indexing operation availability.
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
EECS @ UM
Tools