PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label iteration. Show all posts
Showing posts with label iteration. Show all posts

Tuesday, November 22, 2022

[FIXED] How to set multiple conditions using an iteration for python

 November 22, 2022     iteration, multiple-conditions, pandas, pandas-loc, python     No comments   

Issue

I am looking for a gradient pattern on my dataframe as follows:

df.loc[(
        (df['A'].shift(-0).lt(1.7)) &
        (df['A'].shift(-1).lt(1.7)) &
        (df['A'].shift(-2).lt(1.7)) &
        (df['A'].shift(-3).lt(1.7)) &
        (df['A'].shift(-4).lt(1.7)) &
        (df['A'].shift(-5).lt(1.7)) &
]

The latter will return a df where 6 previous values are smaller than 1.7 for example:

the data frame will look like this (before and after):

         A
329    15.1252
330    13.1251
331     1.3125
332     1.5625
333    39.5625
346    45.6875
347    11.0000
348    11.0000
354     1.8125
355     1.8125
358     1.4375
359     1.4375
360     1.5000
361     1.5000
362     1.5000
363     1.5000
364     1.4375
365     1.4375
366     1.5000 

         A
364    1.4375
365    1.4375
366    1.5000


It works but I want to improve it. I tried many things, I think it could be something like:

parameters = [
    [0, 1.7],
    [1, 1.7],
    [2, 1.7],
    [3, 1.7],
    [4, 1.7],
    [5, 1.7],
]

conditions = ([ ' & ' .join(['(df["A"].shift(-{0}).lt({1}))'.format(x[0], x[1]) for x in parameters])])
conditions = '(' + conditions ')'
df.loc[conditions]

It seems that 'conditons' is returned as string between quotes litterally as 'conditions', so df.loc[conditions] returns a 'KeyError'

Is my first question on the website. Thanks in advance.


Solution

You can try use reduce on list

from functools import reduce

m = reduce((lambda df1, df2: df1&df2), [df['A'].shift(-s).lt(v) for s, v in parameters])
print(df.loc[m])

          A
358  1.4375
359  1.4375
360  1.5000
361  1.5000


Answered By - Ynjxsjmh
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 16, 2022

[FIXED] How to print this information in a good format (vertical alignment) in python?

 November 16, 2022     alignment, iteration, python, vertical-alignment     No comments   

Issue

Im trying to have this information align vertically and not overlap. I have only used print("\t xyz \t") for each iteration and it prints it side by side, as it should, but some strings are longer than others.

How it is

How I want it

Current Output:

Ticker :         GME          

Employees :        14000         

Title :     CEO & Director      Exec. VP & CFO      Exec. VP & Chief Merchandising Officer

Name :      Mr. George E. Sherman       Mr. James Anthony Bell  Mr. Chris R. Homeister

Ages :      58      52      51

Pay :       1,900,374 USD       801,318 USD     766,266 USD

Solution

Generally the way to do this is to either hard code the size of each column, or run through the data, and find a column width to use for each column.

If you want to loop through and adapt the column width, the code is fairly straight forward:

rows = [
    ["Ticker :", "GME"],
    ["Employees :", "14000"],
    ["Title :", "CEO & Director", "Exec. VP & CFO", "Exec. VP & Chief Merchandising Officer"],
    ["Name :", "Mr. George E. Sherman", "Mr. James Anthony Bell", "Mr. Chris R. Homeister"],
    ["Ages :", "58", "52", "51"],
    ["Pay :", "1,900,374 USD", "801,318 USD", "766,266 USD"],
]

# Build up a max length of each column
lengths = {}
for row in rows:
    for i in range(len(row)):
        lengths[i] = max(lengths.get(i, 0), len(row[i]))

for row in rows:
    # For each cell, padd it by the max length
    output = ""
    for i in range(len(row)):
        if len(output) > 0:
            # Add a space between columns
            output += " "
        cell = row[i] + " " * lengths[i]
        cell = cell[:lengths[i]]
        output += cell
    print(output)

This will output:

Ticker :    GME
Employees : 14000
Title :     CEO & Director        Exec. VP & CFO         Exec. VP & Chief Merchandising Officer
Name :      Mr. George E. Sherman Mr. James Anthony Bell Mr. Chris R. Homeister
Ages :      58                    52                     51
Pay :       1,900,374 USD         801,318 USD            766,266 USD


Answered By - Anon Coward
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 29, 2022

[FIXED] What is the perfect counterpart in Python for "while not EOF"

 October 29, 2022     eof, file, iteration, python     No comments   

Issue

To read some text file, in C or Pascal, I always use the following snippets to read the data until EOF:

while not eof do begin
  readline(a);
  do_something;
end;

Thus, I wonder how can I do this simple and fast in Python?


Solution

Loop over the file to read lines:

with open('somefile') as openfileobject:
    for line in openfileobject:
        do_something()

File objects are iterable and yield lines until EOF. Using the file object as an iterable uses a buffer to ensure performant reads.

You can do the same with the stdin (no need to use raw_input():

import sys

for line in sys.stdin:
    do_something()

To complete the picture, binary reads can be done with:

from functools import partial

with open('somefile', 'rb') as openfileobject:
    for chunk in iter(partial(openfileobject.read, 1024), b''):
        do_something()

where chunk will contain up to 1024 bytes at a time from the file, and iteration stops when openfileobject.read(1024) starts returning empty byte strings.



Answered By - Martijn Pieters
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the perfect counterpart in Python for "while not EOF"

 October 29, 2022     eof, file, iteration, python     No comments   

Issue

To read some text file, in C or Pascal, I always use the following snippets to read the data until EOF:

while not eof do begin
  readline(a);
  do_something;
end;

Thus, I wonder how can I do this simple and fast in Python?


Solution

Loop over the file to read lines:

with open('somefile') as openfileobject:
    for line in openfileobject:
        do_something()

File objects are iterable and yield lines until EOF. Using the file object as an iterable uses a buffer to ensure performant reads.

You can do the same with the stdin (no need to use raw_input():

import sys

for line in sys.stdin:
    do_something()

To complete the picture, binary reads can be done with:

from functools import partial

with open('somefile', 'rb') as openfileobject:
    for chunk in iter(partial(openfileobject.read, 1024), b''):
        do_something()

where chunk will contain up to 1024 bytes at a time from the file, and iteration stops when openfileobject.read(1024) starts returning empty byte strings.



Answered By - Martijn Pieters
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 18, 2022

[FIXED] How can I find number of iterations from this function in R

 October 18, 2022     for-loop, function, iteration, r     No comments   

Issue

Maybe you can help me with this code. I got only 4 values, which are right and needed, but also I need to make a table with all iterations, till I get those right values, but I don't know how to get number of those iterations from this function I have: example provided here enter image description here

E <- matrix(c(1, 0, 0, 0,
              0, 1, 0, 0, 
              0, 0, 1, 0, 
              0, 0, 0, 1), byrow = TRUE, nrow = 4)

B <- matrix(c(1.2, 2, 3, 1.5), nrow = 4, byrow = TRUE)

D <- matrix(c(0.18, 0.57, 0.38, 0.42,
              0.57, 0.95, 0.70, 0.44,
              0.38, 0.70, 0.37, 0.18,
              0.42, 0.44, 0.18, 0.40), byrow = TRUE, nrow = 4)

#my matrix
A <- D + 0.1*(8+3)*E
A

# Define a convenience function matching `numpy.inner`
inner <- function(a, b) as.numeric(as.numeric(a) %*% as.numeric(b))

conjugate_grad <- function(A, b) {    
  n <- dim(A)[1]
  x <- numeric(n)
  z <- b - A %*% x
  p <- z
  z_old <- inner(z, z)
  for (i in 1:60) {
    teta <- z_old / inner(p, (A %*% p))
    x <- x + teta * p
    z <- z - teta * A %*% p
    z_new <- inner(z, z)
    if (sqrt(z_new) < 0.001)
      break
    beta <- z_new / z_old
    p <- z + beta * p
    z_old <- z_new
  }
  return(x) 
}

conjugate_grad(A,B)


Thank you in advance!


Solution

I think this modification of your code gives you what you want:

conjugate_grad <- function(A, b) {    
  n <- dim(A)[1]
  x <- numeric(n)
  history <- NULL   # Insert this line 
  z <- b - A %*% x
  p <- z
  z_old <- inner(z, z)
  for (i in 1:60) {
    teta <- z_old / inner(p, (A %*% p))
    x <- x + teta * p
    history <- cbind(history, x)   # Insert this line
    z <- z - teta * A %*% p
    z_new <- inner(z, z)
    if (sqrt(z_new) < 0.001)
      break
    beta <- z_new / z_old
    p <- z + beta * p
    z_old <- z_new
  }
  return(history)      # return history instead of x
}

conjugate_grad(A,B)
#           [,1]      [,2]       [,3]       [,4]
# [1,] 0.4326431 0.1288703 0.09609509 0.08061088
# [2,] 0.7210718 0.1695202 0.15988971 0.16900513
# [3,] 1.0816077 1.8689058 1.85211220 1.85311415
# [4,] 0.5408039 0.6284172 0.70703113 0.70548042

You have to accumulate the results as you compute them in an object, here called history.



Answered By - dcarlson
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 7, 2022

[FIXED] How can I write an additional piece of code to add all my outputs together?

 October 07, 2022     iteration, python, statistics, sum     No comments   

Issue

So I wrote this code that returns the mean of the first three rows of a file.

import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))

and I correctly get the output, which is

100.177647525
97.27899259
100.2046613525

now I want to write an additional block of code that will add the outputs of this code together, in other words, I would like to add 100.177647525, 97.27899259 and 100.2046613525 together. I tried to do this by writing this up..

import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))
s = 0
for x in statistics.mean(h):
    s += x
print(s)

but I'm getting an error message saying "TypeError: 'float' object is not iterable". so what changes should I make to make this work?


Solution

You need to store the values in a variable or may be append a list with all the values like below: ####Solution 1: Store values in a list####


import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    sum_list = []
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))
        sum_list.append(statistics.mean(h))
    total = sum(sum_list)
print(total) 

####Solution 2: keep adding the value to a variable####


import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    count = 0
    total = 0
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))
        count = statistics.mean(h)
        total = total + count
print(total)

I didn't run these codes yet but I think they should work.



Answered By - PandasasPD
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, September 16, 2022

[FIXED] Why inserting `format` function inside a `dolist` expression does not work in Common Lisp?

 September 16, 2022     common-lisp, format, iteration, printing     No comments   

Issue

I am using SBCL, Eamcs, and Slime. Using the print function, I can do:

CL-USER> (dolist (item '(1 2 3))
           (print item))
1 
2 
3 
NIL

In addition, format function works for single elements:

CL-USER> (format nil "~a" 1)
"1"

Why the following insertion of format function inside dolist does not work?

CL-USER> (dolist (item '(1 2 3))
           (format nil "~a" item))
NIL

I was expecting to see all elements of the list processed by the format function.

Thanks


Solution

The answer to this is that the first argument to format denotes a destination for the formatted output. It may be one of four things:

  • a stream, to which output goes;
  • t which denotes the value of the *standard-output* stream;
  • nil which causes format to return the formatted output rather than print it;
  • or a string with a fill pointer, which will append the output to the string at the fill pointer.

So (format nil ...) does not print anything: it returns something.



Answered By - ignis volens
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 18, 2022

[FIXED] How to iterate an Array inside an iterating set of JSON outputs in Angular?

 August 18, 2022     angular, iteration, loops, output     No comments   

Issue

I have a database table which save data about hotels. A hotel can have multiple contact numbers and implemented using a composite table for contact numbers. I want to display all the information of existing hotels. My output displays everything else other than the contact numbers. Please tell me a way to iterate and show the contact numbers of each hotel.

Here's the data coming to front end

address1: "No 400,"
address2: "Beach Road,"
city: "Colombo"
contacts: Array(2)
0: {contactNo: "0712244587"}
1: {contactNo: "0775469823"}
length: 2
__proto__: Array(0)
email: "kingsbury@gmail.com"
hid: 1
hotelName: "Kingsbury"
state: "Western"
zipCode: "10000"

.html code

<div
            class="card"
            style="height: 750px;"
            *ngFor="let hotel of availableHotels"
          >
            <div class="card-img-top">
              <div class="card-body">
                <img
                  style="width: 15cm; height: auto;"
                  src="../../assets/images/car2.jpg"
                  class="card-img"
                  id="img"
                  alt="..."
                />
                <h2 style="margin-top: 20px;">Hotel : {{ hotel.hotelName }}</h2>
                <h4 >{{ hotel.city }}</h4>
                <p class="font-weight-bold">Address : {{hotel.address1}}</p>
                <p class="font-weight-bold">Contact : </p>
             <div *ngFor="let contact of {{hotel.contact}};let i=index">
                  <p>{{contact.contactNo}}</p>
                </div>
           
                <p class="font-weight-bold">Email : {{hotel.email}}</p>
                
              </div>
            </div>
          </div>

.ts code

export class TestcComponent implements OnInit {

  availableHotels: Array<any>;
  hotel: ReplaySubject<String> = new ReplaySubject();
  

  constructor(
    private contractService: ContractService
  ) { }

  ngOnInit(){
    this.contractService.findAllHotels().subscribe((data) => {
      console.log(data);
      this.availableHotels = data;
      data.forEach((item) => {
        this.hotel.next(item);
        
        });
 

});
}
}

How output is shown :


Hotel : Shangri-La
Colombo 10
Address : No 400,

Contact :

Email : shangrila@gmail.com

I'm new to angular and still trying to get familiar with things. Thank you in advance !


Solution

Change this

<div *ngFor="let contact of {{hotel.contact}};let i=index">
  <p>{{contact.contactNo}}</p>
</div>

to

<div *ngFor="let contact of hotel?.contact; let i=index;">
  <p>{{contact?.contactNo}}</p>
</div>


Answered By - Smokey Dawson
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 25, 2022

[FIXED] How to recursively find specific key in nested JSON?

 July 25, 2022     iteration, json, list-comprehension, python, recursion     No comments   

Issue

I'm trying to pull nested values from a json file. I want to print out each of the values for every "id" key. I think I'm close but can't figure out why the obj type changes from a dict to a list, and then why I'm unable to parse that list. Here is a link to the json I'm working with: http://hastebin.com/ratevimixa.tex

and here is my current code:

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import json

json_data = open('JubJubProductions.json', 'r+')
jdata = json.loads(json_data.read().decode("utf-8"))

def recursion(dict):

    for key, value in dict.items():

        if type(value) == type(dict):
            if key != "paging":
                for key, value in value.items():
                    if isinstance (value,list):
                        print key
                        # place where I need to enter list comprehension?
                if type(value) == type(dict):
                    if key == "id":
                        print " id found " + value
                    if key != "id":
                        print key + " 1st level"
                if key == "id":
                    print key
        else:
            if key == "id":
                print "id found " + value       
if __name__ == '__main__':
    recursion(jdata)

-------------------------------------------------------------------------------------------update

This is now what I'm working with and it'll return a single id value, but not all of them:

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import json

json_data = open('jubjubProductions', 'r+')
jdata = json.loads(json_data.read().decode("utf-8"))

def id_generator(d):
    for k, v in d.items():
        if k == "id":
            yield v
        elif isinstance(v, dict):
            for id_val in id_generator(v):
                yield id_val

if __name__ == '__main__':
    for _ in id_generator(jdata):
        print (_)

Solution

def id_generator(dict_var):
    for k, v in dict_var.items():
        if k == "id":
            yield v
        elif isinstance(v, dict):
            for id_val in id_generator(v):
                yield id_val

This will create an iterator which will yield every value on any level under key "id". Example usage (printing all of those values):

for _ in id_generator(some_json_dict):
    print(_)


Answered By - Filip Malczak
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 24, 2022

[FIXED] how to iterate over objects id value ? in vue js

 July 24, 2022     arrays, iteration, json, vue.js     No comments   

Issue

I have a data JSON file locally where I can get the data into a component and print the object value depending on the object array number starting from 0 and on ... how can I print it using the object's id value?

in resolution as an example id=321 I want to print that object.

here is my current working code printing by object array value:

<template>
  <div class="exespotbody">
    <center><h2> Stories Spotlight </h2></center><br>
  <div class="Fgrid">

 <!-- single news Block for data-->
<a
   v-bind:key="dataList[0].id"
   :href="`posts/${dataList[0].id}`"
   class="Gmodule"
   style="display:flex;text-decoration:none;color:#14a0fd;"
   >
   <div>
   <!-- <img  src="https://fintechapp.s3.us-east-2.amazonaws.com/y2qYjf8e2hp8z5yrgyfxF2NN?response-content-disposition=inline%3B%20filename%3D%22BoxLogo.png%22%3B%20filename%2A%3DUTF-8%27%27BoxLogo.png&response-content-type=image%2Fpng&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJG6DG75G7BXQ3XUA%2F20210115%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20210115T192217Z&X-Amz-Expires=518400&X-Amz-SignedHeaders=host&X-Amz-Signature=26b742c676a7fc0854c1efa0c81bf60e9239bc5068606262b3b1eab0f7a21245">
   -->
     <img :src="`{{ dataList[0].logo_url}}`">  </img>
     <h6> {{ dataList[0].title }} </h6>
     <!-- <p v-html="dataList[0].blog_entry"> </p> -->
     <hr>
     <p> {{ dataList[0].author.name }} </p>
     <p> {{ dataList[0].author.title}} </p>
    </div>
</a>
<!-- single news Block for data  END-->
  </div>

  </div>
</template>

<script>
import dataData from "@/data/data.json";
export default {
  name: 'StoriesSpotlight',
  data() {
    return {
      dataList: dataData,
    }
  }
}
</script>

the result on screen :

enter image description here

Here is a is Vue tools pic for data:

enter image description here

what I want to do is print the data of the object bind by the id of the object for example id=321 that would be my next step...


Solution

So you want to find an object by its id from an array, then you can use find() on dataList

dataList.find(item => item.id === 321).title
dataList.find(item => item.id === 321).author.name
dataList.find(item => item.id === 321).author.title


Answered By - Anurat Chapanond
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 9, 2022

[FIXED] What is the use of iter in python?

 July 09, 2022     iteration, keyword, python     No comments   

Issue

What is the use of using the iter function in python?

Instead of doing:

for i in range(8):
  print i

I could also use iter:

for iter in range(8):
  print iter

Solution

First of all: iter() normally is a function. Your code masks the function by using a local variable with the same name. You can do this with any built-in Python object.

In other words, you are not using the iter() function here. You are using a for loop variable that happens to use the same name. You could have called it dict and it would be no more about dictionaries than it is about Guido's choice of coffee. From the perspective of the for loop, there is no difference between your two examples.

You'd otherwise use the iter() function to produce an iterator type; an object that has a .next() method (.__next__() in Python 3).

The for loop does this for you, normally. When using an object that can produce an iterator, the for statement will use the C equivalent of calling iter() on it. You would only use iter() if you were doing other iterator-specific stuff with the object.



Answered By - Martijn Pieters
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the use of iter in python?

 July 09, 2022     iteration, keyword, python     No comments   

Issue

What is the use of using the iter function in python?

Instead of doing:

for i in range(8):
  print i

I could also use iter:

for iter in range(8):
  print iter

Solution

First of all: iter() normally is a function. Your code masks the function by using a local variable with the same name. You can do this with any built-in Python object.

In other words, you are not using the iter() function here. You are using a for loop variable that happens to use the same name. You could have called it dict and it would be no more about dictionaries than it is about Guido's choice of coffee. From the perspective of the for loop, there is no difference between your two examples.

You'd otherwise use the iter() function to produce an iterator type; an object that has a .next() method (.__next__() in Python 3).

The for loop does this for you, normally. When using an object that can produce an iterator, the for statement will use the C equivalent of calling iter() on it. You would only use iter() if you were doing other iterator-specific stuff with the object.



Answered By - Martijn Pieters
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 6, 2022

[FIXED] How to update pointers when pushed on to std::stack using iteration?

 July 06, 2022     binary-tree, c++, iteration, pass-by-reference, stack     No comments   

Issue

Here is the situation:

Given a pointer to the root of a binary search tree(of integers) root and an integer data, perform the rotate function (predefined) on all the ancestral nodes of the node containing data using iterative method. For simplicity, assume data exists and always occurs on the leaf nodes.

The rotate function passes the pointer by reference as follows:

struct Node
{
    Node *left;
    int data;
    Node *right;
};

void rotate(Node* &root); // performs some rotation on the root and reflects the change.

void search(Node* &root, int data)
{
    stack<Node*> s;
    while(root->data!=data)
    {
        s.push(root);
        if(data<root->data)
            root=root->left;
        else
            root=root->right;
    }

    while(!s.empty())
    {
        rotate(s.top()); // does not reflect changes to root
        s.pop();
    }
}

The iterative version requires the use of a stack. std::stack::push() function pushes the pointer by value. As a result, while popping the ancestral pointers, I would be reflecting changes in the stack instead.

What is the best work around for this situation?


Solution

This solves my problem.

void search(Node* &root, int data)
{   
    if(root->data==data)
        return;

    stack<Node**> s;
    while(root->data!=data)
    {
        if(data<root->data)
        {
            s.push(&root->left);
            root=root->left;
        }
        else
        {
            s.push(&root->right);
            root=root->right;
        }
    }
    s.pop(); // to avoid leaf
    while(!s.empty())
    {
        rotate(*s.top())
        s.pop();
    }
    rotate(root);
}


Answered By - DoubtExpert
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, May 13, 2022

[FIXED] How do I iteratively append to text?

 May 13, 2022     append, iteration, pandas, python, text     No comments   

Issue

I have a dataframe that needs to be appended upto page/9/ in python

df:

/soccer/england/premier-league-2020-2021/results/
/soccer/england/premier-league-2019-2020/results/
/soccer/england/premier-league-2018-2019/results/

For every row in df , I have to append page/#/, page/2/, page/3/, page/4/, etc upto page/9/ as below

How can I do it in python?

expected df:

/soccer/england/premier-league-2020-2021/results/#/
/soccer/england/premier-league-2020-2021/results/#/page/2/
/soccer/england/premier-league-2020-2021/results/#/page/3/
.
.
/soccer/england/premier-league-2020-2021/results/#/page/9/
/soccer/england/premier-league-2019-2020/results/#/
/soccer/england/premier-league-2019-2020/results/#/page/2/
/soccer/england/premier-league-2019-2020/results/#/page/3/
.
.
/soccer/england/premier-league-2019-2020/results/#/page/9/
/soccer/england/premier-league-2018-2019/results/#/
/soccer/england/premier-league-2018-2019/results/#/page/2/
/soccer/england/premier-league-2018-2019/results/#/page/3/
.
.
/soccer/england/premier-league-2018-2019/results/#/page/9/

Solution

Sample dataframe used by me:

df=pd.DataFrame({'col': {0: '/soccer/england/premier-league-2020-2021/results/',
  1: '/soccer/england/premier-league-2019-2020/results/',
  2: '/soccer/england/premier-league-2018-2019/results/',
  3: '/soccer/england/premier-league-2020-2021/results/',
  4: '/soccer/england/premier-league-2019-2020/results/',
  5: '/soccer/england/premier-league-2018-2019/results/',
  6: '/soccer/england/premier-league-2020-2021/results/',
  7: '/soccer/england/premier-league-2019-2020/results/',
  8: '/soccer/england/premier-league-2018-2019/results/',
  9: '/soccer/england/premier-league-2020-2021/results/',
  10: '/soccer/england/premier-league-2019-2020/results/',
  11: '/soccer/england/premier-league-2018-2019/results/'}})

You can try:

df['h']=df.index%9+1
#created a helper column
df['col']=df['col']+("#/page/"+df['h'].astype(str)+'/').mask(df['h'].eq(1),"#/")
#conditionally adding '"/#/page/pagenumber/"' and '#/'
df=df.drop('h',1)
#remove that helper column

Now If you print df you will get your desired output

Update:

IIUC you need 9 url for every unique url so:

out=pd.DataFrame(df['col'].unique(),columns=['col'])
#created a dataframe from the unique values of 'col' column
out=out.reindex(out.index.repeat(9)).reset_index(drop=True)
#repeated values of each row 9 times
out['h']=out.index%9+1
#created a helper column
out['col']=out['col']+("#/page/"+out['h'].astype(str)+'/').mask(out['h'].eq(1),"#/")
#conditionally adding '"/#/page/pagenumber/"' and '#/'
out=out.drop('h',1)
#remove that helper column

Now If you print out you will get your desired output



Answered By - Anurag Dabas
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, April 27, 2022

[FIXED] Why is it bad to use an iteration variable in a lambda expression

 April 27, 2022     c#, iteration, lambda, vb.net, warnings     No comments   

Issue

I was just writing some quick code and noticed this complier error

Using the iteration variable in a lambda expression may have unexpected results.
Instead, create a local variable within the loop and assign it the value of the iteration variable.

I know what it means and I can easily fix it, not a big deal.
But I was wondering why it is a bad idea to use a iteration variable in a lambda?
What problems can I cause later on?


Solution

Consider this code:

List<Action> actions = new List<Action>();

for (int i = 0; i < 10; i++)
{
    actions.Add(() => Console.WriteLine(i));
}

foreach (Action action in actions)
{
    action();
}

What would you expect this to print? The obvious answer is 0...9 - but actually it prints 10, ten times. It's because there's just one variable which is captured by all the delegates. It's this kind of behaviour which is unexpected.

EDIT: I've just seen that you're talking about VB.NET rather than C#. I believe VB.NET has even more complicated rules, due to the way variables maintain their values across iterations. This post by Jared Parsons gives some information about the kind of difficulties involved - although it's back from 2007, so the actual behaviour may have changed since then.



Answered By - Jon Skeet
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

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
All Comments
Atom
All Comments

Copyright © PHPFixing