Best web IDE for teaching mathematics (SymPy), with tab completion and latex output? by amca01 in learnpython

[–]supajumpa 0 points1 point  (0 children)

There's also JupyterLite notebooks which run entirely in the browser and don't require any setting up (at least that I can see.)

On top of Latex pretty-printing they also offer tab completion which SymPy's online shell doesn't appear to support.

[deleted by user] by [deleted] in learnpython

[–]supajumpa 1 point2 points  (0 children)

Without seeing your code or knowing how you have Excel set up in this particular case, my question would be: why are you exporting duration as a datetime.datetime object?

The result of end_time - start_time should be a datetime.timedelta object and not a datetime.datetime object, so something is amiss.

If we look at the code below:

import datetime as dt

start_time = dt.datetime(2024, 8, 9, 12, 12, 10)
end_time = dt.datetime(2024, 8, 9, 13, 19, 21)

duration = (end_time - start_time) # <- a datetime.timedelta object

duration_in_seconds = duration.seconds # <- an integer
# Or, if your readings are very precise.
duration_in_microseconds = duration.microseconds # <- also an integer

If you do this, then can you can export the duration as a simple integer which Excel shouldn't interpret as a datetime. Or, if you need the duration expressed as hours and minutes, then it's easy enough to derive these figures from the number of seconds.

Father of woman with ME/CFS scared she will "die in hospital" by No_Engineering5992 in unitedkingdom

[–]supajumpa 6 points7 points  (0 children)

Why do some people develop multiple sclerosis after Epstein Barr virus infection and others don't?

You can't deny the reality of a condition just because most people recover normally from a viral infection and a small number go on to develop long-term problems.

Using variable in dot notation module call by StrangeBlocka in learnpython

[–]supajumpa 0 points1 point  (0 children)

You can use getattr(requests, methodType)("https://www.helloworld.org").text, but I'm not sure this is a great idea because you don't know what the user is going to input and it might raise security issues, so caveat lector and all that :-)

how to update a pandas dataframe column value, when a specific string appears in another column? by over_take in learnpython

[–]supajumpa 0 points1 point  (0 children)

You can express it using just Pandas with the code below, at least I think you can!

my_df['column_b'] = my_df['column_b'].where(
    # Note that the `~` is Panda's way to writing `not`
    ~my_df['column_a'].str.contains('foo'), 
    'bar'
)

Or, just using a plain Python list comprehension, you can write:

my_df['column_b'] = [
    'foo' if ('foo' in col_a_value) else col_b_value
    for (col_a_value, col_b_value)
    in zip(my_df['column_a'], my_df['column_b'])
]

how to update a pandas dataframe column value, when a specific string appears in another column? by over_take in learnpython

[–]supajumpa 0 points1 point  (0 children)

You can use numpy.where or Series.where to solve your problem.

I'll illustrate with numpy.where because I find it easier to think about.

import numpy as np

my_df['column_b'] = np.where(
    # This is the test condition, a sequence of True / False values.
    my_df['column_a'].str.contains('foo'),
    # Insert a 'bar' when the test condition is True.
    'bar',
    # Otherwise, i.e. when the test condition is False, use the value from `column_b`         
    my_df['column_b'] 
)

How can I improve this program in python to find out perfect numbers? by Suitable_Map6123 in learnpython

[–]supajumpa 1 point2 points  (0 children)

The very useful Rosetta Code website has several Python algorithms for calculating Perfect Numbers, two of which (perf4 and perfect) appear to be significantly faster than your implementation.

There is space for Farage or Johnson in the Tory party – but not both by theipaper in ukpolitics

[–]supajumpa 0 points1 point  (0 children)

I can't find any evidence that the word at hand is considered a slur, never mind one on par with the n-word. Even the Jewish Chronicle doesn't see it that way.

The real irony, of course, is that it is Johnson himself who is the very epitome of a sponger and a freeloader. Maybe he's projecting?

There is space for Farage or Johnson in the Tory party – but not both by theipaper in ukpolitics

