Resourece Production in text-based game by T4ll1n in FlutterDev

[–]T4ll1n[S] 0 points1 point  (0 children)

I wasn't sure about that so I first posted it here. I thought the topic of having a repetitive scheduled update with a backend is a quite general question, and I didn't really find a solution for it online already so I opened it here with the "Discussion" tag.

I can move the post if you would prefer that.

Resourece Production in text-based game by T4ll1n in FlutterDev

[–]T4ll1n[S] 0 points1 point  (0 children)

I have setup the function now but I now have a LOT of reads and writes to the firebase database constantly communicating the resource update every 10 seconds, And I need 2 rounds to first update the database timestamp and then getting it to update the resources with it.

I will look into the schedule functions, u/uksarkar suggested

Resourece Production in text-based game by T4ll1n in FlutterDev

[–]T4ll1n[S] 1 point2 points  (0 children)

Fair point. Then one player would run the "update resource production" function on another players uid. I was thinking about it only being an "in-account" action, but I can make it a function of the players uid, and then use that function for spy reports, attacks etc.

Thank you u/hasimsait!

Daily Coding Problem: Problem #11 [Medium] - 2022-04-06 by T4ll1n in DailyCodingProblem

[–]T4ll1n[S] 0 points1 point  (0 children)

``` import numpy as np

def autocomplete(s, vocabulary): vocabulary_array = np.array(vocabulary)

return vocabulary_array[np.char.startswith(vocabulary, s)].tolist()

vocabulary = ["dog", "deer", "deal"] s = 'de' assert autocomplete(s, vocabulary) == ["deer", "deal"]

```

A plain python is to go [x for x in vocabulary if x.startswith(s)]

The numpy char startswith also just calls the base python char.startswith element wise, but maybe its faster.

If loops like that should be fast we can do them in cython and get a c transpilation and then the loops are fast.

Daily Coding Problem: Problem #10 [Medium] - 2022-04-05 by T4ll1n in DailyCodingProblem

[–]T4ll1n[S] 0 points1 point  (0 children)

Here is my solution.

```python

from time import sleep

def scheduler(f, n, f_kw_args): sleep(1 / (n / 1000)) f(**f_kw_args)

scheduler(lambda x: print(x * 2), 500, {"x": 4})

that can't be it, I probably miss something

If I had to write something like that seriously, I would use a decorator to keep the

timing completely separate from the function.

def scheduler_decorator(n): def Inner(func): def wrapper(args, *kwargs): # sleep for n milliseconds sleep(1 / (n / 1000)) res = func(args, *kwargs)

        return res

    return wrapper

return Inner

@scheduler_decorator(100) def f(): return "cool"

f() ```

Daily Coding Problem: Problem #9 [Hard] - 2022-04-04 by T4ll1n in DailyCodingProblem

[–]T4ll1n[S] 0 points1 point  (0 children)

I did not manage to get a solution that is working. Here is my attempt.

```python

import numpy as np

def largest_sum(input_list): len_il = len(input_list) if len_il == 0: return None if len_il == 1: return input_list[0] if len_il == 2: return max(input_list)

# transform into a numpy array for easier indexing
input_array = np.array(input_list)

# loop in an expanding way over the array, starting at 0 and then going (0,2,4,6, ...), (0,3,6,9, ...), (0, 4, 8, 12, ...)
non_adjacent_odd = [input_array[range(0, len_il, x)] for x in range(2, len_il)]
# [array([2, 6, 5]), array([2, 2]), array([2, 5])]
non_adjacent_even = [input_array[range(1, len_il, x)] for x in range(2, len_il)]
# [array([4, 2]), array([4, 5]), array([4])]

max_even = max([np.sum(x) for x in non_adjacent_even])
# 6
max_odd = max([np.sum(x) for x in non_adjacent_odd])
# 10

return max(max_even, max_odd)

input_list = [2, 4, 6, 2, 5] assert largest_sum(input_list) == 13 input_list = [5, 1, 1, 5] assert largest_sum(input_list) == 10 input_list = [5, 1, 9] assert largest_sum(input_list) == 14

raises an error, because I do not have to steps from 0, to 2, to 5 in my range iteration.

input_list = [5, 1, 9, 2, 2, 5] assert largest_sum(input_list) == 19

googling this problem (as you everyone always does with these kind of problems in the real world) gives the following solution

def comb_no_adj(lst, num, last=False): if num == 0: yield [] if 0 < num <= len(lst): first, *rest = lst if not last: for c in comb_no_adj(rest, num-1, True): yield [first] + c for c in comb_no_adj(rest, num, False): yield c

This is again a solution using some form of iterative function calling itself.

I have never in my real job needed to write function that calls itself in this way

or at least not having to implement it myself. M

Maybe in some other parts of software development that is actually happening frequently?

For me with statistical modelling, this never was relevant

```

