Help me create this code please!!

255 views
Skip to first unread message

ChristinaK98

unread,
Oct 1, 2017, 5:14:46 PM10/1/17
to Python GCU Forum

Write a function hide_inside that consumes a list, an item, and a nonnegative integer pos.


Your function should produce a new list that contains all the items of the input list with the new item inserted in position pos. For example,


hide_inside(["a", "b"], "cat", 1]


will produce ["a", "cat", "b"]. If pos is greater than the length of the list, the item should appear at the end of the list. For example,


hide_inside(["a", "b"], "cat", 20]


will produce ["a", "b", "cat"].


But MODIFIED so that it has a default value such that if no position value is entered it will assume a value of zero. Call you function hide_inside_default.



Debraj Das

unread,
Oct 2, 2017, 4:27:38 AM10/2/17
to Python GCU Forum
Hi, I am just learning Python.So pardon any silly mistake.
I think the list_name.insert(position_u wanna_insert , the_value_u_wanna_insert) will do the work just fine, r8?

Pradeep Kumar S

unread,
Oct 4, 2017, 12:54:39 AM10/4/17
to Python GCU Forum
// code is less elegant but does the work


def hide_inside(input_list,item,pos):
  out_list = []
  if pos > len(input_list):
    out_list.extend(input_list)
    out_list.extend(item)
  elif pos <= 0:
    out_list.extend(item)
    out_list.extend(input_list)
  else:
    out_list.extend(input_list[:pos])
    out_list.extend(item)
    out_list.extend((input_list[pos:]))
    
  return out_list

// data 
input_list = ['a','c']
pos = 2
item = 'd'

// output
print hide_inside(input_list,item,pos)

On Monday, October 2, 2017 at 2:44:46 AM UTC+5:30, ChristinaK98 wrote:

pradeep

unread,
Oct 4, 2017, 1:17:54 AM10/4/17
to Python GCU Forum
input_list = ['a','c']
pos = 11
item = 'b'

def hide_inside(input_list,item,pos):
  
  if pos > len(input_list):
    input_list.insert(len(input_list),item)
  elif pos <= 0:
    input_list.insert(0,item)
  else:
    input_list.insert(pos,item)
    
  return input_list
  
print hide_inside(input_list,item,pos)  

On Monday, October 2, 2017 at 2:44:46 AM UTC+5:30, ChristinaK98 wrote:
Reply all
Reply to author
Forward
0 new messages