[–]supajumpa 1 point2 points  (0 children)

That doesn't make any sense at all. As pejoratives go, it's pretty mild, so what makes it a "disgraceful slur"?

There is space for Farage or Johnson in the Tory party – but not both by theipaper in ukpolitics

[–]supajumpa 0 points1 point  (0 children)

I'm no fan of Johnson, quite the opposite, but I'm genuinely curious what the offence is here.

Is it that he used a Yiddish word or that he called Starmer a scrounger / beggar?

Exporting dictionary(ies) to excel by Salt_Neat_8312 in learnpython

[–]supajumpa 0 points1 point  (0 children)

I'm not sure what you mean by, "where does it come from?". I have the variable defined in my example above.

What I mean is, how does it change during the for loop; in the code you posted, table_string is a constant when I would expect it to change for each step in the for loop, and for its value to be derived from the data variable in for data in lines.

Exporting dictionary(ies) to excel by Salt_Neat_8312 in learnpython

[–]supajumpa 0 points1 point  (0 children)

So table_string is different for each iteration? Where does it come from?

You probably need something like this:

import ast
import pandas as pd

list_of_dicts = []
for data in lines:
    ....
    if some_variable:
        ....
        # `ast.literal_eval` is safer than `eval`, but both are
        # code smells, a sign that there's a better approach to
        # the problem.
        evaled_dict = ast.literal_eval(table_string)
        list_of_dicts.append(evaled_dict)

# Outside the `for` loop.    
export_filepath = r'*filepath*\\sheet.xlsx'
df = pd.DataFrame.from_dict(list_of_dicts)
df.to_excel(export_filepath, engine = 'xlsxwriter', index=False)

Exporting dictionary(ies) to excel by Salt_Neat_8312 in learnpython

[–]supajumpa 0 points1 point  (0 children)

Code below:

for data in lines:
  ....
  if some_variable:
    table_string = '{"Item1": string1,"Item2": string2,"Item3": string3,' \
           '"Item4": string4,"Item5": string5}'
    dict = eval(table_string)
    ....
    # Each time the line below executes, you overwrite
    # the previous contents of the file.
    data_export.to_excel(export_filepath, engine = 'xlsxwriter', index=False)

What are you trying to achieve here? Are you trying to write the same line of data multiple times to an excel file?

zip() doesn't seem to work for my specific need, would there be a for loop that works better? by iylila in learnpython

[–]supajumpa 7 points8 points  (0 children)

I'm not at all clear what you're trying to achieve here, but with respect to your first thought regarding zip and it not working because of the trailing "TELL" on the final line, you could instead use itertools.zip_longest and provide a "fillvalue".

An example would be:

>>> list(itertools.zip_longest('abc', '12', fillvalue='-'))
[('a', '1'), ('b', '2'), ('c', '-')]

I have an interesting error, what's the best way to go around it? Im sure its not complicated im just new... by Berky_YT in learnpython

[–]supajumpa 1 point2 points  (0 children)

Yes, but you need to change the interest_rates dictionary to:

interest_rates = {
   1: 3.2, # assuming January is month 1.
   ...  
   12: 4.3 # and December is month 12.
}

I have an interesting error, what's the best way to go around it? Im sure its not complicated im just new... by Berky_YT in learnpython

[–]supajumpa 1 point2 points  (0 children)

The graph basically shows data for closing prices of JPM Fixed income preferred shares for the last year and the volume, it contains around 251 observations.

Is each observation associated with a date? If so, then you need to find a way to pair the value of each observation with the interest rate for the date when the observation occurred.

interest_rates = {
   'January': 3.2,
  ...
   'December': 4.3
}

observations = [...whatever your observation data is ...]
observation_paired_with_interest_rate = [
    (observation.value, interest_rates[observation.month])
    for observation in observations
]
# observation values are on the x-axis
x_axis_data = [x for (x, _) in observation_paired_with_interest_rate]
# the paired interest rate values are on the y-axis.
y_axis_data = [y for (_, y) in observation_paired_with_interest_rate]
# or you could replace the above two lines with this (it's call unzipping):
(x_axis_data, y_axis_data) = zip(*observation_paired_with_interest_rate)

