logo
Tags down

shadow

Storing Specific Whole Numbers - Python


By : Lima
Date : October 18 2020, 08:10 AM
I hope this helps you . Use re (regex) to do this pattern finding stuff, and use input to get the text entered:
code :
import re
a=input('Enter your stuff: ')
s=re.sub('[a-zA-Z^]','',a)
print([int('-'+i[0]) if s[s.index(i)-2]=='-' else int(i[0]) for i in re.split(' [+|-] ',s)])
Enter your stuff: 2x^3 + 5x^2 - 8x + 3
[2, 5, -8, 3]


Share : facebook icon twitter icon

Storing big numbers over 9,000 digits in Python


By : Karthik Eswaran
Date : March 29 2020, 07:55 AM
it should still fix some issue Python can store arbitrarily long integers using the long type and even lets you specify long literals by appending an L to them (e.g. 0L is a long zero, as opposed to just 0 which is an int). Even better, it automatically "promotes" numbers from ints to longs when the result of a calculation is too large to be represented by an int. long is a full-fledged numeric type and is compatible with all Python numeric operations.
If you need more than integers, then you want the decimal module, which features a Decimal type that provides real numbers of arbitrary size and precision, without the issues inherent to binary floating-point representations.

Storing numbers as (x, y) cordinates from a file at a specific point


By : RaJaG
Date : March 29 2020, 07:55 AM
Any of those help sample for "Storing numbers as (x, y) cordinates from a file" (It is better not to fix the reading position)
code :
#include <stdio.h>

typedef struct point {
    int x, y;
} Point;

int readPoint(FILE *fp, Point *p);
int readInt(FILE *fp, int *n);

int main(void){
    FILE *fp = fopen("instance10_001.txt", "r");
    Point p;
    int MAX_X, MAX_Y;

    readPoint(fp, &p);
    MAX_X = p.x;
    MAX_Y = p.y;
    printf("MAX_X:%d, MAX_Y:%d\n", MAX_X, MAX_Y);

    int NUM_PT;
    readInt(fp, &NUM_PT);
    printf("NUM_PT:%d\n", NUM_PT);

    Point arr[NUM_PT];
    for(int i = 0; i < NUM_PT; ++i){
        readPoint(fp, &arr[i]);
        printf("Point(%d, %d)\n", arr[i].x, arr[i].y);
    }
    fclose(fp);
}

int readLine(FILE *fp, char *buff, int buff_size){
    while(fgets(buff, buff_size, fp)){
        if(*buff == '#' || *buff == '\n')
            continue;
        return 1;
    }
    return 0;
}

#define LINE_MAX 128
int readPoint(FILE *fp, Point *p){
    char buff[LINE_MAX];
    if(readLine(fp, buff, sizeof buff)){
        return 2 == sscanf(buff, "%d %d", &p->x, &p->y);
    }
    return 0;
}
int readInt(FILE *fp, int *n){
    char buff[LINE_MAX];
    if(readLine(fp, buff, sizeof buff)){
        return 1 == sscanf(buff, "%d", n);
    }
    return 0;
}

Capturing numbers in a string and storing in data frame in Python


By : Ibrahim Kuşak
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further if you are using pandas 0.18.0+, you can try extractall() to retrieve all atom+count combos and then use pivot() or unstack() to get atoms in the columns. After that reindex() and fillna() to get missing atoms: see below example (tested on Pandas 0.23.4):
UPDATE: On Pandas version 0.24+, the pd.pivot() function yield KeyError and some change on this function made it not compatible with version 0.23.4. Use unstack() instead in the new code:
code :
df = pd.DataFrame([('C55H85N17O25S4',),('C23H65',),(None,), (None,), ('C22H16ClN3OS2',)
         , ('C37H42Cl2N2O6',), ('C21H30BrNO4',), ('C11H13ClN2',), ('C34H53NaO8',), ('A0',)
    ],columns=['molecular_formula'])
#  molecular_formula
#0    C55H85N17O25S4
#1            C23H65
#2              None
#3              None
#4     C22H16ClN3OS2
#5     C37H42Cl2N2O6
#6       C21H30BrNO4
#7        C11H13ClN2
#8        C34H53NaO8
#9                A0

# list of concerned atoms 
atoms = ['C', 'H', 'O', 'N', 'Cl','S','Br']

# regeex pattern
atom_ptn = r'(?P<atom>' + r'|'.join(atoms) + r')(?P<cnt>\d+)'
print(atom_ptn)
#(?P<atom>C|H|O|N|Cl|S|Br)(?P<cnt>\d+)

# extract the combo of atom vs number and pivot them into desired table format 
df1 = df.molecular_formula.str.extractall(atom_ptn) \
        .reset_index(level=1, drop=True) \
        .set_index('atom', append=True) \
        .unstack(1)

# remove the level-0 from the column indexing
df1.columns = [ c[1] for c in df1.columns ]

# reindex df1 and join the result with the original df, then fillna() 
df.join(df1.reindex(columns=atoms)).fillna({c:0 for c in atoms}, downcast='infer')
#  molecular_formula   C   H   O   N Cl  S  Br
#0    C55H85N17O25S4  55  85  25  17  0  4   0
#1            C23H65  23  65   0   0  0  0   0
#2              None   0   0   0   0  0  0   0
#3              None   0   0   0   0  0  0   0
#4     C22H16ClN3OS2  22  16   0   3  0  2   0
#5     C37H42Cl2N2O6  37  42   6   2  2  0   0
#6       C21H30BrNO4  21  30   4   0  0  0   0
#7        C11H13ClN2  11  13   0   2  0  0   0
#8        C34H53NaO8  34  53   8   0  0  0   0
#9                A0   0   0   0   0  0  0   0
df.join(df.molecular_formula.str.extractall(atom_ptn) 
          .droplevel(1)
          .set_index('atom', append=True) 
          .unstack(1) 
          .droplevel(0, axis=1) 
          .reindex(columns=atoms) 
   ).fillna({c:0 for c in atoms}, downcast='infer')
