#algos-and-data-structs

1 messages · Page 119 of 1

lusty lantern
#

lemon_unamused U didn't what was the task was
Also it wasn't index//index

distant dock
#

so ur trying to tell me available[name] and amount are not the index but the index?

lusty lantern
#

Those value were only test cases and not permanent

distant dock
#

then if its for test cases, u should ought to change them to integers like the problem

#

let me take another look give me a few moments to read and get some coffee

lusty lantern
#

I didn't want to waste time on test cases because they were not the point of my question

distant dock
#

what im confused about is, how do you know how much makes one cake

distant dock
#

nvm im stupid lul

#

sorry let me injest coffee

distant dock
#
def cakes4():
    recipe = {"apples": [3], "flour": [300], "sugar": [150], "milk": [100], "oil": [100]}
    available = {"sugar": [500], "flour": [2000], "milk": [2000]}
    
    
    for index, keys in enumerate(recipe):
        for index2,keys2 in enumerate(available):
            KEYS1 = recipe[keys]
            KEYS2 = available[keys2]

        for stuff, stuff2 in zip(KEYS1, KEYS2):
            calc = stuff//stuff2
            return calc
        else:
            if stuff > stuff2:
                calc = stuff//stuff2
                return calc
``` im getting the right answer but its giving me a type error for the interpretor on the website but in my IDE it runs just fine
#

yes its sloppy

#

but ehh

#

ahh its because im using a list

#

eitherway that should be faster than ur code and it still gives the right answer, now what i want u to do is figure out why it wont run with a list instantiated

#

2.842704500000764, 2.159629199999472, 1.8395526999993308, 1.0164244000006875, last one is mine

#

hmmmm, i dont watch tutorials anymore, back then when I did that I was trying to understand real basic stuff like list comp and dictionaries which i still need to become more versed in. I personally like to read tutorials/documentation/sourcecode examples. Make print statements within the code to see what variables mean, what is actually going on in that code is what u gotta do.

#

algorithms in my opinion (just scratching in the surface to them myself) is really just learning to traverse and manipulate arrays

#

think about it like ur trying to sort a list from least to greatest, what algo or what condition or even conditions would that consist of?

#

tbh with u, that problem above is the first algo problem i solved

#

first one i ever worked on

fiery cosmos
fiery cosmos
#

so you just, decided to

#

solve a problem and did it? 🤔

distant dock
#

yes

#

yeah i guess u could say i did, didnt think of it like that but ye

#

not like i solved quantum entanglement though

dapper sapphire
#

Is the space and time complexity for .join() method O(n)?

#
llist = ["This", "is", "a", "test"]
string = " ".join(llist)

print(string)
>> "This is a test"
fiery cosmos
#

why is ds algo so hard for me 🥲

#

i can't understand a thing

#

can anyone suggest me any books

craggy wagon
#

@fiery cosmos please lemme know if u find one 😆

craggy wagon
#

please?

fiery cosmos
#

grokking algorithm

craggy wagon
#

Oh

fiery cosmos
#

i have been told its a good book

craggy wagon
#

I did happened to come across that

fiery cosmos
craggy wagon
#

No I just looked at first few chapters, It's fine ig

fiery cosmos
#

oh okie

craggy wagon
#

What I'm thinking of is to somehow learn problem solving along with ds algo

fiery cosmos
#

yes same

#

if you find one please tell me also

#

🥺

craggy wagon
#

I just started, so not much review I can provide but it looks like a game ok_handbutflipped

fiery cosmos
craggy wagon
fiery cosmos
#

yup

#

it looks good

#

nice ui they have

craggy wagon
#

@dapper sapphire Space is definitely O(n) so is time, even I had feeling of quadratic. But checking stackover flow happened to be O(n)
And I think how it's done is you find the cumulative sum of length of all the sub-strings, then allocate required space, then you start copying! 😅

#

@fiery cosmos plus creative solutions by others 🎉

dapper sapphire
#

Yeah thanks! I am not sure how it's implemented. But if I were to implement something like this I guess I would use bytearray and pass in the size / length and then copy each element over of each substring index by index since bytearray is mutable.

valid cedar
#

can sombody suggest me a good book or any other reference for DSA.I have just started competitive programming any kind of help would be appreciated .thank you!

halcyon plankBOT
#

Objects/stringlib/join.h line 57

/* Here is the general case.  Do a pre-pass to figure out the total```
fervent saddle
#

This says you’re right

dapper sapphire
#

Oh wow thanks. What does "bytes-like" mean, when it says, and see whether all arguments are * bytes-like?

empty swift
#

Hey guys

#

I want to say that jesus loves you❤️ ✝️ ❤️🙌

green seal
#

Hey guys for algorithm and data structure kindly visit tutorialspoint for better explaination on algorithm and data structures 🙏🏽🙏🏽

fiery cosmos
#

DSA proselytizers BlobSweat

craggy wagon
#

@fervent saddle thanks for the insight
I've always heard bad about goto but I see a lot of these here!

strange coral
#

maybe someone has a idea to extract corners of a jigsaw puzzle piece... i tried almost everything... hough lines... polar coords with angle velocity.... contour defects...

fiery cosmos
rocky moss
#

I wonder how his IDE will look in HoloLens

chilly crane
#

hey guys, what kind of file you would propose to hold some info and by one click can load it to the entry boxes ?

#

i mean for easy writing and reading

craggy wagon
#

@chilly crane r u creating such file or looking for‽

chilly crane
#

i want load from file and save to file but wonder which would be easy to manipulate

fiery cosmos
#

can someone help pls?

lament oriole
#

i want to "reverse search" a dictionary, but id prefer to avoid for loops.

im dynamically generating lists of unknown length, and all the items in a given list should correspond to a particular string.
i can easily construct a dictionary as {"string":[generated list here]}, but that would make searching for the key via an item in the list slow.
i can also generate {"item":"string"} for each of the items, but again thats slow.

is there a better datatype for having multiple keys go to a single value without having to generate a dictionary entry for every key? or is there a method for searching a dictionary this way that doesnt need loops?

craggy wagon
#

@lament oriole did you try sets in place of [generated list here], I believe even sets have O(1) time complexity

lament oriole
#

i have cast the list to sets (its a library generating the lists) but still have to iterate over the dictionary when searching, making it O(n) at worst

craggy wagon
#

You looking for O(1) 🔥

lament oriole
#

every day

craggy wagon
#

@lament oriole
I wonder how could this be slow:
i can also generate {"item":"string"} for each of the items, but again thats slow.

lament oriole
main flower
#

Well, you won't achieve O(1) If you also need to search that list

#

Also

#

also wdym by "search"

#

Do u just want to know If there is an element in that list

#

Or u want index or sth

craggy wagon
#

btw what that theList contains

main flower
#

Also, what are those "items" in a list? Integers, strings or sth else?

#

What I'd do is

#

For each string I'd have a BST (or even Red-Black or AVL tree)

#

This would make searching O(logn) which is not that bad

lament oriole
#

the list is a list of strings, each of those strings is unique across both its list and all other lists, so casting to set isnt a bad idea.
for searching, i want to have some way of addressing the dict/whatever type by an item in a list, and it returns to me the key that its under.
ideally, theres a way to generate and index without iteration.

i can do generation without iteration;
{"string": myList} but i then have to iterate twice when searching, once for the dict and once for the list.
i can do searching without iteration, but then the list generation looks like

mydict = {}
for l in all_lists:
  mydict.update({item: "string" for item in l})

which uses 2 loops.

i just wanna do this without loops, and faster than loops

lament oriole
lament oriole
#

decided to bite the bullet on generation to ensure faster searching, just used this as it's fast enough at the scale im using it

reversedDict = {
        item: "string" for item in theList
    } | {
        item: "string" for item in theList
    }
echo goblet
#

you think i could build a discreet system for breaking things apart, based on the heat equation?

#

like instead of heat its would be stress and if it hit a certian amount the lattice connection would snap

#

also

#

!rule 8

halcyon plankBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

mint hedge
#

im sorry

loud trail
#

but use tuples instead of lists 🙂

lament oriole
# loud trail <@!773137363395674133> https://pypi.org/project/bidict/
>>> from bidict import bidict
>>> element_by_symbol = bidict({'H': 'hydrogen'})
>>> element_by_symbol['H']
'hydrogen'
>>> element_by_symbol.inverse['hydrogen']
'H'

would

>>> element_by_symbol = bidict({'H': {'hydrogen'}}) # <- changed to singleton set
>>> element_by_symbol.inverse['hydrogen']

still work?

loud trail
#

i doubt it, also sets aren't hashable, you need frozenset

lament oriole
#

oh right, shouldve made that a tuple really

loud trail
#
element_by_symbol = bidict({'H': ('hydrogen',)})
element_by_symbol.inverse[('hydrogen',)]

this should work

#

for individual list elements, yeah you might need to build 2 dicts or use a fancier data structure

lament oriole
#

element_by_symbol.inverse[('hydrogen',)] would this singleton tuple work if there were multiple items in the stored tuple?

loud trail
#

no

lament oriole
#

dang

#

still though, this seems like a useful library. ill make note of it. thank you

loud trail
#

red-black and AVL trees are binary search trees that can be rebalanced (or are self-balancing) to provide better guarantees about time complexity when searching

#
things = {
  'H': ('hydrogen', 'helium'),
  'C': ('carbon', 'cobalt'),
}

things_rev = {
    val: key
    for key, vals in things.items()
    for val in vals
}

query = 'H'
lookup = things.get(query, things_rev.get(query, None))