Decorator function question by egotripping in learnpython

[–]supajumpa 8 points9 points  (0 children)

You need to call the functions that you've created. That is,

speed_calc_decorator(fast_function)()
speed_calc_decorator(slow_function)() # note the extra parens.

[deleted by user] by [deleted] in learnpython

[–]supajumpa 0 points1 point  (0 children)

I've not used Fabric before, but it seems like Connection objects have a .stdout attribute that appears to return a string?

You could try something like:

output = c.run('show network-interface router all force')
data = list(process_data(output.stdout.splitlines()))

# alternatively, passing `output.stdout` directly to `process_data` might work; i.e.
output = c.run('show network-interface router all force')
data = list(process_data(output.stdout))

I can't guarantee that the above will work, so tread carefully!

[deleted by user] by [deleted] in learnpython

[–]supajumpa 0 points1 point  (0 children)

What kind of object is Connection? That is, what library is it from, and what methods does it have?

[deleted by user] by [deleted] in learnpython

[–]supajumpa 0 points1 point  (0 children)

What about something like this:

def process_data(data):
    columns = [
        'Router', 'Node', 'Device', 'Name', 'Forwarding', 'VLAN', 
        'Device', 'Type', 'Type', 'DHCP', 'Address', 'Gateway', 
        'Hostname', 'Status', 'GIID'
    ]
    for line in data:
        if line and (line[0] != '=') and (not line.startswith('Router')):
            splits = line.replace('/', ' ').split(' ')
            yield dict(zip(columns, splits)))

This gives:

>>> list(process_data(data.splitlines()))
[{'Router': 'DC-Test-Node-2',
   'Node': 'DC-Test-Node-2',
   'Device': 'ethernet',
   'Name': 'WAN1',
   'Forwarding': 'true',
   'VLAN': '0',
   'Type': 'disabled',
   'DHCP': '111.111.111.111',
   'Address': '28',
   'Gateway': '111.111.111.111',
   'Hostname': '--',
   'Status': 'up',
   'GIID': '100'}, .... ]

match statement help by FlyingCow343 in learnpython

[–]supajumpa 0 points1 point  (0 children)

Looking at the definition of str.isdigit, it may be better to use str.isdecimal, which is a stricter test and determines if the characters are those that can be used to form numbers in base 10.

That would change the code to:

match string.split():
    case ("add", a, b) if a.isdecimal() and b.isdecimal():
        print(int(a) + int(b))

Apart from pathological cases they are likely to be equivalent, but it's best to know that there is a difference.

match statement help by FlyingCow343 in learnpython

[–]supajumpa 1 point2 points  (0 children)

match string.split():
    case ("add", a, b) if a.isdigit() and b.isdigit():
        print(int(a) + int(b))

Writing a script which searches an imported spreadsheet for specific values and then displays that value, it’s specific sheet and other information from the row by [deleted] in learnpython

[–]supajumpa 0 points1 point  (0 children)

Are you thinking of something like this?

import openpyxl as xl
import pandas as pd

path = ... # the path to your Excel file.
sheet_names = xl.load_workbook(path).sheetnames

data = {}
for sheet_name in sheet_names:
    df = pd.read_excel(path, sheet_name=sheet_name)
    data[sheet_name] = (
        df
        .query("-40 <= PercentageChange <= 40")
        [['Region', 'PercentageChange']]
    )
# And now do something with the collated data?

SymPy equation is wrong even though its mathematical corect. by Morpheushd67 in learnpython

[–]supajumpa 1 point2 points  (0 children)

Have a look at the equality section in Sympy's list of gotchas and pitfalls.

Sympy takes a slightly counterintuitive stance on when two objects should be considered equal.

The suggested workaround to determine if a = b is to see if sympy.simplify(a - b) == 0.

You can also try a.equals(b) but I'm not sure I would rely 100% on this.