logo
down
shadow

Looping through a function


Looping through a function

By : link89
Date : January 11 2021, 03:34 PM
I hope this helps . So to solve the response as a string issue I would suggest using python's builtin json module. Specifically, the method .loads() can convert a string to a dict or list of dicts. From there you can iterate over the list or dict and check if the key is equal to 'id'. Here's an example based on what you said the response would look like.
code :
import json

s = "[{'_from': None, 'to': {'id': '5c9941fcdd2eeb6a6787916e', 'type': 'user'}}, {'_from': None, 'to': {'id': '5cc9055fcc5781152ca6eeb8', 'type': 'user'}}, {'_from': None, 'to': {'id': '5d1cf102c94c052cf1bfb3cc', 'type': 'user'}}]"

# json uses double quotes and null; there is probably a better way to do this though
s = s.replace("\'", '\"').replace('None', 'null') 

response = json.loads(s)  # list of dicts

for d in response:
    for key, value in d['to'].items():
        if key == 'id':
            print(value)  # or whatever else you want to do

            # 5c9941fcdd2eeb6a6787916e
            # 5cc9055fcc5781152ca6eeb8
            # 5d1cf102c94c052cf1bfb3cc



Share : facebook icon twitter icon
Looping through query results and call a function for each - function contains sleep command

Looping through query results and call a function for each - function contains sleep command


By : Tabby Tabs
Date : March 29 2020, 07:55 AM
With these it helps Resolved. I have restructured my code so that the query is done inside the for loop that contains the sleep command. So it loops through all the results per sleep.
Looping through a function in python but redefining a variable when a function from an array of functions gets called

Looping through a function in python but redefining a variable when a function from an array of functions gets called


By : user2626745
Date : March 29 2020, 07:55 AM
Any of those help Say I have the following example, in python: , Could this be what you want ?
code :
def test1(x):
    x=x**2

    return x

def test2(x):
    x=x**3

    return x

def test3(x):
    x=x+10

    return x


testlist = []
n=0
y_vals=[1,2,3,4,5]

x_fn = [test1, test2, test3]

for fun in x_fn:
    for y in y_vals:

        x = y*2
        z=fun(x)

        testlist.append(z)