this could work if you don't know if you're looking for a key or value, and if you know that a value can only ever appear under one key

#

slow to construct + double storage, but still fast to do lookups

#
things = {
  'H': ('hydrogen', 'helium'),
  'C': ('carbon', 'cobalt'),
  '?': ('cobalt', 'hydrogen'),
}

from collections import defaultdict
things_rev = defaultdict(list)
for key, vals in things.items():
    for val in vals:
        things_rev[key].append(val)

this works in the more general setting where you might need the reverse lookup to be multi-valued

#
things = {
  'H': ('hydrogen', 'helium'),
  'C': ('carbon', 'cobalt'),
  '?': ('cobalt', 'hydrogen'),
}

from multidict import MultiDict
things_rev = MultiDict()
for key, vals in things.items():
    for val in vals:
        things_rev.add(key, val)
indigo berry
#

hi guys how can i write base64 in a text file using pyhton

#

i want to clear the file before i write it too

loud trail
#

@indigo berry just use with open in "write" mode

indigo berry
#

thanks

craggy wagon
#

@fiery cosmos I don't think it's due to recursive function, by default maximum-recursion-depth is set to 1000, if that's not modified then it should yell error at you. I believe the problem is somewhere else. Correct if I'm wrong!

strange terrace
#

umm hello can someone teach the binary search

#

im just learn the python basic and i want to know more about binary search

craggy wagon
#

@strange terrace know what sorting is?

strange terrace
#

no i dont

#

what is sorting?

craggy wagon
#

gotta learn that first

strange terrace
#

oh k thanks

#

can i private chat with you so i can talk more about binary

#

just send a request friend

fervent saddle
#

You must know what sorting is

#

Sorting as in putting things in order from least-to-greatest or greatest-to-least

#

Binary search is checking the middle spot between all the possible values that could have the value you’re looking for

#

It’s like if you have to guess a number between 1 and 100, and first you guess 50, then 25, then 12 or 13, etc

winged hamlet
#

Hello. I needed guidance from the experts. Is there a way to compare two numbers in the list using xor without using brute force coding?

#

seq = [1, 2, 3, 3, 4, 4, 4, 10, 10, 10]
def algorithm():
result = 0
for i in range(len(seq)):
for j in range(i+1, len(seq)):
findNo1 = seq[i]
findNo2 = seq[j]

        if findNo1 ^ findNo2 == 0:
            print('X={}, Y={}'.format(findNo1, findNo2))
            result += findNo1 ^ findNo2 == 0
print('Total Matches is {}'.format(result))

algorithm()

#

Is there a better solution to show the same output print without using brute force?

runic tinsel
#

no

#

that's it

#

you can only do better without xor

winged hamlet
#

No offense. The project want me to use xor without using brute force

runic tinsel
#

can you show the task

#

maybe it's about something else

winged hamlet
#

Given a sequence of positive integers, SEQ, sorted in ascending order, design and
implement an algorithm with Python to determine if there exist two integers X and Y in
the sorted sequence such that X XOR Y = 0

runic tinsel
#

that doesn't say you need to use xor

#

or that you need to count matches

#

oh, it's about adding the end points probably

#

no that's not it

winged hamlet
#

The project wanted me to use xor? Since using for loop twice is getting the numbers in list is treated as brute force.

runic tinsel
#

like, I would never ever think that means I need to use xor

#

it's useless here

#

I would add the length to the first number

#

(1+10-1) = 10

#

that's the minimum the end number can be if there are no repeats

#

you can look at the end number, if it was 9, you immediately know there's a repeat

#

and then you can reevaluate that as you scan the list

#

and what about counting matches?

winged hamlet
#

Yes it needs me to use xor

#

Yes xor is necessary

runic tinsel
#

proof?

winged hamlet
#

Counting matches is there but need to have better solution

#

A brute-force algorithm compares all possible pairs in the sorted sequence and
check if they Exclusive OR to 0. However, using this approach will only give you a
minimal points.

runic tinsel
#

what about counting matches

winged hamlet
#

if counting matches using xor operator then its fine

runic tinsel
#

alright

winged hamlet
#

Thank You Experts. Sorry I'm a newbie.

winged hamlet
#

Hmm. No other solution

#

?

strange terrace
#

can someone check my code

#

i need experts

#

i just learn backtracking and this is the code

halcyon plankBOT
#

Hey @strange terrace!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

strange terrace
#

from typing import List, Optional, Tuple

Matrix = List[List[int]]

initial_grid: Matrix = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]

