PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How to loop multiple appends for python

 May 13, 2022     append, for-loop, list, loops, python     No comments   

Issue

num_pixels_per_cell_one_axis = 5
num_cells_per_module_one_axis = 3
inter_cell_sep = 4

max_items_in_list = num_cells_per_module_one_axis * num_pixels_per_cell_one_axis + (num_cells_per_module_one_axis-1) * inter_cell_sep

print(max_items_in_list)

indices_to_retain = list(range(max_items_in_list))
indices_to_remove = indices_to_retain[num_pixels_per_cell_one_axis :: num_pixels_per_cell_one_axis + inter_cell_sep]
if inter_cell_sep == 2:
    for k in range(0,len(indices_to_remove)):
        indices_to_remove.append(indices_to_remove[k]+1)
        
if inter_cell_sep == 3:
    for k in range(0,len(indices_to_remove)):
        indices_to_remove.append(indices_to_remove[k]+1)
        indices_to_remove.append(indices_to_remove[k]+2)
        
    
for k in indices_to_remove:
    indices_to_retain.remove(k)
    

print(indices_to_remove)
print(indices_to_retain)

I want to find a way to loop inter_cell_sep for any positive number and as it increases the lines for appending the list also increases. The expected answer should be [0,1,2,3,4,9,10,11,12,17,18,19,20]


Solution

I think instead of using if statements for each value of inter_cell_sep you could loop through a range of inter_cell_sep. Here is what I came up with.

num_pixels_per_cell_one_axis = 5
num_cells_per_module_one_axis = 3
inter_cell_sep = 3

max_items_in_list = num_cells_per_module_one_axis * num_pixels_per_cell_one_axis + (num_cells_per_module_one_axis - 1) * inter_cell_sep

print(max_items_in_list)

indices_to_retain = list(range(max_items_in_list))
indices_to_remove = indices_to_retain[num_pixels_per_cell_one_axis:: num_pixels_per_cell_one_axis + inter_cell_sep]

for k in range(0, len(indices_to_remove)):
    indices_to_remove.extend([indices_to_remove[k] + x for x in range(1, inter_cell_sep)])

for k in indices_to_remove:
    indices_to_retain.remove(k)

print(indices_to_remove)
print(indices_to_retain)


Answered By - nickrl21
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing