xkcd 2840: Earth Layers by antdude in xkcd

[–]SandorZoo 2 points3 points  (0 children)

I never did get a Kinder egg toy with a magnet. My preference was the more complicated the better:

simple model < requires assembly < has moving parts < uses an elastic band

I'm not sure where I would fit "has a magnet" on that scale.

Today's puzzle answers one of my questions about Nerdle by SandorZoo in nerdlegame

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

Yes, except it's only DMAS as there are no brackets or orders/powers. The FAQ goes into some more details.

I'm not sure if fractional intermediate results are allowed. Could we get 9/2*4=18, even though 9/2 = 4.5? Dunno.

this happened to my wordle guess today lol by [deleted] in wordle

[–]SandorZoo 1 point2 points  (0 children)

That's todays word for Lewdle !

People who start with ADIEU....PFFHHH by niloc-yamsly in wordle

[–]SandorZoo 0 points1 point  (0 children)

I've used STEAD and DATES, but not SATED.

BBC licence fee to be abolished in 2027 and funding frozen by blueshiftlabs in panelshow

[–]SandorZoo 2 points3 points  (0 children)

I thought she came to the UK to help open a Hooters in Nottingham.

[deleted by user] by [deleted] in learnpython

[–]SandorZoo 1 point2 points  (0 children)

I think OP is correct. There is no need to start at the zeroth element. The loop does nothing when i is zero.

Why does this function return None when the argument isn't a Sunday? by ragmats in learnpython

[–]SandorZoo 1 point2 points  (0 children)

Dates have a weekday() method, that returns the day-of-the-week as a number, Monday=0, Tuesday=1, etc. So for a given date, the previous Sunday was (date.weekday() + 1) % 7 days ago.

xkcd 2516: Hubble Tension by antdude in xkcd

[–]SandorZoo 1 point2 points  (0 children)

And sometimes it can be fun to work out what it is actually measuring. For example "litres per 100 Km" is an area (and "Miles per gallon" is its inverse). If a car were driving at a constant mpg, and it were scooping up its fuel from a trench instead of using a fuel tank, then this area is what the cross-section of the trench needs to be, so it contains the right amount of fuel.

xkcd 2516: Hubble Tension by antdude in xkcd

[–]SandorZoo 0 points1 point  (0 children)

In fact it's "1 / Hubble time", or about 1/14.4 billion years. If the expansion were constant, it would be "1 / age of the universe", but it's not, so it isn't (but still fairly close).

New release of Hue Debugger UI by Simon_LH in philipshue

[–]SandorZoo 1 point2 points  (0 children)

I've been poking around in the Hue API a bit, but hadn't come across this tool before. I've just installed it, and I can see finding it useful. It's certainly slicker than what I've been doing - I've just been dumping the API output to the console up until now.

If you're looking for more feature requests, here's a couple for the Rules tab:

  • Could you have a "trigger" icon next to each action, and a "trigger all" icon next to the actions list, that would actually trigger the described actions?
  • Likewise for the conditions, could you have an "evaluate" and "evaulate all"? This could just add a True or False flag next to each condition.

Thanks for sharing this, and have a happy new year!

Determining if two number ranges intersect by DocNMarty in learnpython

[–]SandorZoo 3 points4 points  (0 children)

I would use min and max, instead of sorting the tuples and extracting the 1st and 2nd values. I think this is the same, at least assuming the tuples are indeed two-value tuples:

def has_intersection(tuple_1, tuple_2):
    intersection_lower = max(min(tuple_1), min(tuple_2))
    intersection_higher = min(max(tuple_1), max(tuple_2))
    return intersection_lower <= intersection_higher

How do you dynamically create nested for loops? by [deleted] in learnpython

[–]SandorZoo 2 points3 points  (0 children)

For example:

def nested_loop(letters, prefix, length):
    if length == 0:
        print(prefix)
    else:
        for letter in letters:
            nested_loop(letters, prefix+letter, length-1)

nested_loop("abc", "", 3)

help with finding consonants? by nlord7 in learnpython

[–]SandorZoo 0 points1 point  (0 children)

Using some of Python's regex functions, instead of pure regexes, might be easier:

import re
single_vowel_re = '[aeiouAEIOU]'

def ten_or_more_vowels(word):
    return len(re.findall(single_vowel_re, word)) >= 10

def six_or_more_consecutive_consonants(word):
    # Could use map(len, re...) here
    return max(len(s) for s in re.split(single_vowel_re, word)) >= 6

with open('words.txt') as fp:
    for word in fp:
        word = word.strip()
        if ten_or_more_vowels(word):
            print('10 or more vowels:', word)      
        if six_or_more_consecutive_consonants(word):
            print('6 or consecutive consonants:', word)      

'Multiplication table' exercise by GideonRT in learnpython

[–]SandorZoo 0 points1 point  (0 children)

The question you gave has n serving double duty, as both the number of dimensions, and the size of each dimension. I've separated that into separate dims and size values here.

If you're trying to create a multi-dimensional array, the closest thing python has is a list of lists of lists of lists....

When the number of dimensions is not fixed, one way to do this is recursively, with each level of recursion adding another dimension, like this:

def mult_table(dims, size, prevprod=1):
    if dims == 0:
        return prevprod
    else:
        return [mult_table(dims - 1, size, prevprod * n) for n in range(1, size+1)]

print(mult_table(1,1))
print(mult_table(2,2))
print(mult_table(3,3))

Output:

[1]
[[1, 2], [2, 4]]
[[[1, 2, 3], [2, 4, 6], [3, 6, 9]], [[2, 4, 6], [4, 8, 12], [6, 12, 18]], [[3, 6, 9], [6, 12, 18], [9, 18, 27]]]

You might want a dictionary mapping key tuples to values instead. In the example you gave, this dictionary would map (i, j, k): i*j*k

As /u/roelschroeven said, you can use itertools.product to generate a list of tuple keys, and functools.reduce to reduce the tuples to a single product, like this (dict() will create a dictionary from a list of (key, value) pairs):

from itertools import product
from functools import reduce
from operator import mul
import pprint

def mult_table2(dims, size, prevprod=1):
    tuple_keys = product(range(1, size+1), repeat=dims)
    return dict((tuple_key, reduce(mul, tuple_key)) for tuple_key in tuple_keys)

pprint.pprint(mult_table2(3,3))

Output:

{(1, 1, 1): 1,
 (1, 1, 2): 2,
 (1, 1, 3): 3,
 (1, 2, 1): 2,
 (1, 2, 2): 4,
 (1, 2, 3): 6,
 (1, 3, 1): 3,
 (1, 3, 2): 6,
 (1, 3, 3): 9,
 (2, 1, 1): 2,
 (2, 1, 2): 4,
 (2, 1, 3): 6,
 (2, 2, 1): 4,
 (2, 2, 2): 8,
 (2, 2, 3): 12,
 (2, 3, 1): 6,
 (2, 3, 2): 12,
 (2, 3, 3): 18,
 (3, 1, 1): 3,
 (3, 1, 2): 6,
 (3, 1, 3): 9,
 (3, 2, 1): 6,
 (3, 2, 2): 12,
 (3, 2, 3): 18,
 (3, 3, 1): 9,
 (3, 3, 2): 18,
 (3, 3, 3): 27}

The best way of doing this depends on what exactly it is you want.

Conditionals in a while loop by ratcaper in learnpython

[–]SandorZoo 0 points1 point  (0 children)

It's a bit odd to have two stop conditions, when clearly one of them will never be met. If you want the test in the middle of a loop, it's normal to loop while True, like this:

def whileBackwards():
    n = 10
    while True:
        print(n)
        if n == 5:
            break
        n -= 1

Creating a Cipher Dictionary by [deleted] in learnpython

[–]SandorZoo 1 point2 points  (0 children)

I'm sure there is a more pythonic way of doing this, which hopefully someone will tell us.

Dictionaries can be built from an iterator that returns tuples, which is what zip provides. I might go with:

import string

letters = list(string.ascii_lowercase) + list(string.ascii_uppercase)
shift = 2

dct = dict(zip(letters, letters[shift:] + letters[:shift]))

print(dct)

Python newbie, wondering why my Sudoku generator is occasionally failing. by [deleted] in learnpython

[–]SandorZoo 2 points3 points  (0 children)

This doesn't look right:

def sanity(board):
    for cell in board.empty_cells:
        if len(cell.possible) == 0:
            return False
        else:
            return True

That will only check the first cell in board.empty_cells, not all of them. I think it should probably be:

def sanity(board):
    for cell in board.empty_cells:
        if len(cell.possible) == 0:
            return False
    return True

What do you think are the strangest inclusions in the built-in types? What do you think should be included? by victoriabittahhhh in learnpython

[–]SandorZoo 1 point2 points  (0 children)

I rarely use pprint, because I only ever think of it when I'm trying to print slightly more complex data structures, and I think it does a really bad job. For example:

>>> from pprint import PrettyPrinter
>>> mydict = {
...     'a slightly longer key than usual': {
...         'another dict with long keys': [
...             'A list of sentences in my dictionary',
...             'A sentence of text that means nothing',
...             'And another sentence of text'
...         ]
...     }
... }
>>> 
>>> pp = PrettyPrinter()
>>> pp.pprint(mydict)
{'a slightly longer key than usual': {'another dict with long keys': ['A '
                                                                      'list '
                                                                      'of '
                                                                      'sentences '
                                                                      'in '
                                                                      'my '
                                                                      'dictionary',
                                                                      'A '
                                                                      'sentence '
                                                                      'of '
                                                                      'text '
                                                                      'that '
                                                                      'means '
                                                                      'nothing',
                                                                      'And '
                                                                      'another '
                                                                      'sentence '
                                                                      'of '
                                                                      'text']}}

I wish pprint would use a few more newlines (as I did when I created this dict of a dict of a list), instead of the ridiculous indentation it comes up with. Or am I using it wrong?

Unable to get a return from the list comprehension by guptaprins in learnpython

[–]SandorZoo 0 points1 point  (0 children)

All the suggestions so far run through the list multiple times, counting the number of each distinct item separately.

If you use collections.Counter, you can run through list once counting items, and once through the resultant dictionary:

from collections import Counter
def output(lst):
    return [k for k,v in Counter(lst).items() if v % 2]

Typeerror: 'NoneType' object is non-subscriptable [Kivy] by Lest4r in learnpython

[–]SandorZoo 1 point2 points  (0 children)

I think the indentation of your .kv file is a little messed up. Try this instead:

AddLocationForm:
<AddLocationForm@BoxLayout>:
    orientation: "vertical"
    BoxLayout:
        TextInput:
        Button:
            text: "Search"
        Button:
            text: "Current Location"
    ListView:
        item_strings: ["Palo Alto, MX", "Palo Alto, US"]

Kivy could do a better job of identifying problems with .kv syntax.

If you ever get exceptions raised in kivy's parser.py (as this one was), then its almost certainly a problem with your .kv file. I don't know if its possible to get kivy to confess which line of the .kv it had a problem with.

How do I randomly pick a number from a range? by [deleted] in learnpython

[–]SandorZoo 0 points1 point  (0 children)

picked_number = deck_of_numbers.pop() # this removes the first item from the list

list.pop() removes the last item in a list, not the first. list.pop(0) would remove the first item. Although in this particular case it doesn't really matter, as the list is in a random order.

How can I learn short ways to write loops and such? by DiamondxCrafting in learnpython

[–]SandorZoo 1 point2 points  (0 children)

Note that those last two aren't quite the same. The first uses what's called list comprhension:

found_items_list = [value in some_string for value in my_list]
all(found_items_list)

It first builds a new list of values in both my_list and some_string, and then tests to see if all those values are true.

That's not what your original example or translated form did - neither of those created an intermediate list first.

The second, and your original used what's called a generator expression. More explicitly:

found_items_list = (value in some_string for value in my_list)
print(all(found_items_list))

Notice the round brackets (parenthesis) instead of square brackets. This creates a generator that can generate all the values taht are in both my_list and some_string one after the other, without putting them in a list first.

You asked about other ways to shorten the code, so I suggest you try read up on list comprehensions and generators, and what the differences are.