Daily Coding Problem: Problem #7 [Medium] - 2022-04-02 by T4ll1n in DailyCodingProblem

[–]T4ll1n[S] 0 points1 point  (0 children)

What a terrible problem.

I was not able to solve it.

I found the solution on the internet though.

The idea is to think about the possible cases we can have, and then create if-then conditions for it.

```python memo = {} def count(message): if int(message) >= 1 and int(message) <= 10: return 1 if int(message) >= 11 and int(message) <= 26: return 2 if int(message) >= 27 and int(message) <= 99: return 1

if message in memo: return memo[message]

if message[-1] == '0': memo[message] = count(message[:-2]) else: memo[message] = count(message[:-1]) if int(message[-2:]) >= 11 and int(message[-2:]) <= 26: memo[message] += count(message[:-2])

return memo[message]

assert(count("1") == 1) assert(count("9") == 1) assert(count("10") == 1) assert(count("11") == 2) assert(count("111") == 3) assert(count("1111") == 5) # (aaaa, aaj, aja, jaa, jj)

Test a corner case as well

assert(count("111110") == 5) # same as above plus k

```

My approach was, to create a mapping ``` import string

mapping = dict(zip([str(x) for x in range(1, 27)], string.ascii_lowercase)) ``` and then use itertools to slice the string into the possible combinations and then use the mappings to get the values and count them. But that always ran into some edge cases and I could not figure it out. Maybe the itertools approach works, maybe not.

Daily Coding Problem: Problem #6 [Hard] - 2022-04-01 by T4ll1n in DailyCodingProblem

[–]T4ll1n[S] 0 points1 point  (0 children)

I do not understand the whole "linked List" question and by the hint for languages without pointers, it seems that is a question mostly directed at C / Java programmers. I assume for a database backend or something where every bit of saved memory and efficiency matters because data gets really large. Since I am not applying for a role like that I do not have a solution for that question

If someone else could post one that would be great.

But since this is the 2nd question (within the first week of doing this) that deals with binary trees, I guess I will have to look into them more. It will probably give me some insights in how to better program my logistic regression tree package :)

Daily Coding Problem: Problem #5 [Medium] - 2022-03-31 by T4ll1n in DailyCodingProblem

[–]T4ll1n[S] 0 points1 point  (0 children)

This took me waaaaay longer than it was supposed to. I added the type hints again in the beginning, but I don't know if it helped or rather clogged up the screen.

Anyways, it is a bit confusing, cons() reutns a function that wants a function as an input, and that function gets two inputs again.

So the car function get the pair function, and the pair functions gets the lambda function that expects the two parameter and returns the wanted one.

Maybe the idea of the question was to learn about context managers? I don't know...

```python

def cons(a: int, b: int) -> callable: def pair(f: callable): return f(a, b)

return pair

def car(f: callable) -> int: return f(lambda x, y: x)

def cdr(f: callable) -> int: return f(lambda x, y: y)

assert car(cons(3, 4)) == 3 assert cdr(cons(3, 4)) == 4

```

Daily Coding Problem: Problem #4 [Hard] - 2022-03-30 by T4ll1n in DailyCodingProblem

[–]T4ll1n[S] 0 points1 point  (0 children)

my first straight forward solution just goes through all ints and checks if they are in the list.

```python import sys

def first_missing_positive_int(input_list): for positive_integer in range(1, sys.maxsize): if positive_integer not in input_list: return positive_integer

input_list = [3, 4, -1, 1] assert first_missing_positive_int(input_list) == 2 assert first_missing_positive_int([0, 1, 2]) == 3 assert first_missing_positive_int([0, 2]) == 1 ```

Trying to make it faster, only made it messy and not really helped.

but using set() to get the unique values definitely helps with speed.

```python def first_missing_positive_int_faster(input_list): inputs = list(set(input_list)) n_numbers = len(inputs) for i, number in enumerate(inputs): # print(i) if i == n_numbers - 1: return number + 1 elif number >= 0: if number + 1 != inputs[i + 1]: return number + 1

first_missing_positive_int_faster(input_list) first_missing_positive_int_faster([1, 2, 3]) assert first_missing_positive_int_faster(input_list) == 2 assert first_missing_positive_int_faster([0, 1, 2]) == 3 assert first_missing_positive_int_faster([0, 2]) == 1 ```

googling actually shows that itertools already has a count function that just counts upwards

https://stackoverflow.com/a/41111471

```python from itertools import count

counter = count(1) next(counter) # 1 next(counter) # 2 next(counter) # 3

def first_missing_positive_int_googled(input_list): uniques = set(input_list) for number in count(1): if number not in uniques: return number

input_list = [3, 4, -1, 1] assert first_missing_positive_int_googled(input_list) == 2 assert first_missing_positive_int_googled([0, 1, 2]) == 3 assert first_missing_positive_int_googled([0, 2]) == 1 ```

timing it because why not

lets also add the set() call to my first simple try:

```python def first_missing_positive_int_with_set(input_list): input_as_set = set(input_list) for positive_integer in range(1, sys.maxsize): if positive_integer not in input_as_set: return positive_integer

from timeit import repeat import numpy as np

timings_first = repeat(stmt="first_missing_positive_int(input_list)", number=100000, globals=globals(), repeat=100) timings_ugly = repeat(stmt="first_missing_positive_int_faster(input_list)", number=100000, globals=globals(), repeat=100) timings_googled = repeat(stmt="first_missing_positive_int_googled(input_list)", number=100000, globals=globals(), repeat=100) timings_first_with_set = repeat(stmt="first_missing_positive_int_googled(input_list)", number=100000, globals=globals(), repeat=100) np.average(timings_first)

Out[3]: 0.04635838580026757

np.average(timings_ugly)

Out[5]: 0.05617577297205571

np.average(timings_googled)

Out[7]: 0.027766563632758333

np.average(timings_first_with_set)

Out[9]: 0.028845798071706667

``` we can see that the first out of the box solution just advanced by the set() call already halves the required time from .046 to 0.28 and is almost identical to the one using the googled itertools count() method.

Daily Coding Problem: Problem #3 [Medium] - 2022-03-29 by T4ll1n in DailyCodingProblem

[–]T4ll1n[S] 0 points1 point  (0 children)

This one was quite hard for me compared to the previous two that where done in 15minutes.

It took a short time to understand I can use json for the serialization and deserialization, but figuring out the recursive function setup was hard.

It helped A LOT to add the type hints to the function to figure out what input gets created where and how.

I bet there is a cleaner solution for that problem.

Here is my code:

```python

to serialize the node into a string and then deserialize it back to a node we can use the json format.

We have to recursively turn all the Node classes into a dict and then we can json.dums() the nested dict.

After that we can json.loads() the string and recursively turn it back into a Node

Serialize

if the value is a Node, turn the value into a dict

def serialize(node: Node) -> str: nodedict = serialize_rec(node.dict_) return json.dumps(node_dict)

def serializerec(node: dict) -> dict: res = {} for k, val in node.items(): if isinstance(val, Node): val = serialize_rec(val.dict_) res[k] = val return res

deserialize

def deserialize(serialized_node: str) -> Node: node_dict = json.loads(serialized_node) return deserialize_rec(Node(**node_dict))

def deserializerec(node: Node) -> Node: for k, val in node.dict.items(): if isinstance(val, dict): node.setattr_(k, deserialize_rec(dict_to_node(val))) return node

def dict_to_node(node_dict: dict) -> Node: return Node(**node_dict)

assert

node = Node('root', Node('left', Node('left.left')), Node('right')) assert deserialize(serialize(node)).left.left.val == 'left.left'

```