no_solution: Matrix = [
[5, 0, 6, 5, 0, 8, 4, 0, 3],
[5, 2, 0, 0, 0, 0, 0, 0, 2],
[1, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]

def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
return False

for i in range(3):
    for j in range(3):
        if grid[(row - row % 3) + i][(column - column % 3) + j] == n:
            return False

return True

def is_completed(grid: Matrix) -> bool:
return all(all(cell != 0 for cell in row) for row in grid)

def find_empty_location(grid: Matrix) -> Optional[Tuple[int, int]]:
for i in range(9):
for j in range(9):
if grid[i][j] == 0:
return i, j
return None

def sudoku(grid: Matrix) -> Optional[Matrix]:

if is_completed(grid):
    return grid

location = find_empty_location(grid)
if location is not None:
    row, column = location
else:
    return grid

for digit in range(1, 10):
    if is_safe(grid, row, column, digit):
        grid[row][column] = digit

        if sudoku(grid) is not None:
            return grid

        grid[row][column] = 0

return None

def print_solution(grid: Matrix) -> None:

#

its a sudoku with backtracking

#

is this wrong or right

#

im a begginer so sorry if its wrong😄

glacial spire
#

Looks about right? Does it solve your example sudoku?

strange terrace
#

i just test it and it say cannot find solution

#

and i dont know what is wrong with it

glacial spire
#

Wait, I think I see the problem

strange terrace
#

?

glacial spire
#

wait no

strange terrace
#

let me see the code again

#

hmmm what is the problem

#

i just check it and nothing wrong with it

glacial spire
#

When I run sudoku(initial_grid) it just gives me a solution?

#
In [1]: sudoku(initial_grid)
Out[1]:
[[3, 1, 6, 5, 7, 8, 4, 9, 2],
 [5, 2, 9, 1, 3, 4, 7, 6, 8],
 [4, 8, 7, 6, 2, 9, 5, 3, 1],
 [2, 6, 3, 4, 1, 5, 9, 8, 7],
 [9, 7, 4, 8, 6, 3, 1, 2, 5],
 [8, 5, 1, 7, 9, 2, 6, 4, 3],
 [1, 3, 8, 9, 4, 7, 2, 5, 6],
 [6, 9, 2, 3, 5, 1, 8, 7, 4],
 [7, 4, 5, 2, 8, 6, 3, 1, 9]]
strange terrace
#

let me check

#

wait.

#

ohh just solved the problem thanks

#

thank you so much😀

#

XD

winged hamlet
glacial spire
winged hamlet
#

Yes

#

using xor operators without brute force coding

glacial spire
#

... why using xor?

winged hamlet
#

The project want me to compare using binary

#

so need to use xor operator

glacial spire
#

"the project"?

winged hamlet
#

yes

#

Are u keen to help me to debug

glacial spire
#

Well normally I'd just combinations.Counter and some combinatoric maths

#

But it sounds like you have some sort of homework assignment

winged hamlet
#

So is there a solution?

glacial spire
#

Not without knowing what exactly you need to do

fallen ridge
#

I'm new to having to wrangle bunches of data in bespoke ways, and I've got a question about the best way to accomplish something if anyone's got a second

winged hamlet
#

and each time the same number compare by the xor operator if it is true then result add 1

fallen ridge
#

I've got a couple of nested classes that aren't really working like I expected, I was hoping to imitate some logic I've seen from some ML repos I've dug around in, but I have no idea how they implemented what they did.

#

Some semi-dummy code:

class TOKEN:
    def __init__(self, address, abi):
        self.address = address
        self.abi = abi
        self.contract = w3.eth.contract(address = self.address, abi = self.abi)

    class ROUTER:
        def __init__(self, address, abi):
            self.address = address
            self.abi = abi
            self.contract = w3.eth.contract(address = self.address, abi = self.abi)
        def quote()
            self.quote = get_quote


BUSD = TOKEN(abi.busd_address, abi.erc20_abi)
PCS = BUSD.ROUTER(abi.pcs_router_address, abi.pcs_router_abi)

print(BUSD.address)
print(BUSD.contract)
print(PCS.address)
print(PCS.contract)
#

All of my print statements return as expected, but I'm going to have multiple PCS objects as sub-objects of different TOKEN objects

#

so BUSD will have a PCS and BSP class, but I'll also have another token TETH that will also have PCS and BSP classes.

#

How do I keep this clean?

#

I thought I could do print(BUSD.PCS.address) or print(BUSD.BSP.address), but apparently not.

fiery cosmos
#

ok so i am gonna drop a bomb here, and i really need some help. Like please, i dont know calculus, and i found this formula for calculating exp exponentially for a discord bot. here it is

(xp + xp_to_add) // 42) ** 0.55

xp is the amount of xp a user already has, which is pulled from my database. xp_to_add is a random int from 1 to 20, that is added every time a message is sent(if it passes the time lock.

now everything works except that i dont know how to calculate the ex needed to get to another level. Since its exponential, it needs to be gotten using a derivative(?), which i have no idea what that is since i am a middle schooler lmao. Anyway here is my final result(the rank card, and the problem is the /370 XP ~ that needs to be dynamic, calculating the xp needed to level up(and i have no idea) plzzzzz help me this is 3d day of headaches lol

thorn bay
#

What is the best collision detection algorithm?

fiery cosmos
woven trench
#

any good free course for dsa?

fiery cosmos
#

if you need to get the rate of change in the value of the exponents as the user gradually levels up, then just use sympy to do the derivative needed for that its a calculus library

main flower
#

xor is equal to 0 only when both integers are same

#

This will be O(n)

#

And that would be the fastest you can go

fiery cosmos
#

correct me if im wrong but i could technically just get the exponential value but using the ** operator so something like this?
exp_to_lvl = int((xp + xp_to_add) ** 0.55)

#

ugh, doesnt seem to work

vocal gorge
# fiery cosmos ok so i am gonna drop a bomb here, and i really need some help. Like please, i d...

Since its exponential, it needs to be gotten using a derivative(?), which i have no idea what that is since i am a middle schooler lmao.
nah, you just need to inverse the function.
Your level is calculated from xp as int(xp ** 0.55), if I understand it correctly. So to reach lvl, it needs to be that xp**0.55 is at least lvl. Put both sides to the power of 1/0.55, and you'll get that xp = lvl**(1/0.55)

rustic roost
#

@winged hamlet does the data come sorted or unsorted?

fiery cosmos
rustic roost
#

@winged hamlet Please paste the question if you cna

vernal urchin
#

guys, how can i use subprocess to call function of another file ?
#script1.py
import subprocess
l=[3,5,6,7,8,9]
for i in l:
call fun(i) of script2

#script2.py
def fun(f):
f=f*f
print(f)
this is just an example. when i run code for 900 videos(research purpose), it works stopped after 10 videos despite of using gpu

winged hamlet
rustic roost
#

@winged hamlet

rustic roost
#

Why are you doing that I am asking, you could break the loop on the first pair saying such pair exists

#

whats the output format?

#
seq = [1,2,3,4,4,6,6,10,10,10]
def isPair(seq):
    for i in range(len(seq)):
        if(seq[i]^seq[i+1] == 0):
            return True
        return False
#

This should do the if pair exists trick

#

@winged hamlet

rain snow
#

Hey, Im trying to write a mathmatical program to calculate pi based using newtons method of using the unit circle formula, rearanging it into a binomial formula and Using the binomial theorem to solve for pi/

#
########### Atempting to Calculate PI using the binomial series and Calculus
import math 

####Binomial series
iterations  = 10
#x = int(input("Attempting to Calculate PI using the binomial series and Calculus\n The equation of a unit circle is x^2 + y^2 = 1 but we can rearrange that to get route(1-x^2) and simplify this \
#to (1-x^2)^0.5. Which is the equation for the top half of a circle since x can only be positive. by integrating this between the bounds 0 and 1 we can find the area of 1/4 of the circle \
   #and therefore pi will be equal to 4 times that. "))
#n = float(input("n: "))
x= 1
n = 0.5
## First 2 terms in the binomial theorem
number = x+(n*(-x**3)/3)
print(number)
for i in range(1, iterations):
    ###Third term index
    index = i+1
    print(f"index: {index}")
    ##Working out the factorial
    factorial = 1
    
    for j in range(1, index+1):

        factorial *=j
    print( f"factorial: {factorial}")
    ####Working out the coefficient of x.
    coefficient = 1
    for k in range(0, -i-1, -1):
        coefficient *= (n+k)
    print(f"first coefficient: {coefficient} ")
    #### Coefficient before integrating
    coefficient= coefficient/factorial
    print(f"real coefficient: {coefficient} ")
    newindex = index + 1
    value = -(coefficient)* (((x)**(2*newindex)) / 2*newindex)
    print(f"value: {value}")
    print(f"current value of pi is {number*4}")
    number+=value
    print("======================")

temp = math.sqrt(3) /8
pi =  (12*number)- temp
pi = 4*number
print(f"pi = {pi}")
#

3.89660390218099 is the closest I can get

#

it should be more exact than that but for some reason I cant anyone see an error?

#

these are my workings if it helps

winged hamlet
#

X=3, Y=3
X=4, Y=4
X=4, Y=4
X=4, Y=4
X=10, Y=10
X=10, Y=10
X=10, Y=10
Total match is 7.

#

It must be format like this

brave oak
#

it makes it hard to understand what the logic is

rain snow
brave oak
#

but it also makes your code hard to read

rain snow
#

alright one sec

#
########### Atempting to Calculate PI using the binomial series and Calculus
import math
from decimal import *
####Binomial series

iterations  = 124



#x = int(input("Attempting to Calculate PI using the binomial series and Calculus\n The equation of a unit circle is x^2 + y^2 = 1 but we can rearrange that to get route(1-x^2) and simplify this \
#to (1-x^2)^0.5. Which is the equation for the top half of a circle since x can only be positive. by integrating this between the bounds 0 and 1 we can find the area of 1/4 of the circle \
   #and therefore pi will be equal to 4 times that. "))
#n = float(input("n: "))
x= 0.5
n = 0.5

### First 2 terms in the binomial theorem

number = x+(n*(-x**3)/3)
print(number)
for i in range(1, iterations):
    ###Third term index
    index = i+1
    #print(f"index: {index}")
    ##Working out the factorial
    factorial = 1
    
    for j in range(1, index+1):

        factorial *=j
    #print( f"factorial: {factorial}")
    ####Working out the coefficient of x.
    coefficient = 1
    for k in range(0, -i-1, -1):
        coefficient *= (n+k)
    #print(f"first coefficient: {coefficient} ")
    #### Coefficient before integrating
    coefficient= coefficient/factorial
    #print(f"real coefficient: {coefficient} ")
    newindex = index 
    value = (coefficient)* (x**((2*index)+1))/ ((2*index)+1)
    #print(f"value: {value}")
    #print(f"current value of pi is {number*4}")
    number+=value
    #print("======================")
sqrt = Decimal(3).sqrt
temp = sqrt /8
print(temp)
pi =  (12*(number- temp))
#pi = 4*number
print(f"pi = {pi}")
print(cmath.sqrt(3)) 
brave oak
#

AAAAAAAAAAAAAAAA

#

you just commented out the prints...

rain snow
#

BECAUUSE I NEED THEM

brave oak
#

okay honestly my head hurts just looking at it

#

let me

#

take a while

#

one suggestion

#

space out your operators

#

in general you should have spaces around arithmetic operators

#

so like

#

value = coefficient * (x ** (2 * index + 1)) / (2 * index + 1)
instead of:
value = (coefficient)* (x**((2*index)+1))/ ((2*index)+1)

rain snow
#

kk

brave oak
#

if your code is easy to read

#

it will be easier for you to get help

#

ngl I feel tired just looking at that chunk

rain snow
#

okay

brave oak
#

also you might want to break your code up into smaller functions?

#

because then you can test them individually

#

to know they work

#

e.g. the factorial

rain snow
#

no it's really not worth it

brave oak
#

but anyway...

#

!e from math import factorial; print(factorial(5))

halcyon plankBOT
#

@brave oak :white_check_mark: Your eval job has completed with return code 0.

120
brave oak
#

just so you know

#

what is newindex even for?

#

you don't use it anywhere

rain snow
#

yeah wanted to see if I could do it myself

#

it was a bug fixing attempt I was going to add 1 to the index before I integrate but then I realised u cant so that

brave oak
#

remove dead code

#

goes back to the readability thing

rain snow
#

its removed on the main

brave oak
#

main what

rain snow
#

but I copied and pasted this ages ago

#

on my pc

#

the actual.code

#
########### Atempting to Calculate PI using the binomial series and Calculus
import math
from decimal import *
####Binomial series

iterations  = 124



#x = int(input("Attempting to Calculate PI using the binomial series and Calculus\n The equation of a unit circle is x^2 + y^2 = 1 but we can rearrange that to get route(1-x^2) and simplify this \
#to (1-x^2)^0.5. Which is the equation for the top half of a circle since x can only be positive. by integrating this between the bounds 0 and 1 we can find the area of 1/4 of the circle \
   #and therefore pi will be equal to 4 times that. "))
#n = float(input("n: "))
x= 0.5
n = 0.5

### First 2 terms in the binomial theorem

number = x+(n*(-x**3)/3)
print(number)
for i in range(1, iterations):
    ###Third term index
    index = i+1
    #print(f"index: {index}")
    ##Working out the factorial
    factorial = 1
    
    for j in range(1, index+1):

        factorial *=j
    #print( f"factorial: {factorial}")
    ####Working out the coefficient of x.
    coefficient = 1
    for k in range(0, -i-1, -1):
        coefficient *= (n+k)
    #print(f"first coefficient: {coefficient} ")
    #### Coefficient before integrating
    coefficient= coefficient/factorial
    #print(f"real coefficient: {coefficient} ")
   
    value = (coefficient)* (x**((2*index)+1))/ ((2*index)+1)
    #print(f"value: {value}")
    #print(f"current value of pi is {number*4}")
    number+=value
    #print("======================")
sqrt = Decimal(3).sqrt
temp = sqrt /8
print(temp)
pi =  (12*(number- temp))
#pi = 4*number
print(f"pi = {pi}")
#

it's late I gtg

#

bye

winged hamlet
runic tinsel
#

wait no

#

too many matches

#

!e

seq = [1, 2, 3, 3, 4, 4, 4, 10, 10, 10]
def algorithm():
    result = 0
    counts = {}
    for i in seq:
       counts[i] = counts.get(i,0)+1
    for k,v in counts.items():
        p = (v*v-v)//2
        for _ in range(p):
            print('X={}, Y={}'.format(k, k))
        result += p
    print('Total Matches is {}'.format(result))

algorithm()
halcyon plankBOT
#

@runic tinsel :white_check_mark: Your eval job has completed with return code 0.

001 | X=3, Y=3
002 | X=4, Y=4
003 | X=4, Y=4
004 | X=4, Y=4
005 | X=10, Y=10
006 | X=10, Y=10
007 | X=10, Y=10
008 | Total Matches is 7
runic tinsel
#

it doesn't use sortedness

fiery cosmos
#

How open addressing and chaining help to resolve collision resolution in hashing?

#

i am in my exam and this is question of Data Structure

#

someone help pls

charred fractal
#

i am 13

#

and i joined this server for fun

#

and i need help

#

its not related to python AT ALL

fiery cosmos
#

lol ok

#

ask

#

me

#

i guess

fiery cosmos
#

u want me to sub u?

austere sparrow
#

@charred fractal If it's not related to Python, we have off-topic channels.
(also keep in mind that we don't allow advertisement, if that's what you're hinting towards)

prisma lily
#

I was wondering how to use a list comparison to iterate over the first element in the defined list?

jolly mortar
#

could you show an example of what you mean?

charred fractal
fiery cosmos
#

dude same i was wondering yestarday

austere sparrow
#

no @charred fractal, this is not a platform to advertise your youtube channel if that's what you're here for.

fiery cosmos
prisma lily
#

!e

halcyon plankBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*

prisma lily
#

!e for i in range(len(vectors)):
if (mask[i] != True):
near_dist = [[dissimilarity(vectors[i], vectors[i2]), [i, i2]] for i2 in range(len(vectors)) if (((dissimilarity(vectors[i], vectors[i2])) < near_dist[0]) and (i != i2) and (mask[i2] != True))]

halcyon plankBOT
#

@prisma lily :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'vectors' is not defined
austere sparrow
charred fractal
#

so ye

austere sparrow
#

that's a pretty complicated comprehension

prisma lily
#

:/

#

Yeah

#

Uhh

austere sparrow
#

!code could you format it with this?

halcyon plankBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

prisma lily
#

Lemme make a quick simple version

#

In short though instead of appending over a list I was wondering if it was possible for a list comprehension to replace the list

#

Alrighty

halcyon plankBOT
#

@prisma lily :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1, in <listcomp>
004 | NameError: name 'i' is not defined
prisma lily
#
outlist = [i*i for i in range(10)]
print(outlist)
#

This list comprehension returns:

#
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#

I was wondering what I would need to do to iterate the first element of the list over all elements resulting in the list:

#
[81]
#

Would my only option be a for loop?

runic tinsel
#

yes

#

i don't know what you mean, but it's a for loop

dusk bison
#

hey everyone, i couldn't find this online but does interpolation search work for strings in a list too?

prisma lily
#

It's currently doing this:

#
outlist = []
    
    for i in range(10):
        outlist.append(i*i)
    print(outlist)
dusk bison
#

That's not what you want?

prisma lily
#

And I want it to do something more like this:

#
 for i in range(10):
    outlist[0] = i*i
print(outlist)
jolly mortar
#

why do you want a list in that case? why not modify a single variable in the loop?

#

also, what are you iterating over in your main code?

prisma lily
#

This is to be nested within a list comprehension

#

I'm storing other elements in the list that relate to the iteration with the overall function

#

I'm iterating over an iteratable iterating over the length of another list if that makes any sense

spark cedar
#

hello can anyone suggest me a course for DS&A ??? Are joma tech's courses any good ??

runic tinsel
#

depends on length of the list

#

dictionary is faster eventually

#

use dictionary

vocal gorge
#

It depends on the use case, but I think this "eventually" may come as soon as n=1

#

for this case:

def f(n):
    lst = [(i,i+1) for i in range(n)]
    %timeit next((el for el in lst if el[0]==n), None)
def g(n):
    dct = {i:i+1 for i in range(n)}
    %timeit dct.get(n,None)

(comparing a list of tuples to a dict), even for n=1 g(n) is faster; because the dict way doesn't need a genexpr with a comparison (all of which happens in Python code)

vocal gorge
#

what do you mean by "best"?

#

and for that matter, by "collision detection algorithm"? Like, do you want Continious Collision Detection or something?

fiery cosmos
#

Worth mentioning in general searching a list like that takes time proportional to the length of the list O(N), whereas a dictionary lookup is constant time O(1) (with high probability Daijoubu). So dict is definitely faster unless the list is tiny.

uneven yarrow
#

you can thank hashes for that uberyaay

uneven yarrow
#

I don't understand it entirely either, but it's an integral piece.

#

Try asking someone else (and relay it to me if you could)

half lotus
#

What do you want to know about hashing?

#

There's a hash function, and there may sometimes be collisions (2 keys result in the same hash). There are generally 2 solutions to deal with collisions: one is to create a linked list and store all values that have the same hash in it. The other is a probing technique, where it keeps modifying the key until it results in a hash that hasn't been used before.

fervent saddle
#

It’s basically making a list with a lot of empty space, and then doing some math formula on the value you want to put in the list to get a valid index position, and putting it at that index

#

A simple example for strings would be adding the numeric values of all the characters, then using the remainder of that sum divided by the length of the list

#

Then if you want to check if a string is in the list, you just use that formula and check at that index if it’s holding an equivalent string

#

That’s the basic idea of it. Then there’s also a lot of ways to deal with if multiple values get the same index position, like mark mentioned. If you don’t deal with that in some way then it won’t work right

#

But the idea of hashing is just using some formula to get an arbitrary non-random index position

fiery cosmos
craggy wagon
#

@fiery cosmos 2021?

fiery cosmos
#

rooThink hmm

#

The data structures haven't changed much in 10 years Daijoubu

lean dome
#

Or 40, honestly 😄

runic tinsel
#

40 is conservative yeah

fiery cosmos
#

I was trying to make a math function that subtracts the minimum value of a list (lists are used as input). I end up getting this error:
Arr.minimum(*list1, *list2)
TypeError: minimum() takes 1 positional argument but 8 were given

#

My code:

class Arr():

    def __init__(self, f_list, s_list):
        self.f_list = f_list
        self.s_list = s_list

    def minimum(self):
        self.f_list = min(f_list)
        self.s_list = min(s_list)
        difference = self.f_list - self.s_list
        print(difference)

    def maximum(self):
        self.f_list = max(f_list)
        self.s_list = max(s_list)
        addes = self.f_list + self.s_list
        print(addes)

list1 = [1,3,2,6]
list2 = [5,2,5,6]

Arr.minimum(*list1, *list2)```
fiery cosmos
#

I don't know much python. But can't you just make minimum() takes 2 lists instead?

gritty marsh
#

What would a linked list implementation in Python look like especially since there's no way to store a reference to a certain location in memory?

fiery cosmos
#

If you have a Node class it can have a self.next member that is another Node instance

marble bronze
#

I'm currently taking a course about Data Structures and algos, I have this hackerrank thing that I have to do, and it is about Binary Search Trees. Can I inquire here? Very, very new at coding

fiery cosmos
#

Ask away.

marble bronze
#

you know when talking it out sometimes helps?

#

thanks

#

HAHAHA

fiery cosmos
#

Rubber duck debugging is a thing lel.

#

Good luck with your schoolwork.

marble bronze
#

I'm gonna be frequent here in the future, haha

untold crown
fiery cosmos
untold crown
#

I think Ik what the problem is. In this case, f_list and s_list are objects rather than variables. The _init_ function passes these as variables, which is why they're not defined as variables, instead being defined as objects when called in the Arr class

untold crown
#

What about using *args or **kwargs instead of what I did? Maybe that'll work

austere sparrow
halcyon plankBOT
#

@austere sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
austere sparrow
#

Or do something like this:

class Node:
    def __init__(self, head, rest):
        self.head = head
        self.tail = tail

which will allow you to attach methods to it

oak spindle
#

what this means?

austere sparrow
#

where does this code come from?

oak spindle
#

this only works on console?

austere sparrow
oak spindle
#

okay, thanks

austere sparrow
#

also, you don't need semicolons

oak spindle
#

yea, i just followed from c++ and it became a habit, lol

winter rampart
#

btw how many of u guys use virtual studio

oak spindle
#

vs code?

winter rampart
#

yep that one

oak spindle
#

i'm using that one

gritty marsh
#

Sometimes you confuse different languages, ya know

last fulcrum
#

Why is an inner loop quadratic?

#

For example if I do

n = 4
for j in range(n):
    for i in range(j + 1):

i is not quadratic for me. Even combining the sum of i and j goes nowhere near 16 times.

gritty marsh
#

It doesn't have to be n^2 exactly to be quadratix

#

In that example, the complexity is n(n+1)/2

#

Simplifying you get (n^2+n)/2

#

Dropping the lower order terms, you get n^2 ;)

#

Big-O notation describes how an algorithm grows

untold crown
#

@fiery cosmos Is this what you were looking for? (Sorry for the late response)

gritty marsh
#

So your example grows quadratically

#

It doesn't necessarily have to be quadratic

#

Did this answer your question @last fulcrum ?

untold crown
untold crown
#

same result but without the extra *arglists in the bottom two functions

last fulcrum
untold crown
gritty marsh
#

It's the partial sum of an arithmetic series! Are you familiar with that topic in maths?

last fulcrum
gritty marsh
last fulcrum
untold crown
#

the global statement I did is redundant, I was testing out some things with **kwargs so that's why it's there (got errors so I gave up on it, but I guess I forgot to remove the global statement afterwards)

winged hamlet
#

Hi can i ask is it possible to get the key function to able to sort like name, title, etc if is selected?

last fulcrum
#

@gritty marsh the book I'm reading says this. Although I don't understand the maths.

gritty marsh
#

@last fulcrum ah. Are you familiar with arithmetic series?

gritty marsh
last fulcrum
gritty marsh
#

An arithmetic series is simply a series of numbers produced by adding some other number to an original number repeatedly

#

Wow that's a bad definition

#

take for example the example series in that image you sent

#

1 + 2 + 3 + 4 + 5 + ... + (n - 2) + (n - 1)

#

here, the original number is 1

#

the common difference is 1

#

you get the second term of the series by adding 1 to 1 (resulting in 2)

#

you get the third term of the series by adding 2 to 1 (resulting in 3)

last fulcrum
#

Oh I've heard of it

#

I saw a video about it last month

gritty marsh
#

mmhmm

#

so the general formula that will be used to represent an arithmetic series is as follows:

#

(a_1) + (a_1 + d) + (a_1 + 2d) + ... + (a_1 + (n-2)d) + (a_1 + (n-1)d)

#

a_1 is the starting number

#

d is the common difference

#

n is the number of terms you want

last fulcrum
#

so how does that go and transform into n2?

gritty marsh
#

Do you understand this formula?

last fulcrum
#

Yes.

gritty marsh
#

Alright, great!

#

Notice how we can represent this series in a different way

last fulcrum
#

if d is 7 you always need to add 7 to the previous number to get the next

gritty marsh
#

Correct!

gritty marsh
#

The last term in this case would be a_n

#

so we would represent that as follows:

#

(a_n) + (a_n - d) + (a_n - 2d) + ... + (a_n - (n-2)d) + (a_n - (n-1)d)

#

Do you understand that this is simply the series above but in reverse?

last fulcrum
#

what is a _ n? Does_mean multiplication?

gritty marsh
#

a_n is simply the last term in this series

#

if a_1 is the first term, and a_2 is the second term

#

and we have n terms

#

then a_n is the last term

#

_ in this case is just subscript notation

last fulcrum
#

Oh that makes sense. So if we have 10 numbers we can say find a10

gritty marsh
#

Alright, great!

#

Now, the result when you add up all of those terms is known as the "partial sum"

#

we call it the partial sum because of course, the series is infinite

#

so if we have the sum of the first 10 terms of the series it's only a part of the series

#

we use s_n to denote partial sum

last fulcrum
#

Ok

gritty marsh
#

if s_1 means the sum of the first 1 terms, and s_2 means the sum of the first 2 terms, then s_n is the sum of the first n terms

#

Are you following along with me?

last fulcrum
#

Yes. Basically like a_n So we can say get the sum of the first 30 terms, which would be s30

gritty marsh
#

Yep

#

Okay, we have all the bits and pieces to start our proof now

#

we have two equations to represent the partial sum:
s_n = (a_1) + (a_1 + d) + (a_1 + 2d) + ... + (a_1 + (n-2)d) + (a_1 + (n-1)d)
and
s_n = (a_n) + (a_n - d) + (a_n - 2d) + ... + (a_n - (n-2)d) + (a_n - (n-1)d)

#

Now tell me, do you notice anything interesting or useful about the two equations above?

last fulcrum
#

One is the reverse of the other.

gritty marsh
#

Yes, anything else?

#

Hint: look at the common differences (d)

last fulcrum
#

both have 2d, and (n-2)d

gritty marsh
#

Nearly there!

#

Do you see anything interesting with the signs? (+/-)

last fulcrum
#

All I see is that the signs are reversed for both

gritty marsh
#

Correct!

#

And that is great!

#

Do you have any idea why that is great?

last fulcrum
#

Give me a min

#

I think that means we can get the first value of a sum if we are given the last

#

And the reverse is true

#

and d

gritty marsh
#

Not quite, here's a hint:

#

s_n = (a_1) + (a_1 + d) + (a_1 + 2d) + ... + (a_1 + (n-2)d) + (a_1 + (n-1)d)
s_n = (a_n) + (a_n - d) + (a_n - 2d) + ... + (a_n - (n-2)d) + (a_n - (n-1)d)

#

what do you think will happen when we add them together?

last fulcrum
#

We can add and subtract like terms?

gritty marsh
#

Correct!

#

We can cancel out all the d's!

#

So our result is simply
2*s_n = (a_1+a_n) + (a_1+a_n) + (a_1+a_n) + ... + (a_1+a_n)

#

(a_1+a_n) is repeated n times

#

so we can simplify this as

#

2*s_n = n(a_1+a_n)

#

isolating the s_n, we get

last fulcrum
#

2*s_n = n(a_1+a_n) / s_n

#

2* = n(a_1+a_n) / s_n

gritty marsh
#

Sorry, internet went out

#

Do you know how to isolate that s_n variable @last fulcrum ?

#

To isolate that s_n variable we simply perform algebra magic

#

s_n = n(a_1+a_n)/2

#

if we have the example series above 1 + 2 + 3 + ...

#

then a_n = n

#

a_1 = 1

#

thus

#

s_n = n(n+1)/2

last fulcrum
gritty marsh
#

Yep

gritty marsh
#

which is of course the series you were asking about

#

but does not apply to all series

last fulcrum
#

I was getting confused by that

gritty marsh
gritty marsh
#

because a_1 = 1 and a_n = n

last fulcrum
#

So how does the general or simplification go to n2?

gritty marsh
#

Ah, this is a whole different explanation

#

okay so we've established that the complexity is quadratic

#

because of the above equation

#

n(n+1) / 2 expands to (n^2 + n) / 2

#

which expands to (1/2)*(n^2) + (1/2)*n

#

in big-O notation, we don't care about the lower order terms

#

we care about the algorithm's growth

#

thus, we throw away the lower order terms

#

n is a lower order term

#

(1/2) is a lower order term

#

so we simply say O(n^2)

#

because it grows quadratically

#

it does not necessarily have to be exactly n^2

#

let me throw up a quick desmos graph

#

This is the graph for very very small n

#

notice there are noticeable differnces

#

of course, they're different equations. there would be differences

#

but notice what happens when we zoom out

#

This is for n on the orders of the hundreds

#

They look like the same graph, don't they?

#

Because they grow the same

last fulcrum
gritty marsh
#

Correct

last fulcrum
#

Man you explained it so well

#

I totally get it

gritty marsh
#

😆 my pleasure

last fulcrum
#

I'll come to you for more help.

#

Thank you

gritty marsh
#

Welcome!

winged hamlet
#

for key in emp_dict:
record_list.append(key)
templist = []
for key, value in emp_dict.items():
temp = [key, value]
templist.append(temp)

#

Can anyone help me for the coding

#

Basically i want to sort by name in dictionary. The key is Employee ID, and the following will have name, title, et

fiery cosmos
#

Have you tried googling something like "sort dictionary by value"?

potent portal
#

im failing on the test case of [1] and 1 but i cant really see why?

#

its expected to return an empty list but this returns [1]

fiery cosmos
#

Anybody knows a video or tutorial about how to create a simulation for image processing? With photon amount and exposure time and all of that?

fiery cosmos
#

Okay so I m gonna ask here because i can t find a proper explanation. What is a B Tree and why the hell should I use a B tree? Is there any good explanations? I can't find a satisfying one (for me)

#

The only thing that I see in a B tree is that the B tree is some sort of BST but with arrays

oblique citrus
#

I'm new in coding with Python and this Problem showed up when I wrote this code.

#

I tipped this code in the anaconda probt and this error does not disappear. Pls help me.

vocal gorge
#

Pycharm by default (if you click through the project creation dialogue) creates a venv for each project.

#

So installing the package via anaconda will install it into your main environment, not the venv.

#

Instead, click that insall package prompt and it'll install it for you (or the slightly longer way - go to the Packages tab and search scikit-learn there)

vocal gorge
#

(also, this isn't really what this channel is for)

oblique citrus
#

thanks

valid slate
#

Hi, I wanted to ask if I wanted to visualize merge sort then how do I exactly keep track of the main array ?

chrome field
#

hey

unborn sundial
#

huh. feeling myself being an idiot
!e

def decorator_factory(argument):
    def decorator(function):
        def wrapper(delay, *args, **kwargs):
            print(f"getting argument {argument}")
            print(f"magically knowing in advance value {delay} of the functiom!")
            result = function(delay, *args, **kwargs)
            return result
        return wrapper
    return decorator

@decorator_factory(10)
def pause(delay):
    print(f"paused for {delay} seconds!")

pause(5)

I can actually use arguments of my function in decorator in a normal way... I always extracted from *args them

sly bronze
#

anyone know if I use windows development kit's sign tool on my exe converted file (from python) will it stop seeing it as threat on other computers ?

eager hamlet
#

say i had a tree

#

with a bunch of numbers

#

i have to perform 2 operations:

#

sum of numbers on the path between any two vertices

#

increment or decrement all numbers on the path between any two vertices by a set amount

#

how would i do this (preferably in log (size of tree))

whole plover
#

vertices?

#

the space between the vertices are the space

#

between Documents and Downloads?

lunar jacinth
#
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
        
        if root1 and root2:
            root = TreeNode(root1.val+root2.val)
            root.left = self.mergeTrees(root1.left, root2.left)
            root.right = self.mergeTrees(root1.right, root2.right)
            print(root)
            return root
        else:
            return root1 or root2
#

can someone help me understand this?

stable pecan
#

some weird meld function that creates a tree with nodes whose values are the sum of the corresponding nodes in root1 and root2

lunar jacinth
lunar jacinth
#

but like im not sure how the algo works here...

#

like how does it know which is left or right?

stable pecan
#

when binary trees are densely packed into a list you can tell a left node from a right node by whether it's in an odd position or even position in the list

#

actually, because they're providing the trees as a list, you can massively simplify the solution

keen hearth
ashen jay
hollow kayak
#

please anybody that know how to get free rdp help me pls

eager hamlet
#

it could be a straight line, or just a bunch of nodes connected to a central one

tall aurora
#

What's a good source to learn algo and ds?

sullen dock
#

hey, anyone know how to implement multilevel queue cpu scheduling algorithm in python

supple hemlock
#

IDK i just started learning python I know nothing

last fulcrum
#
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))

Can someone help me with the return in the else block? How does it decrease itself?

last fulcrum
# tall aurora What's a good source to learn algo and ds?
onyx root
full portal
#

What's the mathematical way to find the average speed with miles and speed limits

#

or is it the same as finding the average with any list of numbers

last fulcrum
onyx root
last fulcrum
#

So on the second it should still be 5 -4

onyx root
#

each call keeps its own value of n, but the function calls nest like russian dolls

last fulcrum
#

Still confusing me. You said it calls factorial with n = 4, but the value of n I gave to the code never changed. I guess my problem is why is n changing. In a normal python code that would not be possible

#

I'll go watch some YouTube videos to help

fiery cosmos
#

I want good resource to learn algorithms

#

and data structures

#

using python

austere sparrow
fiery cosmos
#

Also it could be better if it resource will be documented using BIG O

#

noatation

last fulcrum
last fulcrum
austere sparrow
#

!e

def print_numbers_down_from(n):
    print(n)
    if n > 0:
        print_numbers_down_from(n - 1)

print_numbers_down_from(4)
halcyon plankBOT
#

@austere sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | 4
002 | 3
003 | 2
004 | 1
005 | 0
fiery cosmos
austere sparrow
#

In other words, n isn't a global variable.

jagged oasis
#

Ya n in scope of function only

last fulcrum
onyx root
fiery cosmos
last fulcrum
onyx root
#

@fiery cosmos if you want to learn the basics of Big-O, this is a good less-mathematical introduction: https://bit.ly/bigopy

fiery cosmos
last fulcrum
#

Ok thank you @austere sparrow @onyx root I think what is confusing me is that I've never seen 5 different function calls happening.

onyx root
last fulcrum
austere sparrow
#

smh rule 6 lemon_pensive @onyx root||/s||

onyx root
fiery cosmos
austere sparrow
last fulcrum
#

@austere sparrow I really understood the print_numbers function. Not sure why it's not clicking for the factorial haha

austere sparrow
#

it has a really good visual debugger

#

I'll show a screenshot, but I have 2gb of updates to download

last fulcrum
#

Nope. But I just understood the factorial also. I'll explain so you tell me if it's right

onyx root
last fulcrum
#

So it's 5 right, then it calls the function on 5 saying factorial (5-1)
So now it's 4. So it calls the function on itself saying again 4-1, so it's basically like it stores the number subtracted and then on the next call uses that number.

austere sparrow
#

It's not really "changing n", it just spawns an entirely separate function call, which will have its own, completely separate n variable.

onyx root
#

@last fulcrum Look at this example:

def foo(n):
    print(n)

n = 5
foo(10)
print(n)
#

The call to foo doesn't change the n on the outside, only the n on the inside

last fulcrum
#

!e
def foo(n):
print(n)

n = 5
foo(10)
print(n)

halcyon plankBOT
#

@last fulcrum :white_check_mark: Your eval job has completed with return code 0.

001 | 10
002 | 5
last fulcrum
austere sparrow
#

Imagine a shady Amazon seller. When you buy a book from him for $20, he goes on to buy it from another seller for $16. That seller in turn buys from another seller for $14, who just had it laying around.

#

Each of those transactions will have its own price, order ID etc.

last fulcrum
#

So I have one more question.

#

So then if it's doing separate calls how does it combine them all when it reaches the base case?

austere sparrow
#
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n - 1)

If you call factorial(1), it's going to return 1.
If you call factorial(2), it's going to return 2 * factorial(1), which will in turn call factorial(1), which will return 1, so the result is 2
If you call factorial(3), it's going to return 3 * factorial(2), which will in turn call factorial(2), which will return 2 (as shown above), so the result is 6
If you call factorial(4), it's going to return 4 * factorial(3), which will in turn call factorial(3), which will return 6 (as shown above), so the result is 24

#

You could change the function like this:

def factorial(n):
    if n == 1:
        return 1
    else:
        previous = factorial(n - 1)
        return n * previous
```, maybe that will help.
last fulcrum
austere sparrow
last fulcrum
austere sparrow
#

👍

sick dagger
#

Hi! I was browsing the internet and found this golden ratio formula. I tried to code it, unfortunately it seems endless and I have trouble conceptualizing the code. Someone would have any idea ? Thank you.

austere sparrow
topaz swallow
#

I think it will be hard

#

Can you explain what you mean by implementation ?

fiery cosmos
#

@onyx root Could you please recommend an algorithms and data structure book?

fiery cosmos
#

I just want to have sevral choices

fiery cosmos
#

A favorite source

keen hearth
onyx root
fiery cosmos
keen hearth
onyx root
fiery cosmos
onyx root
#

they expect you to implement red-black trees, or something, which you will never have to do on the job.

#

if you can study for the interview, then what is the interview assessing?

austere sparrow
# sick dagger Hi! I was browsing the internet and found this golden ratio formula. I tried to ...

The trick to computing infinite fractions is usually to take some initial value and substitute it for the ....
For example, if you pick 1 for ... and some random depth, you end up with

phi = 1 + (1/(1 + (1/(1 + 1/(1 + 1/(1 + 1/(1 + 1/(1 + ...))))))))
phi = 1 + (1/(1 + (1/(1 + 1/(1 + 1/(1 + 1/(1 + 1/(1 + 1))))))))

...which is 1.619047619047619.

The way you could get up to this point is, for example:

  1. take some value as your result, like 1
  2. compute 1 + 1 / (1 + result). It's going to be a slightly better approximation.
  3. store the new approximation
  4. go to step 1

However, this gets a bit tricky.
Let's try to find an exact solution for phi:

φ = 1 + 1/φ
φ^2 = φ + 1
φ^2 - φ - 1 = 0

φ = (1 + √5)/2
φ = (1 - √5)/2

So there are two solutions to this equation.
If you try to substitute some number (except -1) using the algorithm above, you'll be slowly approaching (1 + √5)/2 (approx. 1.618). However, if you choose (1 - √5)/2 (approx. -0.618) as your starting point, you'll get:

φ0 = (1 - √5)/2

φ1 = 1 + 1/φ0 = 1 + 2/(1 - √5) = ((1 - √5) + 2)/(1 - √5) = (3 - √5)/(1 - √5)

Using some transformations (e.g. using the proportion rule, (3 - √5)/(1 - √5) = (1 - √5)/2 <=> (6 - 2√5) = (1 - √5)(1 - √5) <=> 6 - 2√5 = 6 - 2√5), you can see that you end up at the same point, and result is going to stick to (1 - √5)/2.
(with floating point numbers, of course, it's going to eventually drift, but it's still going to do that very slowly).

#

oops sorry for the text wall

fiery cosmos
austere sparrow
#

if you implement your own optimized red-black tree for a simple CRUD application, you'll probably get fired 👀

onyx root
fiery cosmos
onyx root
#

have you built anything interesting?

wide lake
#

hey guys just completed the basic of python if i want to start dsa where do i start like any youtube channels,books,websites

#

any recommend

oak spindle
austere sparrow
stable pecan
#

i did avl trees recently, not red-black trees

#

i'm slacking

fiery cosmos
#

I guess it wasn't about competitive problem solving, right?

indigo radish
#

But the theory of book, the approach is nice.

fiery cosmos
#

Infinite and no pattern

#

you have formula to get closer, but never exact

#

Like pi

last fulcrum
#

For binary search, is it better if your item has not been found to make the new upperbound the mid - 1 or is just mid?

#

Same thing for lowerbound if the item has not been found (mid + 1 or mid)

#

And is it better to use iteration or recursion for binary search?

runic tinsel
#

performance-wise iteration is always better, you use recursion for aesthetic reasons like readability

#

well not always, often it's the same, depends on the compiler

#

for python you want iteration

last fulcrum
#

Anyone knows what I'm doing wrong?

def binary_search(sequence, item_to_find):
    lowerbound = 0
    upperbound = len(sequence) - 1

    while lowerbound <= upperbound:
        midpoint = (lowerbound + upperbound) // 2

        if sequence[midpoint] == item_to_find:
            return sequence[midpoint]

        elif sequence[midpoint] < item_to_find:
            upperbound = midpoint

        else:
            lowerbound = midpoint
    return None
runic tinsel
#

do -1 and +1

#

and it's > item_to_find

last fulcrum
#

And why can't you do midpoint = lower, but you have to add one

runic tinsel
#

[1,2] and you look for 2

#

midpoint is 0

#

you change lower bound to 0, nothing changed

#

just how numbers work out

last fulcrum
runic tinsel
#

0+1

#

[1,2] is entire array

#

so 0 and 1

last fulcrum
#

Ok makes sense.

runic tinsel
#

maybe -1 is not necessary

#

can't hurt

fierce wolf
#

hi there, I feel like I have been given a question in this practice paper which is not totally accurate and was hoping someone could help me understand. I need to apply branch-and-bound technique to a knapsack problem - but I need to do this by using jumptracking and not backtracking

#

I was under the impression knapsack problems were solved using backtracking and machine learning type problems were solved with jumptracking

#

so i'm at a loss when trying to solve a knapsack problem with jumptracking, any help is appreciated thank you

eager hamlet
#

would a greedy method work for this problem?

shut phoenix
#

why does this doesnt work? (Ive a file were is the data I need, and its called codigos.py), appears an error in there


from Codigos import English

objQuestionnaire = English()

objQuestionnaire.empezar()
objQuestionnaire.respuestas()
objQuestionnaire.imprimir()
vocal gorge
shut phoenix
#

okok, thanks

dapper sapphire
#

If we modify the current array/list, we are not using any extra space, then is it considered O(1)?

vocal gorge
#

Yes, inplace doesn't count as extra memory. For example, many inplace sorts are O(1) extra memory.

#

(timsort among them, I think)

dapper sapphire
#

ok got it thanks!!

fiery cosmos
#

Hi, Is this the right place to ask about resources related to algorithms and ds in python?

vocal gorge
#

Yup

fiery cosmos
#

So I've been looking for resources lately, I tried CLRS, Princeton Uni's course on Algorithms, elements of programming interview in python but none of them were good for me atleast. I was looking for something which would just explain me the basic algorithms, ds and maybe the implementation from scratch w/o importing anything, I'm ok with video lectures but I prefer articles/books.

jagged oasis
#

I recommend implementing data structures by hand in another language.

fiery cosmos
#

like by myself?

#

I'll use C++

#

I'll look at the pinned resources first.

marble bronze
#

Is there anyone here knowledgeable about BSTs and heaps?

drifting drum
#

Came across this question in some test:
You have an array of integers.
You're supposed to remove those elements A[i] which satisfy A[i] > A[i-1]
Do this until you cannot find any more pairs. How many rounds does it take till you cannot find any more pairs?
For example

[3, 6, 2, 7, 5]
After 1 round, it becomes [3, 2, 5]
After 2 rounds, it becomes [3, 2]
And then it stays that way forever so the answer would be 2

Another example is:
[6, 5, 8, 4, 7, 10, 9]
After 1 round, [6, 5, 4, 9]
After 2 rounds, [6, 5, 4]
Then it stays that way

Constraints were len(arr) <= 10^5
Initially thought it had to do with next smaller element and stacks, but then got stuck
thoughts?

#

I also tried simulating it, but that timed out ofcourse

vocal gorge
#

can't you do it in one pass? Like, just extract a descending subsequence from the list

#

iterate over the list, remembering the last accepted element. The first element is accepted, then accept only elements <= the remembered one.

drifting drum
#

or maybe I don't understand clearly what you're trying to say

#

erm, okay you mean get rid of the elements that satisfy that condition

#

okay but then?

vocal gorge
#

You need to remove all elements that's higher than the previous one. So for an element to remain, it has to be <= the previous one, and therefore <= than all previous ones

drifting drum
#

<= ?

#

right

#

then?

vocal gorge
#

therefore, you just need to accept only elements that are lower or equal to the last accepted element

#

and that's pretty much it

#

a single pass over the list, O(n) complexity

drifting drum
#

how does that give us the number of rounds?

#

getting the numbers that remain in the end is easy, O(N) with a stack, yes.
However, the # of rounds is what's required.

vocal gorge
#

oooh, I totally missed this. Hmm...

#

perhaps the number of turns for a number to get removed is something like "how many positions away the previous lower number is"

drifting drum
#

so did I, when I was solving it initially. Implemented the same idea before realising it -.-

#

haha, yeah I thought so too but then it's easy to come up with counterexamples for that

#

1, 10, 11, 12, 13, 4
vs
1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 4
Both cases require 2 days

#

and I tried handling that but then it got tricky because there can be examples like above where you need 3 days, 4 days, more

vocal gorge
#

A number that gets removed but doesn't get removed right away must be a part of a nonincreasing subsequence that starts with a higher number than the last accepted number before it, so, hmm

drifting drum
#

must be -> may be

#

5, 10, 11, 12, 13, 4
vs
1, 10, 11, 12, 13, 4

vocal gorge
#

hmm, indeed it's not obvious

drifting drum
#

thank you for saying that, makes me feel less bad that I couldn't solve it 😄

vocal gorge
#

I do feel like it's the right way to dig, though - for each nonincreasing subarray, determine how many numbers need to be chipped off of it

drifting drum
#

yeah essentially you could simulate it till you realise there's no increasing subarrays left anymore

#

but that's gonna time out

vocal gorge
#

in these cases, the subsequence is 13,4, and it needs to lose 1 number in the first (because then 5>4) and 2 in the second case (because 1 is lower than both of them)

drifting drum
#

yeah, I think getting the numbers isn't the hard part

vocal gorge
#

I feel like it might be, for each nonincreasing subarray, the number of numbers in it that's higher than the last accepted number

#

and then you take the max over all these counts to get the value for the entire list

drifting drum
#

I mean, getting the final list of numbers that survive

#

i was thinking of cases where you have like
p , .....q, ..... , r, ......, s,..... w

#

the dots are the elements that are going to get removed

#

so if q > p, then q needs 2 days.

#

and then if r < q and r > p, it will need 3 days
but if r > q, it needs 2 days

#

but if q < p

#

then, it's like q becomes the new p

#

and now if r > q, r needs 2 days.

#

and if r < q, then.. r becomes the new q? and in turn the new p

#

and that's like

#

O(N^2) again because

#

it really makes no difference whether our array was
p , .....q, ..... , r, ......, s,..... w
or
p, q, r, s , w

#

because in the worst case

#

we could have p > q > r > s
and for w, we might have to wound back all the way upto p to check whether it gets removed

#

Agh, now that I think of it

#

TreeSet sounds like such a good idea

#

Oh god -.-

#

that would give us the position of w in the array [p, q, r, s] and essentially the number of days, in log(n) time

#

hm, I'm still fuzzy about it, maybe I'm just wrong

vocal gorge
# drifting drum hm, I'm still fuzzy about it, maybe I'm just wrong

it still sounds to me like you don't need any ds here. Like...

def rounds(nums):
    accepted = last = nums[0]
    max_rounds = 0
    noninc_count = 0
    for num in nums[1:]:
        #print(num,accepted,max_rounds,noninc_count)
        if num<=last:
            # we're in a nonincreasing subsequence
            noninc_count += 1
            if num <= accepted:
                max_rounds = max(max_rounds, noninc_count+1)
                accepted = num
                noninc_count = 0
        else:
            noninc_count = 0
        last = num
    max_rounds = max(max_rounds, noninc_count+1)
    return max_rounds
#

this seems to pass all examples you posted

drifting drum
#

This for example

#

fails nums = [5, 10, 11, 12, 4]

#

well, probably this is an easy one too, but what I meant to say is there were many more cases yeah

#

I failed on like the last 2 amongst all their cases

#

and ofc, the cases weren't revealed

#

now the answer for this case btw, should be 1, the code outputs 2

vocal gorge
#
def rounds(nums):
    accepted = last = nums[0]
    max_rounds = 0
    noninc_count = 1
    for num in nums[1:]:
        if num<=last:
            # we're in a nonincreasing subsequence
            noninc_count += 1
            if num <= accepted:
                #print(num,accepted,max_rounds,noninc_count)
                max_rounds = max(max_rounds, noninc_count-1)
                accepted = num
                noninc_count = 0
        else:
            noninc_count = 1
            #print(num,accepted,max_rounds,noninc_count)
        last = num
    max_rounds = max(max_rounds, noninc_count)
    return max_rounds

passes it. Actually, lemme build a proper automatic tester...

drifting drum
#

well this one would fail on
nums = [5, 10, 11, 12, 6, 7]

drifting drum
vocal gorge
#

ah, I see

#

I generated an example [0, 1, 1, 2, 1]

#

which... yeah, it shows why my approach is flawed

#

my approach would predict that both subsequences here 1,1 and 2,1 dissolve in 2 turns

#

but in reality, after one turn, 0,1,1 is left, and the second 1 doesn't dissolve on that turn

drifting drum
#

also, let's just assume numbers are unique right now

#

(not that it changes anything ofcourse)

#

and yes, correct

vocal gorge
#

here's the automated tester I used, using hypothesis to generate examples:

from hypothesis import given, strategies as st

def rounds_exact(nums):
    """Inefficiently (but, hopefully, correctly) calculates rounds needed by simulating"""
    nums = list(nums)#copy
    rounds = 0
    while True:
        new = [nums[0]]
        skips = 0
        for i in range(1,len(nums)):
            if nums[i] > nums[i-1]:
                skips += 1
                continue
            new.append(nums[i])
        if skips == 0:
            break
        rounds += 1
        nums = new
    return rounds

# make hypothesis disprove this.
# Limiting the list size to 1000, otherwise rounds_exact would be too slow.
@given(st.lists(st.integers(0,1000),min_size=2,max_size=1000))
def test_rounds(nums):
    true = rounds_exact(nums)
    calc = rounds(nums)
    assert true==calc,(true,calc)

test_rounds()
drifting drum
#

ah, quite cool

#

what's the st.lists() and given decorator doing
@given(st.lists(st.integers(0,1000),min_size=2,max_size=1000))

#

oh, building a list of ints from 0-1000 of 2 <= size <= 1000

#

hm

vocal gorge
#

the decorator here describes the parameters - that nums should be a list of size 2 to 1000 of integers from 0 to 1000

gleaming kite
#

wow, cool

drifting drum
#

I see

#

interesting stuff, thank you for sharing that

gleaming kite
#

how it works? by trying to fuzz whole AST?

vocal gorge
austere sparrow
#

it can also use type hints to infer the data to generate, which is cool

#

(if your data doesn't have additional constraints)

vocal gorge
#

as for how exactly it works, uhh... I'm trying to read the source but it's unclear. I think it generates examples randomly starting from "simple" ones, but a lot of the niceness comes from it being able to shrink a disproving example to a simpler one

gleaming kite
vocal gorge
halcyon plankBOT
#

hypothesis-python/src/hypothesis/internal/conjecture/utils.py line 164

def biased_coin(data, p, *, forced=None):```
vocal gorge
#

it has... quite a bit of comments

fallen breach
#

Hi ! I have a problem ! I have a data file with an array of 7221721721171, I would like to split whenever it meets the number 7
the result I want is : [7..],[7..],[7..] , I tried np.split but I have some difficulties . thx you !

past escarp
#

is there a library that has max_heap implemented? i only found minheap

fiery cosmos
#

Negate all the numbers

past escarp
#

k thanks

loud trail
#

are there any performance constraints? is the file really big?

fallen breach
fallen breach
halcyon plankBOT
#

Hey @fallen breach!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

fallen breach
#

so basically the problem is I have 2 list

scenic goblet
#

how to implement dfs in edge list vector<pair<int,int>>edges

loud trail
#

!e ```python
text = '7221721721171'
sections = []
section = []
for c in text:
if c == '7':
sections.append(section)
section = [c]
else:
section.append(c)
print(sections)

halcyon plankBOT
#

@loud trail :white_check_mark: Your eval job has completed with return code 0.

[[], ['7', '2', '2', '1'], ['7', '2', '1'], ['7', '2', '1', '1']]
fallen breach
dull yoke
#

hello guys, I have a deque with maxlen of 50 items that belongs to [0, 640].

#

Most of the items fluctuate minimally with the range of about 50 or 60. But suddenly, some items emerge from the graph, rise above or go lower than the fluctuation range. How do I detect that change?

#

the reason it is maxlen of 50 is because the deque is updated per frame.

loud trail
loud trail
#

i'd rather not, sorry

fallen breach
#

okay so basically I have two lists one with a serie of numbers and the second with the time associated

#

I asked how to split for the numbers and now I have to split for the time and then substract

#

for example : [7112],[7212] and the time associated [0,1,2,3],[4,5,6,7] and then I have to substract the second list ( there's a lot of number in the file ) [0,1,2,3],[4-4,5-46-4,7-4] @loud trail

loud trail
#

you want to subtract the first number in a list from every number in the list?

#

are these lists, or numpy arrays?

tranquil vigil
#

Is there anyone who can mentor me?

#

I'm beginners rn

ashen forge
ashen forge
lean spruce
#

After typing yes in input?

loud trail
#

@lean spruce you'd have to put the entire thing in another while loop

loud trail
#

sure, something like that

#

maybe it's a good idea to put your entire game into a function

#
def run_game():
    ...

def ask_yn(prompt):
    ask_repeat = True
    while ask_repeat:
        user_val = input(prompt).strip().lower()
        if user_val == 'n':
            return False
        elif user_val == 'y':
            return True
        else:
            print('That is not a valid response.')

def main():
    play_game = True
    while play_game:
        run_game()
        play_game = ask_yn("Play again? y/n: ")
        if play_game:
            print('Again!')
    print('Goodbye!')

something like this

lean spruce
#

oke

#

thanks

grizzled hemlock
#

Does anyone have a good article where I can learn about algorthims in terms of N+1 , N(0), etc...?

#

please ping me if you do! 🙂

ashen forge
grizzled hemlock
#

Thanks for your recommendations 🙂

grizzled hemlock
austere sparrow
#

No, that's not correct O-notation

grizzled hemlock
#

What term am I looking for that would explain N+1 complexities?

austere sparrow
#

Did you find that somewhere?

#

Maybe you are referring to the 'N+1 problem'?

grizzled hemlock
#

Algorithms that suffer from N+1 , sorry I'm a bit of a noobie with time complexity.

grizzled hemlock
#

Is that just how it's referred to, N+1?

austere sparrow
grizzled hemlock
#

Gotcha understood

ashen forge
grizzled hemlock
ashen forge
#

Time complexity is integral part of DSA

#

I learnt it from geeksforgeeks

grizzled hemlock
#

Yeah I just visited the many articles they have about time complexity

#

super useful stuff, thank you 👍

fervent saddle
#

It’s what type of line you’d see if you graphed how long something took vs how much data you have

#

So finding the length of a list is a flat horizontal line, it’s O(1), since lists keep track of their length

#

And finding the index position of something in an unsorted list would be a flat diagonal line, it would be O(n)

#

Like if the x axis was how much data you have, and the y axis was how long it took to do it

#

That’s why constant factors don’t matter for finding something’s time complexity

#

Because it doesn’t change what kind of line you see

grizzled hemlock
#

I see

grizzled hemlock
fervent saddle
#

Then you could use binary search

#

I mentioned it being unsorted so it’s clear that I’m talking about linear search and not binary search

grizzled hemlock
#

what notation would binary searches be?

fervent saddle
#

O(log(n))

fiery cosmos
#

Hey anyone who can code discord bots. I am willin to pay or do what ever you want. I just want my own discord bot for my discord server..

sturdy crest
#

why do we have gaming flag at the background?

sturdy crest
cinder wigeon
stiff oyster
#

Hello there, I'm not sure were to ask. I try to build a data line graph with dash and plotly. The CSV sadly seperats the date in two rows: Date and Time. Is there an easy way to combine this rows with panda? So i can display the datetime on my x scale?

gilded kernel
#

hi

#

py

import random
word_list = ["aardvark", "baboon", "camel"]

chosen_word = random.choice(word_list)

print (chosen_word)
guess = input("chose a word ").lower()

display = ['-']
for i in chosen_word:
    if guess==i:
        print(guess)
    else:
        print(display)
#

how can i print my output vertically

#

please teach me am new to python

cerulean elk
last fulcrum
#

Each cell of an array must use the same number of bytes. This is true in statically typed languages like C, since I have to do
int data[100]; so everything in memory would be the same since they are all int's. In Python, the language is dynamically typed, so I can do list_1 = ['a', 'b', 4, 4, 4.0]. An int, a character and a float would all take up different spaces in memory, so how does the statement work in Python?

west hollow
#

Hello!

austere sparrow
#

In C, int data[100] creates a contiguous chunk of 400 bytes, and all the ints are stored in that chunk. However, you can make an array of pointers: char* strings[100]. Now you have an array of 100 strings, but the array itself only stores the memory addresses of where each string begins.

jaunty cave
fiery cosmos
#

Can someone suggest me a good python data structures algorithm book or video tutorials?

austere sparrow
#

No, you don't, const just means that you can't change something.

last fulcrum
austere sparrow
last fulcrum
#

Click on my profile. And yes it makes sense

unborn sundial
#

!e

import contextlib

@contextlib.contextmanager
def withandler(var):
    try:
        print("start stuff")
        yield var
    finally:
        print("finish stuff")


with withandler("123") as var:
    print(f"do stuff = {var}")
halcyon plankBOT
#

@unborn sundial :white_check_mark: Your eval job has completed with return code 0.

001 | start stuff
002 | do stuff = 123
003 | finish stuff
unborn sundial
#

more decorators to the throne of decorators

loud trail
#

!e ```python
import contextlib

@contextlib.contextmanager
def withandler(var):
print("start stuff")
try:
yield var
finally:
print("finish stuff")

with withandler("123") as var:
print(f"do stuff = {var}")

i'd do it like this
halcyon plankBOT
#

@loud trail :white_check_mark: Your eval job has completed with return code 0.

001 | start stuff
002 | do stuff = 123
003 | finish stuff
hollow skiff
last fulcrum
#

@austere sparrow can you help me explain this. The part of the referential structure.

Most significantly, the overall memory usage will be much lower for a compact structure because there is no overhead devoted to the explicit storage of the sequence of memory references (in addition to the primary data). That is, a referential structure will typically use 64-bits for the memory address stored in the array, on top of whatever number of bits are used to represent the object that is considered the element.

jaunty cave
# austere sparrow No, you don't, `const` just means that you can't change something.

Yes thats the only way to make array of strings from array of char pointer without warning after compiling. This is happening when g++ is used as compiler. To make array of string that is editable, u have to make 2 dimensional array of char, not array of char pointer.

const char* strings1[100];     //this is non-editable
char strings2[100][101];       //this is editable
austere sparrow
# jaunty cave Yes thats the only way to make array of strings from array of char pointer witho...

If you make a char* strings1[100], the strings will be perfectly editable, it's just that you can't put read-only strings into it.
A string literal like "Hello!" will point into a read-only part of memory, and not create a new string on the heap or the stack.
This: ```c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main() {
char* strings[2];

char* hello = malloc(strlen("Hello!") + 1);
strcpy(hello, "Hello!");
char* world = malloc(strlen("world") + 1);
strcpy(world, "world");

strings[0] = hello;
strings[1] = world;
printf("%s %s\n", strings[0], strings[1]);

free(hello);
free(world);

}

#

(also, g++ is for C++, not C)

last fulcrum
austere sparrow
last fulcrum
austere sparrow
last fulcrum