# sort the list of atoms based on their length
atoms_sorted = [ i[0] for i in sorted([(k, len(k)) for k in atoms], key=lambda x: -x[1]) ]

# the new pattern based on list of atoms_sorted and \d* on cnt
atom_ptn = r'(?P<atom>' + r'|'.join(atoms_sorted) + r')(?P<cnt>\d*)'
print(atom_ptn)
#(?P<atom>Cl|Br|C|H|O|N|S)(?P<cnt>\d*)
df.join(df.molecular_formula.str.extractall(atom_ptn)
          .fillna(1)
          .droplevel(1)
          .set_index('atom', append=True)
          .unstack(1)
          .droplevel(0, axis=1)
          .reindex(columns=atoms)
   ).fillna({c:0 for c in atoms}, downcast='infer')

SQL for storing numbers from cold to hot for specific range?


By : pplove80
Date : March 29 2020, 07:55 AM
may help you . With a recursive CTE create the dataset 1-37 and then UNION ALL to create a dataset with all the numbers in the table.
Join the 2 datasets and group by the number and aggregate:
code :
with cte(n) as (
  select 1 union all select (cte.n + 1) n from cte where cte.n < 37
) 

select 
  cte.n, count(t.number) counter
from cte left join (
  select date, val1 number from tablename union all
  select date, val2 from tablename union all
  select date, val3 from tablename union all
  select date, val4 from tablename union all
  select date, val5 from tablename
) t on t.number = cte.n and t.date between '2019-05-01' and '2019-05-31'
group by cte.n
order by counter, cte.n

Storing Multiple Numbers in SharedPreferences without having specific keys


By : crunchRP
Date : March 29 2020, 07:55 AM
Hope this helps You can't store different value for same key, so better you should use Sqlite.
Related Posts Related Posts :
  • Get mongod rs.status() results from a python script
  • ImportError: C extension: No module named 'parsing' not built
  • python pandas update column values related to previous updated row during iteration over it
  • 3 nested loops: Optimizing a simple simulation for speed
  • Assign subset of values to pandas dataframe with MultiIndex
  • How to group two sets of buttons on each top corner of the screen using Tkinter?
  • django login using class based for custom user
  • MRJob sort reducer output
  • Python Pandas Counts using rolling time window
  • Getting or editing a string from a column in a csv file with pandas
  • Python - Delete row in matrix/array if row contains
  • Using dicom Images with OpenCV in Python
  • Odoo ghost record
  • Creating and assigning multiple variables in a tkinter application
  • Graph dictionary
  • No changes to original dataframe after applying loop
  • AUC of Random forest model is lower after tuning parameters using hypergrid search and CV with 10 folds
  • Python: Reading multiple CSV files, and assigning each to a different variable
  • How to identify empty rectangle using OpenCV
  • How to iterate multilevel dataframe in python
  • How to limit the contour plot with a line plot?
  • Why subclassing a str or int behaves differently from subclising a list or dict?
  • Python decode with translation table
  • i need to click unordered links in the below URL using selenium, python
  • How to join pandas dataframe with itself?
  • How to apply a color cast to a video frame in OpenCV Python?
  • Is there any existing library for median filtering with kernel size greater then 5 using OpenCL acceleration in python?
  • Changing the color of points in scatter plot for different dummy values
  • Calculate center for each polygon in a list efficiently
  • Loading modules in the same Python package
  • replacing pixels in an imagewith pixels from another image python
  • Suggestion on picking the best options of two lists (minimum and maximum )python
  • Resetting Index in a Dataframe drops the Indexed column by 1 row
  • Convert number which are str from readlines to digits - python
  • Unable to authenitcate with python minds api
  • Print variables from a query in python
  • Ipython does not see the installed library
  • Javascript-like array-method chaining in Python?
  • PyQT: Get contents CustFormWidgetIem inside QListWidgetItem
  • Bottle server: HTTPResponse vs bottle.response
  • pytorch vgg model test on one image
  • Runtime scope and `main` symbol is different inside or outside a function
  • Use anaconda in pycharm (Import libraries error, updating anaconda and virtual environment)
  • how to get the sum of a CSV column list to print
  • Python plot drop lines with repeating value in column
  • receive binary file from POST request with BaseHTTPRequestHandler
  • D-Bus - 'ServiceUnknown' exception encountered while calling a remote procedure
  • Pandas .min() method doesn't seem fastest
  • Pandas: How to reference columns of structure: ('Name', n) ('Name', n+1)
  • Read a text file and remove all characters except alphabets & spaces in Python
  • Compute all powerset intersections of two lists
  • Applying literal_eval on string of lists of POS tags gives ValueError
  • Modelling a logic puzzle
  • What is the meaning of Copy_X in sklearn linear models
  • selenium.common.exceptions.ElementNotInteractableException: Message: Element is not displayed
  • pydev debugger does not stop in breakpoint
  • Python windows path regex
  • Flask and selenium-hub are not communicating when dockerised
  • How to use groupby on a single column and perform comparisons for multiple columns in Pandas?
  • Locate a python script without absolute path
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org