I am curious if I am Code Golfing properly. I set the challenge for myself to make a small hashing program into a single statement in Python. I first started off with:
from itertools import permutations from string import ascii_lowercase from random import sample def test(): chars = sample(ascii_lowercase, 9) sums = list(map(h, permutations(chars))) if len(set(sums)) == len(sums): print("unique results for permutations of given string") else: print("duplicate entries present in test results") def h(s): r = 0 for i in range(len(s)): r += ord(s[i]) << (i * len(s)) return r test() I then made the function recursive:
def h(s, i=0): if i < len(s) - 1: return h(s, i+1) + ord(s[i]) << (i * len(s)) else: return ord(s[i]) << (i * len(s)) I tried shortening it with a lambda for repeating code (it didn't work):
def h(s, i=0, f=lambda s,i: ord(s[i]) << (i * len(s))): if i < len(s) - 1: return h(s, i+1) + f(s,i) else: return f(s,i) Finally I ended up with a lambda:
h=lambda s,i=0:h(s,i+1)+ord(s[i])<<(i*len(s))if i<len(s)-1 else ord(s[i])<<(i*len(s)) I wanted the program to be one statement, so first I came up with:
def test(): chars = sample(ascii_lowercase, 9) sums = list(map((lambda s,i=0,f=lambda s,i,f:f(s,i+1,f)+ord(s[i])<<(i*len(s))if i<len(s)-1 else ord(s[i])<<(i*len(s)):f(s,i,f)), permutations(chars))) if len(set(sums)) == len(sums): print("unique results for permutations of given string") else: print("duplicate entries present in test results") And lastly I ended up with:
print((lambda x=list(map((lambda s,i=0,f=lambda s,i,f:f(s,i+1,f)+ord(s[i])<<(i*len(s))if i<len(s)-1 else ord(s[i])<<(i*len(s)):f(s,i,f)), permutations(sample(ascii_lowercase, 9)))): "unique results for permutations of given string" if len(set(x)) == len(x) else "duplicate entries present in test results")()) Is this how codegolf problems are worked out? I've never really done this sort of thing, so right now I just want to know if I am doing it right.
Amendment: This program does all the work for you; so I will here refer to the function: As input, the program takes in all the permutations of a given string; here the string is nine characters randomly picked from ascii_lowercase. The output is a human-readable string defining whether the result of each permutation of the given string is a duplicate of another result for a different string. If there are no duplicates for all permutations, the program indicates success. Nine characters was picked as being the largest length of characters readily computed repeatedly on my box.
Amendment II As pointed out by a studious reader, the intended purpose described is not obtained through the accompanying code. The test case is obviously inadequate.
print"x"instead ofprint("x")\$\endgroup\$list()? \$\endgroup\$