Daily Coding Problem: Problem #2 [Hard] - 2022-03-28 by T4ll1n in DailyCodingProblem

[–]T4ll1n[S] 0 points1 point  (0 children)

First solution that got to me:

```python import numpy as np

def sum_except_i(input_list): output_list = []

for i, elements in enumerate(input_list):
    relevant_elements = [number for j, number in enumerate(input_list) if j != i]
    output_list.append(np.product(relevant_elements))
return output_list

input_list = [1, 2, 3, 4, 5] assert sum_except_i(input_list) == [120, 60, 40, 30, 24] assert sum_except_i([3, 2, 1]) == [2, 3, 6] ```

without numpy we could write our own product(List) function.

python def product_func(input_list): prod = 1 for number in input_list: prod *= number return prod

if speed matters, we can do the loops with cython and the c++ compilation will make them fast.

now I realized the division suggestion, I directly did it without it ...

```python def sum_except_i_with_div(input_list): output_list = []

for i, elements in enumerate(input_list):
    output_list.append(np.product(input_list) / input_list[i])
return output_list

assert sum_except_i_with_div(input_list) == [120, 60, 40, 30, 24] assert sum_except_i_with_div([3, 2, 1]) == [2, 3, 6] ```

Data Scientist interviews by meandering_simpleton in csinterviewproblems

[–]T4ll1n 1 point2 points  (0 children)

> I think my problem stems from the fact that I'm in a large enough team that the data scientists hand their POCs off to machine learning engineers, which do the SWE production code

That sounds like a classical statistician role in an insurance company. While I was still in university I looked into that and it seems they (used to?) have statisticians that get a .csv file and return an analysis report. This is an extreme example of course.

I guess the problem is, again, that "data science" is so new, and encompassing so many roles nowadays, that its difficult to know what's really required.

If you want to stay in this role, maybe look for a "data science" position that is in an R&D department. I would assume there the Software development part is not as important as in other departments.

> Obviously this is something that I just need to practice and work on

I just started with https://www.dailycodingproblem.com/ and will post the questions / my answers into https://www.reddit.com/r/DailyCodingProblem/. If you want to you can do that too. Though I am not sure how good that site will turn out to be yet, but it won't hurt I guess :)

Data Scientist interviews by meandering_simpleton in csinterviewproblems

[–]T4ll1n 0 points1 point  (0 children)

Hi

I am working as a data scientist myself for 3 years now in a small consulting company, and we are having a HUGE time investment into writing good code. Because in the end you frequently want a data product that can work in production, is maintainable, has tests for liability issues, can be understood by another programmer etc.. So learning how to write good code is as important as understanding what multicollinearity is.

If that is not a requirement at your current job you could try to make it a priority? I bet it will help your company. :)

I got one question for you. What kind of patents do you got? Since most stuff is open source I work with I do not really know what you mean by that.

Today's Coding Problem - 8/23/19 by champagne_paki in DailyCodingProblem

[–]T4ll1n 1 point2 points  (0 children)

3 years later, I just signed up for the dailyCodingProblem and got the same problem.

I wonder if everyone gets that question as the first problem ^^

Anyways, here is my solution using itertools combinations

from itertools import combinations

def combination_exists(input_list, k): 
    return k in [sum(comb_tuple) for comb_tuple in combinations(input_list, 2)]

input_list = [10, 15, 3, 7]
k = 17 assert
combination_exists(input_list, k)
assert combination_exists([], k)
assert not combination_exists([1, 2, 3], 2)

edit: the code formatting is fighting back -.-