zingcat
BAN USER// An example in golang using a closure.
// It simply decrements the counter on every call.
// Returns nil when the counter is zero.
// A use case is shown in the main function.
package main
import (
"fmt"
)
// Returns an iterator of obj
func Iterator(obj interface{}, n int) (func() interface{}) {
f := func() interface{} {
if n > 0 {
n--
return obj
} else {
return nil
}
}
return f
}
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name:"Bruce", Age:45}
g := Iterator(p, 5)
for v := g(); v != nil; v = g() {
fmt.Println(v.(Person))
}
}
/*
Output:
{Bruce 45}
{Bruce 45}
{Bruce 45}
{Bruce 45}
{Bruce 45}
*/
// add adds the carry carry to the digit n.
// It returns the result and the carry.
func add(n, carry int) (int, int) {
if n == 9 && carry == 1 {
return 0, 1
}
return n+1, 0
}
// add1 adds 1 to a list of single digits assuming the list as a single number.
// It returns the new list after adding.
func add1(arr []int) []int {
carry := 1
for i := len(arr)-1; i >=0; i-- {
// replace the old digit with the new digit after adding carry 1
arr[i], carry = add(arr[i], 1)
if carry == 0 {
break
}
}
// case where all digits are 9 e.g. [9, 9 , 9]
if carry == 1 {
arr = append([]int{1}, arr...)
}
return arr
}
// The idea is to start from the LMB by taking a pair of consecutive bits.
// If the consecutive bits are not equal, they are exchanged. The resulting number after
// exchange is the result.
// If the bits either all 0s or 1s, it is not applicable as all the bits are same.
// Otherwise there should be atleast a pair of consecutive bits which are not same - 01 or 10
// We don't cosider if the pair of bits are at the righmost position, as after exchanging the bits
// one of the numbers will have a leading zero which doesn't get counted as part of the unsigned number.
// Example -
// 10000 : bitset = 1 1s, 4 0s
// 01000 => 1000 : bitset = 1 1s, 3 0s
// flipBit flips the bit at position pos
func flipBit(n uint32, pos uint) uint32 {
mask := uint32(1) << pos
n = n ^ mask
return n
}
// nearestBitset returns a number m with same bitset as n such that |n - m| is minimimum.
// It returns n if it is not applicable
func nearestBitset(n uint32) uint32 {
// bit positions
pos1, pos2 := uint(0), uint(1)
mask := uint32(1)
// how far should pos2 go
m := n >> mask
for m > uint32(0x11) {
if ((n >> pos1) & mask) != ((n >> pos2) & mask) {
fmt.Printf("exchanging bits at positions: %d, %d\n", pos1, pos2)
n = toggleBit(n, pos1)
n = toggleBit(n, pos2)
return n
}
pos1++
pos2++
m >>= mask
}
return n
}
import (
"fmt"
"strconv"
)
func i18n(word string) []string {
// Map to store the result
// This avoids duplicates
m := make(map[string]struct{})
for i, j := len(word)-2, 1; i > 0; i, j = i-1, j+1 {
for k := 1; k <= j; k++ {
w := word[:k] + strconv.Itoa(i) + word[i+k:]
m[w] = struct{}{}
}
}
m[word] = struct{}{}
// Extract the keys from the map
result := make([]string, len(m))
i := 0
for k := range m {
result[i] = k
i += 1
}
return result
}
def NearZeroPair(x):
xx = sorted(x)
l, r = 0, len(xx) -1
# If list is all -ve
# Return the last two numbers
if xx[0] < 0 and xx[-1] < 0:
return xx[-2:]
# If list is all +ve
# Return the first two numbers
if xx[0] >= 0 and xx[-1] >= 0:
return sorted(x)[:2]
# If list is a mix of +ve and -ve
# Traverse the sorted array from both ends
# Find the minimum sum
# Return the pair with the minimum sum
min_l, min_r = l, r
min_sum = xx[l] + xx[r]
while l < r:
s = xx[l] + xx[r]
if abs(s) < abs(min_sum):
min_sum = s
min_l, min_r = l, r
if sum < 0:
l += 1
else:
r -= 1
return [xx[min_l], xx[min_r]]
(((
def NearZeroPair(x):
xx = sorted(x)
l, r = 0, len(xx) -1
# If list is all -ve
# Return the last two numbers
if xx[0] < 0 and xx[-1] < 0:
return xx[-2:]
# If list is all +ve
# Return the first two numbers
if xx[0] >= 0 and xx[-1] >= 0:
return sorted(x)[:2]
# If list is a mix of +ve and -ve
# Traverse the sorted array from both ends
# Find the minimum sum
# Return the pair with the minimum sum
min_l, min_r = l, r
min_sum = xx[l] + xx[r]
while l < r:
s = xx[l] + xx[r]
if abs(s) < abs(min_sum):
min_sum = s
min_l, min_r = l, r
if sum < 0:
l += 1
else:
r -= 1
return [xx[min_l], xx[min_r]]
}}}
def _helper(result, s, word, i, l):
if i == l:
result.append(word)
return
if s[i] == "0" or s[i] == "1":
_helper(result, s, word+s[i], i+1, l)
else:
_helper(result, s, word+"0", i+1, l)
_helper(result, s, word+"1", i+1, l)
return result
def expand(expression):
return _helper([], expression, "", 0, len(expression))
As n can be a number which might not be a multiple of 256, for the remaining r bytes to be read we can get it with one call to ReadFromDisk() and taking the first r bytes
def Read(n):
t, r = n / 256, n % 256
result = b""
while t > 0:
result += ReadFromDisk()
t -= 1
result += ReadFromDisk()[:r]
return result
def __count(seq):
count = 0
for i in seq:
if i == seq[0]:
count += 1
else:
break
return seq[count:], str(count), seq[0]
def lsseq(n,__cache=['1']):
if len(__cache) > n:
return __cache[n]
while len(__cache) <= n:
last_seq = __cache[-1]
new_last_seq = ''
while last_seq:
last_seq, count, num= __count(last_seq)
new_last_seq = ''.join([new_last_seq, count, num])
__cache.append(new_last_seq)
return __cache[n]
- zingcat December 06, 2015