print testlist
While looping through a function, Error: Maximum stored procedure, function, trigger, or view nesting level exceeded (li

While looping through a function, Error: Maximum stored procedure, function, trigger, or view nesting level exceeded (li


By : user2955926
Date : November 22 2020, 10:48 AM
I wish did fix the issue. Im going to assume that the purpose of this exercise is to split the values out of the columns so that you can then normalise your data.
regarding the actual error read @Amir's answer regarding helping you with solving your problem have a look at my approach below, hopefully you can pull something from that to help you.
code :
-- set up our sample datasource
declare @source as table 
(
    ProductNo int, 
    S1_CR varchar(100), 
    S1_CAT1 varchar(100), 
    S1_CAT2 varchar(100), 
    S1_CAT3 varchar(100), 
    S1_CAT4 varchar(100)
)

insert into @source values (1234, 'Prod1#Prod2#Prod3', '10#200#300', '20#34#400', '40#12#12', '50#23#12')

-- set up what will become input parameters to our sp
declare @prodNo     int = 1234
declare @code       varchar(10) = 'Prod2'
--Note that there are not Columns named Product, Year in the sample data but you refer to it in your Query so I assume they exist
declare @Product    varchar(10) -- is your declaration long enough? calling your sp you use 'ProductName1' which wont fit.
declare @year       varchar(4) = '2010'

-- this could be a constant if it doesnt change from record to record,
-- or a parameter if it does
declare @delimiter  char    = '#'

--declare our variables
declare @output     table
(
    ProductNo int, 
    S1_CR   varchar(100), 
    S1_CAT1 varchar(100), 
    S1_CAT2 varchar(100), 
    S1_CAT3 varchar(100), 
    S1_CAT4 varchar(100)
)

declare @ProductNo  int 
declare @S1_CR      varchar(100)
declare @S1_CAT1    varchar(100) 
declare @S1_CAT2    varchar(100) 
declare @S1_CAT3    varchar(100) 
declare @S1_CAT4    varchar(100)

--these ones are used during validation
declare @index      int = 1     
declare @term_count int = 0 -- this counts the number of terms in the column we are looking at
declare @num_terms  int = 0 -- this becomes our fixed comparison value
declare @reviewing  varchar(100) -- this is the data from the column we are looking at

select 
    @ProductNo = s.ProductNo,
    @S1_CR = s.S1_CR + @delimiter,
    @S1_CAT1 = s.S1_CAT1 + @delimiter,  
    @S1_CAT2 = s.S1_CAT2 + @delimiter,
    @S1_CAT3 = s.S1_CAT3 + @delimiter,
    @S1_CAT4 = s.S1_CAT4 + @delimiter
from @source s
where s.ProductNo = @prodNo

set @reviewing = @S1_CR

--validate to ensure there are equal number of concatenated terms in each column
--you will probably want to do other validation on inputs etc.
while @index > 0 --and @num_terms > 0
begin

    set @index = CHARINDEX(@delimiter, @reviewing, @index +1)

    if @index > 0 
        set @term_count = @term_count + 1
    else if @index = 0 and @term_count  @num_terms and @reviewing  @S1_CR -- num_terms will be zero when reviewing the first column
        set @num_terms = 0
    else 
        begin

            select 
                @num_terms = case @reviewing
                                when @S1_CR then @term_count
                                else @num_terms
                            end,
                @reviewing = case @reviewing
                                when @S1_CR then @S1_CAT1
                                when @S1_CAT1 then @S1_CAT2
                                when @S1_CAT2 then @S1_CAT3
                                when @S1_CAT3 then @S1_CAT4 
                                else ''
                            end

            if @reviewing = ''
                set @index = 0
            else
                set @index = 1
                set @term_count = 0
        end
end

--Split out the terms
while @num_terms > 0
begin    
    insert into @output values
    (
        @ProductNo,
        left(@S1_CR,CHARINDEX(@delimiter,@S1_CR,1) -1),
        left(@S1_CAT1,CHARINDEX(@delimiter,@S1_CAT1,1) -1),
        left(@S1_CAT2,CHARINDEX(@delimiter,@S1_CAT2,1) -1),
        left(@S1_CAT3,CHARINDEX(@delimiter,@S1_CAT3,1) -1),
        left(@S1_CAT4,CHARINDEX(@delimiter,@S1_CAT4,1) -1)
    )

    set @S1_CR = right(@S1_CR,len(@S1_CR) - CHARINDEX(@delimiter,@S1_CR,1))
    set @S1_CAT1 = right(@S1_CAT1,len(@S1_CAT1) - CHARINDEX(@delimiter,@S1_CAT1,1))
    set @S1_CAT2 = right(@S1_CAT2,len(@S1_CAT2) - CHARINDEX(@delimiter,@S1_CAT2,1))
    set @S1_CAT3 = right(@S1_CAT3,len(@S1_CAT3) - CHARINDEX(@delimiter,@S1_CAT3,1))
    set @S1_CAT4 = right(@S1_CAT4,len(@S1_CAT4) - CHARINDEX(@delimiter,@S1_CAT4,1))

    set @num_terms = @num_terms - 1
end

select * from @output where S1_CR = @code
How can I make my function faster (the function is looping through a multidimensional array)?

How can I make my function faster (the function is looping through a multidimensional array)?


By : Abdul Suadik Mohamme
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , It seems your code produces the same output, no matter if $baseval is TRUE or FALSE. The following code produces the same output, runs fast and gracefully ignores the value of $baseval too:
code :
function explodeTree(array $array, $delimiter = "_", $baseval = false)
{
    # Build the output here
    $returnArr = array();

    foreach ($array as $item) {
        # Split the path using the delimiter, drop the empty segments
        $pieces = array_filter(explode($delimiter, $item['path']));
        # Turn the path into a nested array
        # Each component of the path is the only key on its level
        # Build it from the leaf up to the root
        $a = array_reduce(
            array_reverse($pieces),        # Start from the leaf
            function (array $carry, $piece) {     # Create parent node...
                return array($piece => $carry);   # ... use the path piece as key
            },
            $item                          # Put the item itself as leaf
        );

        # Combine the new path (nested arrays) into the existing tree
        # array_merge_recursive() takes care of all the levels
        $returnArr = array_merge_recursive($returnArr, $a);
    }

    # That's all
    return $returnArr;
}
["folder2"]=>
array(1) {
  ["cat"]=>
  array(1) {
    ["sam"]=>
    array(4) {
      ["path"]=>
      string(23) "Volumes/folder2/cat/sam"
      ["age"]=>
      string(2) "11"
      ["name"]=>
      string(3) "sam"
      ["john"]=>
      array(3) {
        ["path"]=>
        string(28) "Volumes/folder2/cat/sam/john"
        ["age"]=>
        string(2) "16"
        ["name"]=>
        string(4) "john"
      }
    }
  }
}
["folder2"]=>
array(1) {
  ["cat"]=>
  array(1) {
    ["sam"]=>
    array(2) {
      ["__base_val"]=>
      array(3) {
        ["path"]=>
        string(23) "Volumes/folder2/cat/sam"
        ["age"]=>
        string(2) "11"
        ["name"]=>
        string(3) "sam"
      }
      ["john"]=>
      array(3) {
        ["path"]=>
        string(28) "Volumes/folder2/cat/sam/john"
        ["age"]=>
        string(2) "16"
        ["name"]=>
        string(4) "john"
      }
    }
  }
}
function explodeTree(array $array, $delimiter = "_", $baseval = false)
{
   # Build the output here
   $returnArr = array();

   foreach ($array as $item) {
      # Split the path using the delimiter, drop the empty segments
      $pieces = array_filter(explode($delimiter, $item['path']));
      # Keep a reference to the current node; start from the root of the tree we build
      $pos = &$returnArr;
      foreach ($pieces as $piece) {
        if (! array_key_exists($piece, $pos)) {
            # The path component doesn't exist in the tree; add it
            $pos[$piece] = array();
        } elseif ($baseval && array_key_exists('path', $pos[$piece])) {
            # The component exists, it is a leaf node (has 'path' property) and $baseval is TRUE
            # Save the existing node content
            $val = $pos[$piece];
            # Replace it with a new level; store the old leaf in '__base_val'
            $pos[$piece] = array('__base_val' => $val);
        }
        # Advance to the next level
        $pos = &$pos[$piece];
      }

      # If $baseval is TRUE, make sure we don't mix leaf nodes with inner nodes
      if ($baseval && ! empty($pos)) {
         # The node already has children; put the item in '__base_val'
         $pos['__base_val'] = $item;
      } else {
         # The node was just added; store $item in it
        $pos = array_merge($pos, $item);
      }

      unset($pos);
   }

   return $returnArr;
}
Looping through python function and savings inputs and function value in a matrix format

Looping through python function and savings inputs and function value in a matrix format


By : MrMan
Date : March 29 2020, 07:55 AM
I wish this helpful for you I have a function, f, and I am trying to evaluate it at x, y and z: , Here is program which might help you:
code :
x = range(60, 70)
y = range(0,5)
z = ["type1", "type2"]
ans = []
for i in x:
    for j in y:
        for k in z:
            ans.append([i, j, k, f(i, j, k)])

print(ans)
Related Posts Related Posts :
  • Tuning the hyperparameter with gridsearch results in overfitting
  • some coordinates that I extracted from geocoder in Python are not saving in the variable I created
  • 7C in cs circles- python Im not sure what is wrong with this yet
  • How to fix 'AttributeError: 'list' object has no attribute 'shape'' error in python with Tensorflow / Keras when loading
  • python - thread`s target is a method of an object
  • Retrieve Variable From Class
  • What is the reason for matplotlib for printing labels multiple times?
  • Why would people use ThreadPoolExecutor instead of direct function call?
  • When clear_widgets is called, it doesnt remove screens in ScreenManager
  • Python can't import function
  • Pieces doesn't stack after one loop on my connect4
  • How to change font size of all .docx document with python-docx
  • How to store a word with # in .cfg file
  • How to append dictionaries to a dictionary?
  • How can I scrape text within paragraph tag with some other tags then within the paragraph text?
  • Custom entity ruler with SpaCy did not return a match
  • Logging with two handlers - one to file and one to stderr
  • How to do pivot_table in dask with aggfunc 'min'?
  • This for loop displays only the last entry of the student record
  • How to split a string by a specific pattern in number of characters?
  • Python 3: how to scrape research results from a website using CSFR?
  • Setting the scoring parameter of RandomizedSeachCV to r2
  • How to send alert or message from view.py to template?
  • How to add qml ScatterSeries to existing qml defined ChartView?
  • Django + tox: Apps aren't loaded yet
  • My css and images arent showing in django
  • Probability mass function sum 2 dice roll?
  • Cannot call ubuntu 'ulimit' from python subprocess without using shell option
  • Dataframe Timestamp Filter for new/repeating value
  • Problem with clicking select2 dropdownlist in selenium
  • pandas dataframe masks to write values into new column
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org