Go deh!

Mainly Tech projects on Python and Electronic Design Automation.

Thursday, December 28, 2023

How not to check for a key in a dictionary.

 I skim the Linkedin Python group and sometimes comment.

A few days there was a poll asking for the way to check if a key is in a Python dictionary and as I write, more than half of the 900+ respondents have chosen dict.get rather than key in dict, which is the correct answer!

When pushed, it seems they are relying on dict.get returning None if the key is not in the dict, but fail to see tha if the key being tested is in the dict, but has a value of None then their test fails. 

Here's some code:

# %%
mydict1 = {'a': 1, 'b': 2}
print(mydict1.get('c'))  # -> None

# %%

def key_in_dict1(key_, dict_: dict) -> bool:
    "FAULTY IMPLEMENTATION"
    return dict_.get(key_) != None

# This works
mydict1 = {'a': 1, 'b': 2}
print(key_in_dict1('a', mydict1))  # -> True
print(key_in_dict1('x', mydict1))  # -> False
# %%

# But adding a key of x with value None gives
# the wrong result
mydict2 = {'a': 1, 'b': 2, 'x': None}
print(key_in_dict1('x', mydict2))  # -> False

# %%

# The correct way is to use 'in'
def key_in_dict2(key_, dict_: dict) -> bool:
    "Pythonic IMPLEMENTATION"
    return key_ in dict_

# Tests:
print(key_in_dict2('a', mydict1))  # -> True
print(key_in_dict2('x', mydict1))  # -> False

# %%

# And now for keys with None as a value:
print(key_in_dict2('x', mydict2))  # -> True


Ugly, code-golf solution using dict.get()

You can alter the default value returned from dict.get if a key is not found. This allows one to use two calls of dict.get with different defaults  to be used to give a correct solution:

def key_in_dict3(key_, dict_: dict) -> bool:
    "CODE-GOLF IMPLEMENTATION USING GETs"
    default1 = None
    default2 = ""
    return default1 != default2 \
        and ( dict_.get(key_, default1) != default1
             or dict_.get(key_, default2) != default2)

# Tests:
print(key_in_dict3('a', mydict1))  # -> True
print(key_in_dict3('x', mydict1))  # -> False
print(key_in_dict3('x', mydict2))  # -> True



Of course, don't use  key_in_dict3, use version 2, i.e. key in dict.

END.

Friday, November 24, 2023

Google Bard vs Microsoft Bing Chat: Vanity questions

 I ask two questions about my activities online and compare the outputs from the two AI tools.


Google Bard

 


Sure, here is a Rosetta Code task in the style of user paddy3118:

Task:

Write a program that generates the Godeh series. The Godeh series is an infinite sequence of integers that is defined by the following recursive formula:

godeh(n) = {
  1, if n = 1
  godeh(n // 2), if n is even
  godeh(n // 2) + godeh(n // 2 + 1), if n is odd
}

Input:

An integer n.

Output:

The first n terms of the Godeh series.

Example:

Input: 10

Output:
1
1
2
1
3
2
3
1
4
3

Solution:

Python
def godeh(n):
  if (n == 1):
    return 1
  elif (n % 2 == 0):
    return godeh(n // 2)
  else:
    return godeh(n // 2) + godeh(n // 2 + 1)

n = 10
for i in range(1, n + 1):
  print(godeh(i))

Paddy3118's style:

Paddy3118's programs are typically well-written and easy to understand. They are also often accompanied by clear and concise explanations of the code. In this task, Paddy3118 would likely provide a brief explanation of the Godeh series and the recursive formula used to define it. He would then provide a Python implementation of the program, along with an example of how to use it.

Here is an example of a task that Paddy3118 might write:

Task:

Write a program that generates the prime numbers up to a specified input.

Input:

An integer n.

Output:

A list of all the prime numbers up to n.

Example:

Input: 100

Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Solution:

Python
def is_prime(n):
  if (n <= 1):
    return False
  if (n <= 3):
    return True
  if (n % 2 == 0or n % 3 == 0):
    returnFalse
  i = 5while (i * i <= n):
    if (n % i == 0or n % (i + 2) == 0):
      returnFalse
    i += 6returnTruedefprime_numbers_up_to(n):
  primes = []
  for i inrange(2, n + 1):
    if (is_prime(i)):
      primes.append(i)
  return primes

n = 100
primes = prime_numbers_up_to(n)
print(primes)

 

Microsoft Bing Chat

create a rosettacode.org task in the style of user paddy3118

 
 
 
 


 Bard vs Bing

The actual formatting does not copy-paste well in either case.
  • Bard attempts to write a task in my style, and gives some tips on my style.
  • Bing cannot create the task, but does extract some info on me.
  • Clearly a Bard win.
  • Flattery will get them nowhere! (But keep it up mind you).

 

 

Google Bard #2

what does paddy3118 do online?

Paddy3118 is an active participant in the online programming community, particularly in areas related to mathematics and algorithms. They have authored numerous programs and solutions to coding challenges, demonstrating expertise in various programming languages and problem-solving techniques. Paddy3118's contributions can be found across various platforms, including:

GitHub: Paddy3118 has a notable presence on GitHub, where they have authored over 50 programs covering a wide range of topics, including:

  • Mathematical algorithms: Implementing various mathematical concepts and algorithms, such as the Godeh series generator, Collatz conjecture tester, and prime number generator.

  • Problem-solving challenges: Tackling coding challenges from platforms like Codewars, showcasing their ability to solve complex problems efficiently.

  • Data manipulation and analysis: Demonstrating proficiency in handling and analyzing data through programs like the factorial calculator and Fibonacci sequence generator.

Their GitHub repositories often include detailed explanations of the code, making them valuable learning resources for other programmers.

Stack Overflow: Paddy3118 is an active contributor on Stack Overflow, a question-and-answer website for programmers. They have answered over 1,000 questions with an average score of 4.5 out of 5, indicating their deep understanding of programming concepts and their willingness to share their knowledge with others.

Codewars: Paddy3118 is a skilled competitor on Codewars, a coding challenge platform. They have solved over 1,000 coding challenges and currently rank in the top 1% of users. This achievement highlights their ability to think creatively and apply their programming expertise to solve complex problems.

GitHub Discussions: Paddy3118 actively engages in discussions on GitHub Discussions, a forum where users discuss technical topics. They provide helpful advice, share insights, and contribute to the overall knowledge base of the community.

Overall, Paddy3118 is a valuable member of the online programming community, recognized for their contributions to various platforms and their willingness to share their knowledge and expertise with others.

Microsoft Bing Chat #2

 

Bard vs Bing #2

  • Bard has found me on numerous sites and attempted to summarise my contributions to them and comments that I like to help
  • Bing states up front that it could not find me but then quotes an extract based on my RosettaCode talk page.
  • None mention Python!?!
  • Another win for Bard.
At the moment, just using these easy-access AI tools, Bard seems to give better results.

It's still early days however!

END.

 

Followers

Subscribe Now: google

Add to Google Reader or Homepage

Go deh too!

whos.amung.us

Blog Archive