Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate a Haskell translation of this Python snippet without changing its computational steps. | import re as RegEx
def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ):
outString = ""
strPos = 0
matches = RegEx.findall( "[0-9]*", _string )
for match in matches[:-1]:
if not match:
outString += _string[ strPos ]
strPos += 1
else:
if len(match) > _periodLen:
leadIn = match[:_st... | #!/usr/bin/env runhaskell
import Control.Monad (forM_)
import Data.Char (isDigit)
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
isDigitOrPeriod :: Char -> Bool
isDigitOrPeriod '.' = True
isDigitOrPeriod c = isDigit c
chopUp :: Int -> String -> [String]
chopUp _ [] = []
chopUp by str
| by < 1 = [st... |
Convert the following code from Python to Haskell, ensuring the logic remains intact. | ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def convertToBase58(num):
sb = ''
while (num > 0):
r = num % 58
sb = sb + ALPHABET[r]
num = num // 58;
return sb[::-1]
s = 25420294593250030202636073700053352635053786165627414518
b = convertToBase58(s)
print("... | import Numeric (showIntAtBase)
chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
base58Encode :: Integer -> String
base58Encode n = showIntAtBase 58 (chars !!) n ""
main :: IO ()
main = mapM_ (putStrLn . base58Encode)
[25420294593250030202636073700053352635053786165627414518,
0x61... |
Write a version of this Python function in Haskell with identical behavior. | ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def convertToBase58(num):
sb = ''
while (num > 0):
r = num % 58
sb = sb + ALPHABET[r]
num = num // 58;
return sb[::-1]
s = 25420294593250030202636073700053352635053786165627414518
b = convertToBase58(s)
print("... | import Numeric (showIntAtBase)
chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
base58Encode :: Integer -> String
base58Encode n = showIntAtBase 58 (chars !!) n ""
main :: IO ()
main = mapM_ (putStrLn . base58Encode)
[25420294593250030202636073700053352635053786165627414518,
0x61... |
Transform the following Python implementation into Haskell, maintaining the same output and logic. | def dList(n, start):
start -= 1
a = range(n)
a[start] = a[0]
a[0] = start
a[1:] = sorted(a[1:])
first = a[1]
r = []
def recurse(last):
if (last == first):
for j,v in enumerate(a[1:]):
if j + 1 == v:
... | import Data.List (permutations, (\\))
import Control.Monad (foldM, forM_)
latinSquares :: Eq a => [a] -> [[[a]]]
latinSquares [] = []
latinSquares set = map reverse <$> squares
where
squares = foldM addRow firstRow perm
perm = tail (groupedPermutations set)
firstRow = pure <$> set
addRow tbl rows = [... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? | from string import ascii_uppercase
from itertools import product
from re import findall
def uniq(seq):
seen = {}
return [seen.setdefault(x, x) for x in seq if x not in seen]
def partition(seq, n):
return [seq[i : i + n] for i in xrange(0, len(seq), n)]
def playfair(key, from_ = 'J', to = None):
if ... | import Control.Monad (guard)
import Data.Array (Array, assocs, elems, listArray, (!))
import Data.Char (toUpper)
import Data.List (nub, (\\))
import Data.List.Split (chunksOf)
import Data.Maybe (listToMaybe)
import Data.String.Utils (replace)
type Square a = Array (Int, Int) a
arr... |
Preserve the algorithm and functionality while converting the code from Python to Haskell. | from string import ascii_uppercase
from itertools import product
from re import findall
def uniq(seq):
seen = {}
return [seen.setdefault(x, x) for x in seq if x not in seen]
def partition(seq, n):
return [seq[i : i + n] for i in xrange(0, len(seq), n)]
def playfair(key, from_ = 'J', to = None):
if ... | import Control.Monad (guard)
import Data.Array (Array, assocs, elems, listArray, (!))
import Data.Char (toUpper)
import Data.List (nub, (\\))
import Data.List.Split (chunksOf)
import Data.Maybe (listToMaybe)
import Data.String.Utils (replace)
type Square a = Array (Int, Int) a
arr... |
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version. | def _notcell(c):
return '0' if c == '1' else '1'
def eca_infinite(cells, rule):
lencells = len(cells)
rulebits = '{0:08b}'.format(rule)
neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}
c = cells
while True:
yield c
c = _notcell(c[0])*2 + c + _notcell(c... |
import Control.Comonad
import Data.InfList (InfList (..), (+++))
import qualified Data.InfList as Inf
data Cells a = Cells (InfList a) a (InfList a) deriving Functor
view n (Cells l x r) = reverse (Inf.take n l) ++ [x] ++ (Inf.take n r)
fromList [] = fromList [0]
fromList (x:xs) = let zeros = Inf.repeat 0
... |
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version. |
from itertools import (chain)
def stringParse(lexicon):
return lambda s: Node(s)(
tokenTrees(lexicon)(s)
)
def tokenTrees(wds):
def go(s):
return [Node(s)([])] if s in wds else (
concatMap(nxt(s))(wds)
)
def nxt(s):
return lambda w: parse(
... | import Data.List (isPrefixOf, intercalate)
import Data.Tree (Tree(..))
wordBreaks :: [String] -> String -> String
wordBreaks ws = (++) <*> (":\n" ++) . report . fmap go . tokenTrees ws
where
go t
| null (subForest t) = [rootLabel t]
| otherwise = subForest t >>= ((:) (rootLabel t) . go)
report xs... |
Please provide an equivalent version of this Python code in Haskell. | from math import pi, sin, cos
from collections import namedtuple
from random import random, choice
from copy import copy
try:
import psyco
psyco.full()
except ImportError:
pass
FLOAT_MAX = 1e100
class Point:
__slots__ = ["x", "y", "group"]
def __init__(self, x=0.0, y=0.0, group=0):
self... |
module KMeans where
import Control.Applicative
import Control.Monad.Random
import Data.List (minimumBy, genericLength, transpose)
import Data.Ord (comparing)
import qualified Data.Map.Strict as M
type Vec = [Float]
type Cluster = [Vec]
kMeansIteration :: [Vec] -> [Vec] -> [Cluster]
kMeansIteration pts = cluster... |
Translate the given Python code snippet into Haskell without altering its behavior. | hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))
def float_dec2bin(d):
neg = False
if d < 0:
d = -d
neg = True
hx = float(d).hex()
p = hx.index('p')
bn = ''.join(hex2bin.get(char, char) for char i... | import Data.Char (intToDigit)
import Numeric (floatToDigits, showIntAtBase)
dec2bin :: RealFloat a => a -> String
dec2bin f = "0." ++ map intToDigit digits ++ "p+" ++ showIntAtBase 2 intToDigit ex ""
where (digits, ex) = floatToDigits 2 f
main :: IO ()
main = putStrLn $ dec2bin 23.34375
|
Ensure the translated Haskell code behaves exactly like the original Python snippet. | hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))
def float_dec2bin(d):
neg = False
if d < 0:
d = -d
neg = True
hx = float(d).hex()
p = hx.index('p')
bn = ''.join(hex2bin.get(char, char) for char i... | import Data.Char (intToDigit)
import Numeric (floatToDigits, showIntAtBase)
dec2bin :: RealFloat a => a -> String
dec2bin f = "0." ++ map intToDigit digits ++ "p+" ++ showIntAtBase 2 intToDigit ex ""
where (digits, ex) = floatToDigits 2 f
main :: IO ()
main = putStrLn $ dec2bin 23.34375
|
Generate an equivalent Haskell version of this Python code. | from itertools import imap, imap, groupby, chain, imap
from operator import itemgetter
from sys import argv
from array import array
def concat_map(func, it):
return list(chain.from_iterable(imap(func, it)))
def minima(poly):
return (min(pt[0] for pt in poly), min(pt[1] for pt in poly))
def translate_to_... | import System.Environment (getArgs)
import Control.Arrow ((***), first)
import Data.Set (toList, fromList)
import Data.List (sort)
import Data.Bool (bool)
type Coord = Int
type Point = (Coord, Coord)
type Polyomino = [Point]
minima :: Polyomino -> Point
minima (p:ps) = foldr (\(x, y) (mx, my) -> (min x mx, min y m... |
Convert the following code from Python to Haskell, ensuring the logic remains intact. |
from itertools import groupby
from unicodedata import decomposition, name
from pprint import pprint as pp
commonleaders = ['the']
replacements = {u'ß': 'ss',
u'ſ': 's',
u'ʒ': 's',
}
hexdigits = set('0123456789abcdef')
decdigits = set('0123456789')
def splitch... | import Data.List
import Data.Char
import Data.String.Utils
import Data.List.Utils
import Data.Function (on)
printOutput = do
putStrLn "# Ignoring leading spaces \n"
printBlockOfMessages sample1Rule ignoringStartEndSpaces
putStrLn "\n # Ignoring multiple adjacent spaces ... |
Port the following code from Python to Haskell with equivalent syntax and logic. |
import argh
import hashlib
import sys
@argh.arg('filename', nargs='?', default=None)
def main(filename, block_size=1024*1024):
if filename:
fin = open(filename, 'rb')
else:
fin = sys.stdin
stack = []
block = fin.read(block_size)
while block:
node = (0, ... |
import Control.Monad (mfilter)
import Crypto.Hash.SHA256 (hash)
import qualified Data.ByteString as B
import Data.ByteString.Builder (byteStringHex, char7, hPutBuilder)
import Data.Functor ((<&>))
import Data.Maybe (listToMaybe)
import Data.Strict.Tuple (Pair(..))
import qualified Data.Strict.Tuple as T
import System... |
Convert this Python block to Haskell, preserving its control flow and logic. | from itertools import islice
def posd():
"diff between position numbers. 1, 2, 3... interleaved with 3, 5, 7..."
count, odd = 1, 3
while True:
yield count
yield odd
count, odd = count + 1, odd + 2
def pos_gen():
"position numbers. 1 3 2 5 7 4 9 ..."
val = 1
diff = posd... |
data Memo a = Node a (Memo a) (Memo a)
deriving (Functor)
memo :: Integral a => Memo p -> a -> p
memo (Node a l r) n
| n == 0 = a
| odd n = memo l (n `div` 2)
| otherwise = memo r (n `div` 2 - 1)
nats :: Memo Int
nats =
Node
0
((+ 1) . (* 2) <$> nats)
((* 2) . (+ 1) <$> nats)
partitions... |
Translate this program into Haskell but keep the logic exactly as in Python. | from __future__ import print_function
from __future__ import division
def extended_synthetic_division(dividend, divisor):
out = list(dividend)
normalizer = divisor[0]
for i in xrange(len(dividend)-(len(divisor)-1)):
out[i] /= normalizer
coef... | import Data.List
normalized :: (Eq a, Num a) => [a] -> [a]
normalized = dropWhile (== 0)
isZero :: (Eq a, Num a) => [a] -> Bool
isZero = null . normalized
shortDiv :: (Eq a, Fractional a) => [a] -> [a] -> ([a], [a])
shortDiv p1 p2
| isZero p2 = error "zero divisor"
| otherwise =
let go 0 p = p
g... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? | from __future__ import print_function
from __future__ import division
def extended_synthetic_division(dividend, divisor):
out = list(dividend)
normalizer = divisor[0]
for i in xrange(len(dividend)-(len(divisor)-1)):
out[i] /= normalizer
coef... | import Data.List
normalized :: (Eq a, Num a) => [a] -> [a]
normalized = dropWhile (== 0)
isZero :: (Eq a, Num a) => [a] -> Bool
isZero = null . normalized
shortDiv :: (Eq a, Fractional a) => [a] -> [a] -> ([a], [a])
shortDiv p1 p2
| isZero p2 = error "zero divisor"
| otherwise =
let go 0 p = p
g... |
Port the provided Python code into Haskell while preserving the original functionality. | from __future__ import print_function
import os
import hashlib
import datetime
def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"):
knownFiles = {}
for root, dirs, files in os.walk(pth):
for fina in files:
fullFina = os.path.join(root, fina)
isSymLink = os.path.isli... | import Crypto.Hash.MD5 (hash)
import Data.ByteString as BS (readFile, ByteString())
import System.Environment (getArgs, getProgName)
import System.Directory (doesDirectoryExist, getDirectoryContents)
import System.FilePath.Posix ((</>))
import Control.Monad (forM)
import Text.Printf ... |
Produce a language-to-language conversion: from Python to Haskell, same semantics. | from primesieve import primes
from math import isqrt
from functools import cache
p = primes(isqrt(1_000_000_000))
@cache
def phi(x, a):
res = 0
while True:
if not a or not x:
return x + res
a -= 1
res -= phi(x//p[a], a)
def legpi(n):
if n < 2: return 0
a = l... |
import Data.Time.Clock.POSIX ( getPOSIXTime )
import Data.Int ( Int64 )
import Data.Bits ( Bits( shiftL, shiftR ) )
data Memo a = EmptyNode | Node a (Memo a) (Memo a)
deriving Functor
memo :: Integral a => Memo p -> a -> p
memo (Node a l r) n
| n == 0 = a
| odd n = memo l (n `div` 2)
| otherwise = memo r... |
Rewrite the snippet below in Haskell so it works the same as the original Python code. |
from __future__ import annotations
import functools
import gzip
import json
import logging
import platform
import re
from collections import Counter
from collections import defaultdict
from typing import Any
from typing import Iterator
from typing import Iterable
from typing import List
from typing import Mapping
... | import System.Environment
import Network.HTTP
import Text.Printf
import Text.Regex.TDFA
import Data.List
import Data.Array
import qualified Data.Map as Map
splitByMatches :: String -> [MatchText String] -> [String]
splitByMatches str matches = foldr splitHead [str] matches
where splitHead match acc = before:a... |
Write the same algorithm in Haskell as shown in this Python implementation. | from itertools import count
from pprint import pformat
import re
import heapq
def pal_part_gen(odd=True):
for i in count(1):
fwd = str(i)
rev = fwd[::-1][1:] if odd else fwd[::-1]
yield int(fwd + rev)
def pal_ordered_gen():
yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(o... | import Control.Monad (guard)
palindromic :: Int -> Bool
palindromic n = d == reverse d
where
d = show n
gapful :: Int -> Bool
gapful n = n `rem` firstLastDigit == 0
where
firstLastDigit = read [head asDigits, last asDigits]
asDigits = show n
result :: Int -> [Int]
result d = do
x <- [(d+100),(d+110)..]
... |
Rewrite the snippet below in Haskell so it works the same as the original Python code. | from itertools import count
from pprint import pformat
import re
import heapq
def pal_part_gen(odd=True):
for i in count(1):
fwd = str(i)
rev = fwd[::-1][1:] if odd else fwd[::-1]
yield int(fwd + rev)
def pal_ordered_gen():
yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(o... | import Control.Monad (guard)
palindromic :: Int -> Bool
palindromic n = d == reverse d
where
d = show n
gapful :: Int -> Bool
gapful n = n `rem` firstLastDigit == 0
where
firstLastDigit = read [head asDigits, last asDigits]
asDigits = show n
result :: Int -> [Int]
result d = do
x <- [(d+100),(d+110)..]
... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? | from numpy import log
def sieve_of_Sundaram(nth, print_all=True):
assert nth > 0, "nth must be a positive integer"
k = int((2.4 * nth * log(nth)) // 2)
integers_list = [True] * k
for i in range(1, k):
j = i
while i + j + 2 * i * j < k:
integers_list[i + j + 2 * i * j]... | import Data.List (intercalate, transpose)
import Data.List.Split (chunksOf)
import qualified Data.Set as S
import Text.Printf (printf)
sundaram :: Integral a => a -> [a]
sundaram n =
[ succ (2 * x)
| x <- [1 .. m],
x `S.notMember` excluded
]
where
m = div (pred n) 2
excluded =
S.fromLis... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? | from sympy import sieve
primelist = list(sieve.primerange(2,1000000))
listlen = len(primelist)
pindex = 1
old_diff = -1
curr_list=[primelist[0]]
longest_list=[]
while pindex < listlen:
diff = primelist[pindex] - primelist[pindex-1]
if diff > old_diff:
curr_list.append(primelist[pindex])
i... | import Data.Numbers.Primes (primes)
consecutives equiv = filter ((> 1) . length) . go []
where
go r [] = [r]
go [] (h : t) = go [h] t
go (y : ys) (h : t)
| y `equiv` h = go (h : y : ys) t
| otherwise = (y : ys) : go [h] t
maximumBy g (h : t) = foldr f h t
where
f r x = if g r < g x t... |
Convert the following code from Python to Haskell, ensuring the logic remains intact. | def pad_like(max_n=8, t=15):
start = [[], [1, 1, 1]]
for n in range(2, max_n+1):
this = start[n-1][:n+1]
while len(this) < t:
this.append(sum(this[i] for i in range(-2, -n - 2, -1)))
start.append(this)
return start[2:]
def pr(p):
print(.strip())
fo... | import Data.Bifunctor (second)
import Data.List (transpose, uncons, unfoldr)
padovans :: Int -> [Int]
padovans n
| 0 > n = []
| otherwise = unfoldr (recurrence n) $ take (succ n) xs
where
xs
| 3 > n = repeat 1
| otherwise = padovans $ pred n
recurrence :: Int -> [Int] -> Maybe (Int, [Int])
rec... |
Maintain the same structure and functionality when rewriting this code in Haskell. |
from pyprimesieve import primes
def digitsum(num):
return sum(int(c) for c in str(num))
def generate_honaker(limit=5_000_000):
honaker = [(i + 1, p) for i, p in enumerate(primes(limit)) if digitsum(p) == digitsum(i + 1)]
for hcount, (ppi, pri) in enumerate(honaker):
yield hcount + 1... | import Control.Monad (join)
import Data.Bifunctor (bimap)
import Data.List.Split (chunksOf)
import Data.Numbers.Primes (primes)
honakers :: [(Integer, Integer)]
honakers =
filter
(uncurry (==) . both sumDigits)
(zip [1 ..] primes)
main :: IO ()
main =
putStrLn "First Fifty:\n"
>> mapM_
(putSt... |
Transform the following Python implementation into Haskell, maintaining the same output and logic. |
def isowndigitspowersum(integer):
digits = [int(c) for c in str(integer)]
exponent = len(digits)
return sum(x ** exponent for x in digits) == integer
print("Own digits power sums for N = 3 to 9 inclusive:")
for i in range(100, 1000000000):
if isowndigitspowersum(i):
print(i)
| import Data.List (sort)
ownDigitsPowerSums :: Int -> [Int]
ownDigitsPowerSums n = sort (ns >>= go)
where
ns = combsWithRep n [0 .. 9]
go xs
| digitsMatch m xs = [m]
| otherwise = []
where
m = foldr ((+) . (^ n)) 0 xs
digitsMatch :: Show a => a -> [Int] -> Bool
digitsMatch n ds =
... |
Maintain the same structure and functionality when rewriting this code in Haskell. | import textwrap
from itertools import pairwise
from typing import Iterator
from typing import List
import primesieve
def primes() -> Iterator[int]:
it = primesieve.Iterator()
while True:
yield it.next_prime()
def triplewise(iterable):
for (a, _), (b, c) in pairwise(pairwise(iterable)):
... | import Data.Numbers.Primes (primes)
import Data.List (sort)
ormistons :: [(Integer, Integer, Integer)]
ormistons =
concat $ zipWith3
(\(dx, x) (dy, y) (dz, z)
-> [(x, y, z) | dx == dy && dx == dz])
primeDigits
(tail primeDigits)
(drop 2 primeDigits)
primeDigits :: [(Integer, I... |
Produce a functionally identical Haskell code for the snippet given in Python. | def Riordan(N):
a = [1, 0, 1]
for n in range(3, N):
a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1))
return a
rios = Riordan(10_000)
for i in range(32):
print(f'{rios[i] : 18,}', end='\n' if (i + 1) % 4 == 0 else '')
print(f'The 1,000th Riordan has {len(str(rios[999]))} digits.')
... |
riordans :: [Integer]
riordans =
1 :
0 :
zipWith
div
( zipWith
(*)
[1 ..]
( zipWith
(+)
((2 *) <$> tail riordans)
((3 *) <$> riordans)
)
)
[3 ..]
main :: IO ()
main =
putStrLn "First 32 Riordan terms:"
>> mapM_ print (ta... |
Convert this Python snippet to Haskell and keep its semantics consistent. | def Riordan(N):
a = [1, 0, 1]
for n in range(3, N):
a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1))
return a
rios = Riordan(10_000)
for i in range(32):
print(f'{rios[i] : 18,}', end='\n' if (i + 1) % 4 == 0 else '')
print(f'The 1,000th Riordan has {len(str(rios[999]))} digits.')
... |
riordans :: [Integer]
riordans =
1 :
0 :
zipWith
div
( zipWith
(*)
[1 ..]
( zipWith
(+)
((2 *) <$> tail riordans)
((3 *) <$> riordans)
)
)
[3 ..]
main :: IO ()
main =
putStrLn "First 32 Riordan terms:"
>> mapM_ print (ta... |
Port the following code from Python to Haskell with equivalent syntax and logic. |
from __future__ import annotations
import functools
import math
import os
from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Writer(Generic[T]):
def __init__(self, value: Union[T, Wri... | import Control.Monad.Trans.Writer
import Control.Monad ((>=>))
loggingVersion :: (a -> b) -> c -> a -> Writer c b
loggingVersion f log x = writer (f x, log)
logRoot = loggingVersion sqrt "obtained square root, "
logAddOne = loggingVersion (+1) "added 1, "
logHalf = loggingVersion (/2) "divided by 2, "
halfOfAddOneOf... |
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version. | import os,sys,zlib,urllib.request
def h ( str,x=9 ):
for c in str :
x = ( x*33 + ord( c )) & 0xffffffffff
return x
def cache ( func,*param ):
n = 'cache_%x.bin'%abs( h( repr( param )))
try : return eval( zlib.decompress( open( n,'rb' ).read()))
except : pass
s = func( *param )
... | import System.IO (readFile)
import Control.Monad (foldM)
import Data.List (intercalate)
import qualified Data.Set as S
distance :: String -> String -> Int
distance s1 s2 = length $ filter not $ zipWith (==) s1 s2
wordLadders :: [String] -> String -> String -> [[String]]
wordLadders dict start end
| length start /= ... |
Produce a functionally identical Haskell code for the snippet given in Python. | from itertools import combinations_with_replacement as cmbr
from time import time
def dice_gen(n, faces, m):
dice = list(cmbr(faces, n))
succ = [set(j for j, b in enumerate(dice)
if sum((x>y) - (x<y) for x in a for y in b) > 0)
for a in dice]
def loops(seq):
... |
import Data.List
import Control.Monad
newtype Dice = Dice [Int]
instance Show Dice where
show (Dice s) = "(" ++ unwords (show <$> s) ++ ")"
instance Eq Dice where
d1 == d2 = d1 `compare` d2 == EQ
instance Ord Dice where
Dice d1 `compare` Dice d2 = (add $ compare <$> d1 <*> d2) `compare` 0
where
... |
Maintain the same structure and functionality when rewriting this code in Haskell. |
import math
def apply_perm(omega,fbn):
for m in range(len(fbn)):
g = fbn[m]
if g > 0:
new_first = omega[m+g]
omega[m+1:m+g+1] = omega[m:m+g]
omega[m] = new_first
return omega
def int... | import Data.List (unfoldr, intercalate)
newtype Fact = Fact [Int]
fact :: [Int] -> Fact
fact = Fact . zipWith min [0..] . reverse
instance Show Fact where
show (Fact ds) = intercalate "." $ show <$> reverse ds
toFact :: Integer -> Fact
toFact 0 = Fact [0]
toFact n = Fact $ unfoldr f (1, n)
where
f (b, ... |
Maintain the same structure and functionality when rewriting this code in Haskell. | Plataanstraat 5 split as (Plataanstraat, 5)
Straat 12 split as (Straat, 12)
Straat 12 II split as (Straat, 12 II)
Dr. J. Straat 12 split as (Dr. J. Straat , 12)
Dr. J. Straat 12 a split as (Dr. J. Straat, 12 a)
Dr. J. Straat 12-14 split as (Dr. J. Straat, 12... |
module Main where
import Control.Monad
import Data.Char
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Text.Regex.PCRE.Text
testSet :: [T.Text]
testSet =
[ "Plataanstraat 5"
, "Straat 12"
, "Straat 12 II"
, "Dr. J. Straat 12"
, "Dr. J. Straat 12 a"
, "Dr... |
Preserve the algorithm and functionality while converting the code from Python to Haskell. | from datetime import date
from calendar import isleap
def weekday(d):
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"]
dooms = [
[3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],
[4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
]
c = d.year // 100
r = d... | import Text.Printf
data Date = Date {year :: Int, month :: Int, day :: Int}
instance Show Date where
show Date {year = y, month = m, day = d} =
printf "%4d-%02d-%02d" y m d
leap :: Int -> Bool
leap year =
year `mod` 4 == 0
&& (year `mod` 100 /= 0 || year `mod` 400 == 0)
weekday :: Date -> Int
weekday Da... |
Rewrite the snippet below in Haskell so it works the same as the original Python code. | from datetime import date
from calendar import isleap
def weekday(d):
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"]
dooms = [
[3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],
[4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
]
c = d.year // 100
r = d... | import Text.Printf
data Date = Date {year :: Int, month :: Int, day :: Int}
instance Show Date where
show Date {year = y, month = m, day = d} =
printf "%4d-%02d-%02d" y m d
leap :: Int -> Bool
leap year =
year `mod` 4 == 0
&& (year `mod` 100 /= 0 || year `mod` 400 == 0)
weekday :: Date -> Int
weekday Da... |
Preserve the algorithm and functionality while converting the code from Python to Haskell. | import numpy as np
from numpy.linalg import inv
a = np.array([[1., 2., 3.], [4., 1., 6.],[ 7., 8., 9.]])
ainv = inv(a)
print(a)
print(ainv)
| isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs
isSquareMatrix xs = null xs || all ((== (length xs)).length) xs
mult:: Num a => [[a]] -> [[a]] -> [[a]]
mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss
matI::(Num a) => Int -> [[a]]
... |
Produce a language-to-language conversion: from Python to Haskell, same semantics. | import numpy as np
from numpy.linalg import inv
a = np.array([[1., 2., 3.], [4., 1., 6.],[ 7., 8., 9.]])
ainv = inv(a)
print(a)
print(ainv)
| isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs
isSquareMatrix xs = null xs || all ((== (length xs)).length) xs
mult:: Num a => [[a]] -> [[a]] -> [[a]]
mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss
matI::(Num a) => Int -> [[a]]
... |
Preserve the algorithm and functionality while converting the code from Python to Haskell. | from math import prod
largest = [0]
def iscolorful(n):
if 0 <= n < 10:
return True
dig = [int(c) for c in str(n)]
if 1 in dig or 0 in dig or len(dig) > len(set(dig)):
return False
products = list(set(dig))
for i in range(len(dig)):
for j in range(i+2, len(dig)+1):
... | import Data.List ( nub )
import Data.List.Split ( divvy )
import Data.Char ( digitToInt )
isColourful :: Integer -> Bool
isColourful n
|n >= 0 && n <= 10 = True
|n > 10 && n < 100 = ((length s) == (length $ nub s)) &&
(not $ any (\c -> elem c "01") s)
|n >= 100 = ((length s) == (length $ nub s)) && (n... |
Produce a functionally identical Haskell code for the snippet given in Python. | from math import prod
largest = [0]
def iscolorful(n):
if 0 <= n < 10:
return True
dig = [int(c) for c in str(n)]
if 1 in dig or 0 in dig or len(dig) > len(set(dig)):
return False
products = list(set(dig))
for i in range(len(dig)):
for j in range(i+2, len(dig)+1):
... | import Data.List ( nub )
import Data.List.Split ( divvy )
import Data.Char ( digitToInt )
isColourful :: Integer -> Bool
isColourful n
|n >= 0 && n <= 10 = True
|n > 10 && n < 100 = ((length s) == (length $ nub s)) &&
(not $ any (\c -> elem c "01") s)
|n >= 100 = ((length s) == (length $ nub s)) && (n... |
Produce a functionally identical Haskell code for the snippet given in Python. | import random
board = [[" " for x in range(8)] for y in range(8)]
piece_list = ["R", "N", "B", "Q", "P"]
def place_kings(brd):
while True:
rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)
diff_list = [abs(rank_white - rank_black)... |
module RandomChess
( placeKings
, placePawns
, placeRemaining
, emptyBoard
, toFen
, ChessBoard
, Square (..)
, BoardState (..)
, getBoard
)
where
import Control.Monad.State (State, get, gets, put)
import Data.List (find, sortBy)
import System.Random (Random, RandomGen, StdGen, random, randomR)
type Pos = (Char, In... |
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version. |
from functools import reduce
from sympy import divisors
FOUND = 0
for num in range(1, 1_000_000):
divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1
if num * num * num == divprod:
FOUND += 1
if FOUND <= 50:
print(f'{num:5}', end='\n' if FOUND % 10 == 0 else... | import Data.List (group, intercalate, transpose)
import Data.List.Split (chunksOf)
import Data.Numbers.Primes ( primeFactors )
import Text.Printf (printf)
oeisA111398 :: [Integer]
oeisA111398 = 1 : [n | n <- [1..], 8 == length (divisors n)]
divisors :: Integer -> [Integer]
divisors =
foldr
(flip ((<*>) . fm... |
Transform the following Python implementation into Haskell, maintaining the same output and logic. | from sympy.ntheory import factorint
def D(n):
if n < 0:
return -D(-n)
elif n < 2:
return 0
else:
fdict = factorint(n)
if len(fdict) == 1 and 1 in fdict:
return 1
return sum([n * e // p for p, e in fdict.items()])
for n in range(-99, 101):
print('{:5... | import Control.Monad (forM_)
import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Math.NumberTheory.Primes (factorise, unPrime)
import Text.Printf (printf)
arithderiv_ :: Integer -> Integer
arithderiv_ 0 = 0
arithderiv_ n = foldr step 0 $ factorise n
where step (p, v) s = s + n `quot` unPrime p *... |
Can you help me rewrite this code in Haskell instead of Python, keeping it the same logically? |
from sympy import factorint
NUM_WANTED = 100
for num in range(1, NUM_WANTED + 1):
fac = factorint(num, multiple=True)
product = fac[0] * fac[-1] if len(fac) > 0 else 1
print(f'{product:5}', end='\n' if num % 10 == 0 else '')
| import Data.List (intercalate, transpose)
import Data.List.Split (chunksOf)
import Data.Numbers.Primes (primeFactors)
import Text.Printf (printf)
oeisA066048 :: [Integer]
oeisA066048 = 1 : fmap f [2 ..]
where
f = ((*) . head <*> last) . primeFactors
main :: IO ()
main = putStrLn $
table " " $ (chunksOf 1... |
Generate an equivalent Haskell version of this Python code. | from numpy import Inf
class MaxTropical:
def __init__(self, x=0):
self.x = x
def __str__(self):
return str(self.x)
def __add__(self, other):
return MaxTropical(max(self.x, other.x))
def __mul__(self, other):
return MaxTropical(self.x + other.x)
def __pow__(s... |
import Prelude hiding ((^))
import Data.Monoid (Sum(Sum))
import Data.Number.CReal (CReal)
import Data.Semiring (Semiring, (^), plus, times)
import Data.Semiring.Tropical (Tropical(..), Extrema(Maxima))
newtype MaxPlus = MaxPlus (Tropical 'Maxima CReal)
(⊕), (⊗) :: MaxPlus -> MaxPlus -> MaxPlus
(⊕) = plus... |
Convert this Python snippet to Haskell and keep its semantics consistent. |
from itertools import permutations
numList = [2,3,1]
baseList = []
for i in numList:
for j in range(0,i):
baseList.append(i)
stringDict = {'A':2,'B':3,'C':1}
baseString=""
for i in stringDict:
for j in range(0,stringDict[i]):
baseString+=i
print("Permutations for " + str(baseList) + " :... | permutationsSomeIdentical :: [(a, Int)] -> [[a]]
permutationsSomeIdentical [] = [[]]
permutationsSomeIdentical xs =
[ x : ys
| (x, xs_) <- select xs,
ys <- permutationsSomeIdentical xs_
]
where
select [] = []
select ((x, n) : xs) =
(x, xs_) :
[ (y, (x, n) : cs)
| (y, cs) ... |
Write a version of this Python function in Haskell with identical behavior. | from sympy import isprime, lcm, factorint, primerange
from functools import reduce
def pisano1(m):
"Simple definition"
if m < 2:
return 1
lastn, n = 0, 1
for i in range(m ** 2):
lastn, n = n, (lastn + n) % m
if lastn == 0 and n == 1:
return i + 1
return 1
def p... | import qualified Data.Text as T
main = do
putStrLn "PisanoPrime(p,2) for prime p lower than 15"
putStrLn . see 15 . map (`pisanoPrime` 2) . filter isPrime $ [1 .. 15]
putStrLn "PisanoPrime(p,1) for prime p lower than 180"
putStrLn . see 15 . map (`pisanoPrime` 1) . filter isPrime $ [1 .. 180]
let ns = [1 .. ... |
Keep all operations the same but rewrite the snippet in Haskell. | print(
"{:19.16f} {:19.16f}".format(
minkowski(minkowski_inv(4.04145188432738056)),
minkowski_inv(minkowski(4.04145188432738056)),
)
)
| import Data.Tree
import Data.Ratio
import Data.List
intervalTree :: (a -> a -> a) -> (a, a) -> Tree a
intervalTree node = unfoldTree $
\(a, b) -> let m = node a b in (m, [(a,m), (m,b)])
Node a _ ==> Node b [] = const b
Node a [] ==> Node b _ = const b
Node a [l1, r1] ==> Node b [l2, r2] =
\x -> case x `compare` a... |
Keep all operations the same but rewrite the snippet in Haskell. |
from math import sqrt
from numpy import array
from mpmath import mpf
class AdditionChains:
def __init__(self):
self.chains, self.idx, self.pos = [[1]], 0, 0
self.pat, self.lvl = {1: 0}, [[1]]
def add_chain(self):
newchain = self.chains[self.idx].copy()
... | dichotomicChain :: Integral a => a -> [a]
dichotomicChain n
| n == 3 = [3, 2, 1]
| n == 2 ^ log2 n = takeWhile (> 0) $ iterate (`div` 2) n
| otherwise = let k = n `div` (2 ^ ((log2 n + 1) `div` 2))
in chain n k
where
chain n1 n2
| n2 <= 1 = dichotomicChain n1
| otherwise = case... |
Keep all operations the same but rewrite the snippet in Haskell. |
import inflect
def count_letters(word):
count = 0
for letter in word:
if letter != ',' and letter !='-' and letter !=' ':
count += 1
return count
def split_with_spaces(sentence):
sentence_list = []
curr_word = ""
for c in sentence:
if... | import Data.Char
sentence = start ++ foldMap add (zip [2..] $ tail $ words sentence)
where
start = "Four is the number of letters in the first word of this sentence, "
add (i, w) = unwords [spellInteger (alphaLength w), "in the", spellOrdinal i ++ ", "]
alphaLength w = fromIntegral $ length $ filter isAlpha... |
Ensure the translated Haskell code behaves exactly like the original Python snippet. |
from functools import reduce
from operator import add
def wordleScore(target, guess):
return mapAccumL(amber)(
*first(charCounts)(
mapAccumL(green)(
[], zip(target, guess)
)
)
)[1]
def green(residue, tg):
t, g = tg
return (residue... | import Data.Bifunctor (first)
import Data.List (intercalate, mapAccumL)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
type Tally = M.Map Char Int
wordleScore :: String -> String -> [Int]
wordleScore target guess =
snd $
uncurry (mapAccumL amber) $
first charCounts $
mapAccu... |
Port the following code from Python to Haskell with equivalent syntax and logic. | class Head():
def __init__(self, lo, hi=None, shift=0):
if hi is None: hi = lo
d = hi - lo
ds, ls, hs = str(d), str(lo), str(hi)
if d and len(ls) > len(ds):
assert(len(ls) - len(ds) + 1 > 21)
lo = int(str(lo)[:len(ls) - len(ds) + 1])
hi = int(str... | import System.CPUTime (getCPUTime)
import Data.List
main = do
startTime <- getCPUTime
mapM_ (putStrLn.formatAns).take 7.iterate (*10) $ 10
mapM_ (putStrLn.seeFib) [16,32]
finishTime <- getCPUTime
putStrLn $ "Took " ++ (took startTime finishTime)
took t = fromChrono.chrono t
fromChrono :: (Integer... |
Change the following Python code into Haskell without altering its purpose. | class Head():
def __init__(self, lo, hi=None, shift=0):
if hi is None: hi = lo
d = hi - lo
ds, ls, hs = str(d), str(lo), str(hi)
if d and len(ls) > len(ds):
assert(len(ls) - len(ds) + 1 > 21)
lo = int(str(lo)[:len(ls) - len(ds) + 1])
hi = int(str... | import System.CPUTime (getCPUTime)
import Data.List
main = do
startTime <- getCPUTime
mapM_ (putStrLn.formatAns).take 7.iterate (*10) $ 10
mapM_ (putStrLn.seeFib) [16,32]
finishTime <- getCPUTime
putStrLn $ "Took " ++ (took startTime finishTime)
took t = fromChrono.chrono t
fromChrono :: (Integer... |
Rewrite the snippet below in Haskell so it works the same as the original Python code. | from itertools import count, chain
from collections import deque
def primes(_cache=[2, 3]):
yield from _cache
for n in count(_cache[-1]+2, 2):
if isprime(n):
_cache.append(n)
yield n
def isprime(n):
for p in primes():
if n%p == 0:
return False
if... | import Data.List
import Data.Numbers.Primes (primeFactors)
negateVar p = zipWith (*) p $ reverse $ take (length p) $ cycle [1,-1]
lift p 1 = p
lift p n = intercalate (replicate (n-1) 0) (pure <$> p)
shortDiv :: [Integer] -> [Integer] -> [Integer]
shortDiv p1 (_:p2) = unfoldr go (length p1 - length p2, p1)
where
... |
Ensure the translated Haskell code behaves exactly like the original Python snippet. | from itertools import count, chain
from collections import deque
def primes(_cache=[2, 3]):
yield from _cache
for n in count(_cache[-1]+2, 2):
if isprime(n):
_cache.append(n)
yield n
def isprime(n):
for p in primes():
if n%p == 0:
return False
if... | import Data.List
import Data.Numbers.Primes (primeFactors)
negateVar p = zipWith (*) p $ reverse $ take (length p) $ cycle [1,-1]
lift p 1 = p
lift p n = intercalate (replicate (n-1) 0) (pure <$> p)
shortDiv :: [Integer] -> [Integer] -> [Integer]
shortDiv p1 (_:p2) = unfoldr go (length p1 - length p2, p1)
where
... |
Convert the following code from Python to Haskell, ensuring the logic remains intact. | from functools import lru_cache
DIVS = {2, 3}
SUBS = {1}
class Minrec():
"Recursive, memoised minimised steps to 1"
def __init__(self, divs=DIVS, subs=SUBS):
self.divs, self.subs = divs, subs
@lru_cache(maxsize=None)
def _minrec(self, n):
"Recursive, memoised"
if n == 1:
... |
import Data.List
import Data.Ord
import Data.Function (on)
data Memo a = Node a (Memo a) (Memo a)
deriving Functor
memo :: Integral a => Memo p -> a -> p
memo (Node a l r) n
| n == 0 = a
| odd n = memo l (n `div` 2)
| otherwise = memo r (n `div` 2 - 1)
nats :: Integral a => Memo a
nats = Node 0 ((+1).(*2... |
Transform the following Python implementation into Haskell, maintaining the same output and logic. | from mpmath import mp
heegner = [19,43,67,163]
mp.dps = 50
x = mp.exp(mp.pi*mp.sqrt(163))
print("calculated Ramanujan's constant: {}".format(x))
print("Heegner numbers yielding 'almost' integers:")
for i in heegner:
print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt... | import Control.Monad (forM_)
import Data.Number.CReal (CReal, showCReal)
import Text.Printf (printf)
ramfun :: CReal -> CReal
ramfun x = exp (pi * sqrt x)
ramanujan :: CReal
ramanujan = ramfun 163
heegners :: [Int]
heegners = [19, 43, 67, 163]
intDist :: CReal -> CReal
intDist x = abs (x - fromIntegral (round x)... |
Ensure the translated Haskell code behaves exactly like the original Python snippet. | from mpmath import mp
heegner = [19,43,67,163]
mp.dps = 50
x = mp.exp(mp.pi*mp.sqrt(163))
print("calculated Ramanujan's constant: {}".format(x))
print("Heegner numbers yielding 'almost' integers:")
for i in heegner:
print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt... | import Control.Monad (forM_)
import Data.Number.CReal (CReal, showCReal)
import Text.Printf (printf)
ramfun :: CReal -> CReal
ramfun x = exp (pi * sqrt x)
ramanujan :: CReal
ramanujan = ramfun 163
heegners :: [Int]
heegners = [19, 43, 67, 163]
intDist :: CReal -> CReal
intDist x = abs (x - fromIntegral (round x)... |
Translate this program into Haskell but keep the logic exactly as in Python. | def to_tree(x, index=0, depth=1):
so_far = []
while index < len(x):
this = x[index]
if this == depth:
so_far.append(this)
elif this > depth:
index, deeper = to_tree(x, index, depth + 1)
so_far.append(deeper)
else:
index -=1
break
... |
import Data.Bifunctor (bimap)
import Data.Tree (Forest, Tree (..), drawTree, foldTree)
treeFromSparseLevels :: [Int] -> Tree (Maybe Int)
treeFromSparseLevels =
Node Nothing
. forestFromNestLevels
. rooted
. normalised
sparseLevelsFromTree :: Tree (Maybe Int) -> [Int]
sparseLevelsFromTree = foldTree ... |
Rewrite this program in Haskell while keeping its functionality equivalent to the Python version. | def to_tree(x, index=0, depth=1):
so_far = []
while index < len(x):
this = x[index]
if this == depth:
so_far.append(this)
elif this > depth:
index, deeper = to_tree(x, index, depth + 1)
so_far.append(deeper)
else:
index -=1
break
... |
import Data.Bifunctor (bimap)
import Data.Tree (Forest, Tree (..), drawTree, foldTree)
treeFromSparseLevels :: [Int] -> Tree (Maybe Int)
treeFromSparseLevels =
Node Nothing
. forestFromNestLevels
. rooted
. normalised
sparseLevelsFromTree :: Tree (Maybe Int) -> [Int]
sparseLevelsFromTree = foldTree ... |
Keep all operations the same but rewrite the snippet in Haskell. | from pprint import pprint as pp
def to_indent(node, depth=0, flat=None):
if flat is None:
flat = []
if node:
flat.append((depth, node[0]))
for child in node[1]:
to_indent(child, depth + 1, flat)
return flat
def to_nest(lst, depth=0, level=None):
if level is None:
le... |
import Data.List (span)
data Nest a = Nest (Maybe a) [Nest a]
deriving Eq
instance Show a => Show (Nest a) where
show (Nest (Just a) []) = show a
show (Nest (Just a) s) = show a ++ show s
show (Nest Nothing []) = "\"\""
show (Nest Nothing s) = "\"\"" ++ show s
type Indent a = [(Int, a)]
class Is... |
Rewrite the snippet below in Haskell so it works the same as the original Python code. | import collections
def MostFreqKHashing(inputString, K):
occuDict = collections.defaultdict(int)
for c in inputString:
occuDict[c] += 1
occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)
outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])
return outputStr
d... | module MostFrequentK
where
import Data.List ( nub , sortBy )
import qualified Data.Set as S
count :: Eq a => [a] -> a -> Int
count [] x = 0
count ( x:xs ) k
|x == k = 1 + count xs k
|otherwise = count xs k
orderedStatistics :: String -> [(Char , Int)]
orderedStatistics s = sortBy myCriterion $ nub $ zip ... |
Translate this program into Haskell but keep the logic exactly as in Python. |
import argparse
import itertools
import pathlib
import re
import secrets
import sys
MAGIC = "
def make_keys(n, size):
return (secrets.token_hex(size) for _ in range(n))
def make_pad(name, pad_size, key_size):
pad = [
MAGIC,
f"
f"
*make_keys(pad_s... |
module OneTimePad (main) where
import Control.Monad
import Data.Char
import Data.Function (on)
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.Time
import System.Console.GetOpt
import System.En... |
Convert this Python snippet to Haskell and keep its semantics consistent. |
import argparse
import itertools
import pathlib
import re
import secrets
import sys
MAGIC = "
def make_keys(n, size):
return (secrets.token_hex(size) for _ in range(n))
def make_pad(name, pad_size, key_size):
pad = [
MAGIC,
f"
f"
*make_keys(pad_s... |
module OneTimePad (main) where
import Control.Monad
import Data.Char
import Data.Function (on)
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.Time
import System.Console.GetOpt
import System.En... |
Translate the given Python code snippet into Haskell without altering its behavior. | from itertools import zip_longest
fc2 =
NAME, WT, COV = 0, 1, 2
def right_type(txt):
try:
return float(txt)
except ValueError:
return txt
def commas_to_list(the_list, lines, start_indent=0):
for n, line in lines:
indent = 0
while line.startswith(' ' * (4 * indent))... |
import Data.Bifunctor (first)
import Data.Bool (bool)
import Data.Char (isSpace)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
import Data.Tree (Forest, Tree (..), foldTree)
import Numeric (showFFloat)
import System.Directory (doesFileExist)
data Coverage =... |
Preserve the algorithm and functionality while converting the code from Python to Haskell. | import re
from collections import defaultdict
from itertools import count
connection_re = r
class Graph:
def __init__(self, name, connections):
self.name = name
self.connections = connections
g = self.graph = defaultdict(list)
matches = re.finditer(connection_re, connections,
... | import Data.Maybe
import Data.List
import Control.Monad.State
import qualified Data.Map as M
import Text.Printf
type Node = Int
type Color = Int
type Graph = M.Map Node [Node]
nodes :: Graph -> [Node]
nodes = M.keys
adjacentNodes :: Graph -> Node -> [Node]
adjacentNodes g n = fromMaybe [] $ M.lookup n g
degree ... |
Port the following code from Python to Haskell with equivalent syntax and logic. | def perim_equal(p1, p2):
if len(p1) != len(p2) or set(p1) != set(p2):
return False
if any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))):
return True
p2 = p2[::-1]
return any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1)))
def edge_to_periphery(e):
edges = sorted(e)
p =... | import Data.List (find, delete, (\\))
import Control.Applicative ((<|>))
newtype Perimeter a = Perimeter [a]
deriving Show
instance Eq a => Eq (Perimeter a) where
Perimeter p1 == Perimeter p2 =
null (p1 \\ p2)
&& ((p1 `elem` zipWith const (iterate rotate p2) p1)
|| Perimeter p1 == Perimeter (rev... |
Write a version of this Python function in Elixir with identical behavior. | with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None
| defmodule LineReader do
def get_line(filename, line) do
File.stream!(filename)
|> Stream.with_index
|> Stream.filter(fn {_value, index} -> index == line-1 end)
|> Enum.at(0)
|> print_line
end
defp print_line({value, _line_number}), do: String.trim(value)
defp print_line(_), do: {:error, "Inv... |
Can you help me rewrite this code in Elixir instead of Python, keeping it the same logically? | import urllib
s = 'http://foo/bar/'
s = urllib.quote(s)
| iex(1)> URI.encode("http://foo bar/", &URI.char_unreserved?/1)
"http%3A%2F%2Ffoo%20bar%2F"
|
Rewrite this program in Elixir while keeping its functionality equivalent to the Python version. | >>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)
>>> import operator
>>> def sorttable(table, ordering=None, column=0, reverse=False):
return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)
>>> data = [["a", "b",... | defmodule Optional_parameters do
def sort( table, options\\[] ) do
options = options ++ [ ordering: :lexicographic, column: 0, reverse: false ]
ordering = options[ :ordering ]
column = options[ :column ]
reverse = options[ :reverse ]
sorted = sort( table, ordering, column )
if reverse, do: ... |
Transform the following Python implementation into Elixir, maintaining the same output and logic. | Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def f(x): return abs(x) ** 0.5 + 5 * x**3
>>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!")
for x,v in ((y, f(float(y))) for y in input('\nn... | defmodule Trabb_Pardo_Knuth do
def task do
Enum.reverse( get_11_numbers )
|> Enum.each( fn x -> perform_operation( &function(&1), 400, x ) end )
end
defp alert( n ), do: IO.puts "Operation on
defp get_11_numbers do
ns = IO.gets( "Input 11 integers. Space delimited, please: " )
|> St... |
Change the programming language of this snippet from Python to Elixir without modifying what it does. | def is_repeated(text):
'check if the first part of the string is repeated throughout the string'
for x in range(len(text)//2, 0, -1):
if text.startswith(text[x:]): return x
return 0
matchstr =
for line in matchstr.split():
ln = is_repeated(line)
print('%r has a repetition length of %i i.e.... | defmodule Rep_string do
def find(""), do: IO.puts "String was empty (no repetition)"
def find(str) do
IO.puts str
rep_pos = Enum.find(div(String.length(str),2)..1, fn pos ->
String.starts_with?(str, String.slice(str, pos..-1))
end)
if rep_pos && rep_pos>0 do
IO.puts String.duplicate(" ",... |
Please provide an equivalent version of this Python code in Elixir. | >>> from itertools import permutations
>>> def f1(p):
i = 0
while True:
p0 = p[0]
if p0 == 1: break
p[:p0] = p[:p0][::-1]
i += 1
return i
>>> def fannkuch(n):
return max(f1(list(p)) for p in permutations(range(1, n+1)))
>>> for n in range(1, 11): print(n,fannkuch(n))
1 0
2 1
3 2
4 4
5 7
6 10
7 16
8 22
... | defmodule Topswops do
def get_1_first( [1 | _t] ), do: 0
def get_1_first( list ), do: 1 + get_1_first( swap(list) )
defp swap( [n | _t]=list ) do
{swaps, remains} = Enum.split( list, n )
Enum.reverse( swaps, remains )
end
def task do
IO.puts "N\ttopswaps"
Enum.map(1..10, fn n -> {n, perm... |
Generate an equivalent Elixir version of this Python code. | >>> from itertools import product
>>> nuggets = set(range(101))
>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):
nuggets.discard(6*s + 9*n + 20*t)
>>> max(nuggets)
43
>>>
| defmodule Mcnugget do
def solve(limit) do
0..limit
|> MapSet.new()
|> MapSet.difference(
for(
x <- 0..limit,
y <- 0..limit,
z <- 0..limit,
Integer.mod(x, 6) == 0,
Integer.mod(y, 9) == 0,
Integer.mod(z, 20) == 0,
x + y + z <= limit,
into... |
Convert this Python block to Elixir, preserving its control flow and logic. |
from __future__ import division
def jaro(s, t):
s_len = len(s)
t_len = len(t)
if s_len == 0 and t_len == 0:
return 1
match_distance = (max(s_len, t_len) // 2) - 1
s_matches = [False] * s_len
t_matches = [False] * t_len
matches = 0
transpositions = 0
for i in ran... | defmodule Jaro do
def distance(s, t) when is_binary(s) and is_binary(t), do:
distance(to_charlist(s), to_charlist(t))
def distance(x, x), do: 1.0
def distance(s, t) do
s_len = length(s)
t_len = length(t)
{s_matches, t_matches, matches} = matching(s, t, s_len, t_len)
if matches == 0 do
0.... |
Port the following code from Python to Elixir with equivalent syntax and logic. | from sys import stdin, stdout
def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)
def odd(prev = lambda: None):
a = char_in()
if not a.isalpha():
prev()
char_out(a)
return a != '.'
def clos():
char_out(a)
prev()
return odd(clos)
def even():
while True:
c = char_in()
char_out(c... | defmodule Odd_word do
def handle(s, false, i, o) when ((s >= "a" and s <= "z") or (s >= "A" and s <= "Z")) do
o.(s)
handle(i.(), false, i, o)
end
def handle(s, t, i, o) when ((s >= "a" and s <= "z") or (s >= "A" and s <= "Z")) do
d = handle(i.(), :rec, i, o)
o.(s)
if t == true, do: handle(d, t... |
Produce a functionally identical Elixir code for the snippet given in Python. | >>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True... | defmodule Self_describing do
def number(n) do
digits = Integer.digits(n)
Enum.map(0..length(digits)-1, fn s ->
length(Enum.filter(digits, fn c -> c==s end))
end) == digits
end
end
m = 3300000
Enum.filter(0..m, fn n -> Self_describing.number(n) end)
|
Can you help me rewrite this code in Elixir instead of Python, keeping it the same logically? | def rotate(list, n):
for _ in range(n):
list.append(list.pop(0))
return list
def rotate(list, n):
k = (len(list) + n) % len(list)
return list[k::] + list[:k:]
list = [1,2,3,4,5,6,7,8,9]
print(list, " => ", rotate(list, 3))
| def rotate(enumerable, count) do
{left, right} = Enum.split(enumerable, count)
right ++ left
end
rotate(1..9, 3)
|
Change the following Python code into Elixir without altering its purpose. |
import curses
from random import randrange, choice
from collections import defaultdict
letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']
actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']
actions_dict = dict(zip(letter_codes, actions * 2))
def get_user_action(keyboard):
char = "N"
while char not in... | defmodule Game2048 do
@size 4
@range 0..@size-1
def play(goal \\ 2048), do: setup() |> play(goal)
defp play(board, goal) do
show(board)
cond do
goal in Map.values(board) ->
IO.puts "You win!"
exit(:normal)
0 in Map.values(board) or combinable?(board) ->
mo... |
Produce a language-to-language conversion: from Python to Elixir, same semantics. | import math
dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,
-0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,
2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193,
0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, ... | defmodule Deming do
def funnel(dxs, rule) do
{_, rxs} = Enum.reduce(dxs, {0, []}, fn dx,{x,rxs} ->
{rule.(x, dx), [x + dx | rxs]}
end)
rxs
end
def mean(xs), do: Enum.sum(xs) / length(xs)
def stddev(xs) do
m = mean(xs)
Enum.reduce(xs, 0.0, fn x,sum -> sum + (x-m)*(x-m) / length(xs... |
Generate an equivalent Elixir version of this Python code. | import math
dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,
-0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,
2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193,
0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, ... | defmodule Deming do
def funnel(dxs, rule) do
{_, rxs} = Enum.reduce(dxs, {0, []}, fn dx,{x,rxs} ->
{rule.(x, dx), [x + dx | rxs]}
end)
rxs
end
def mean(xs), do: Enum.sum(xs) / length(xs)
def stddev(xs) do
m = mean(xs)
Enum.reduce(xs, 0.0, fn x,sum -> sum + (x-m)*(x-m) / length(xs... |
Rewrite the snippet below in Elixir so it works the same as the original Python code. | while 1:
print "SPAM"
| defmodule Loops do
def infinite do
IO.puts "SPAM"
infinite
end
end
Loops.infinite
|
Rewrite the snippet below in Elixir so it works the same as the original Python code. | def multiply(x, y):
return x * y
| defmodule RosettaCode do
def multiply(x,y) do
x * y
end
def task, do: IO.puts multiply(3,5)
end
RosettaCode.task
|
Write the same code in Elixir as shown below in Python. | def cycleSort(vector):
"Sort a vector in place and return the number of writes."
writes = 0
for cycleStart, item in enumerate(vector):
pos = cycleStart
for item2 in vector[cycleStart + 1:]:
if item2 < item:
pos += 1
if pos == c... | defmodule Sort do
def cycleSort(list) do
tuple = List.to_tuple(list)
{data,writes} = Enum.reduce(0 .. tuple_size(tuple)-2, {tuple,0}, fn cycleStart,{data,writes} ->
item = elem(data, cycleStart)
pos = find_pos(data, cycleStart, item)
if pos == cycleStart do
{data, write... |
Ensure the translated Elixir code behaves exactly like the original Python snippet. | def cycleSort(vector):
"Sort a vector in place and return the number of writes."
writes = 0
for cycleStart, item in enumerate(vector):
pos = cycleStart
for item2 in vector[cycleStart + 1:]:
if item2 < item:
pos += 1
if pos == c... | defmodule Sort do
def cycleSort(list) do
tuple = List.to_tuple(list)
{data,writes} = Enum.reduce(0 .. tuple_size(tuple)-2, {tuple,0}, fn cycleStart,{data,writes} ->
item = elem(data, cycleStart)
pos = find_pos(data, cycleStart, item)
if pos == cycleStart do
{data, write... |
Convert the following code from Python to Elixir, ensuring the logic remains intact. | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i i... | iex(1)> yc = fn f -> (fn x -> x.(x) end).(fn y -> f.(fn arg -> y.(y).(arg) end) end) end
iex(2)> fac = fn f -> fn n -> if n < 2 do 1 else n * f.(n-1) end end end
iex(3)> for i <- 0..9, do: yc.(fac).(i)
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
iex(4)> fib = fn f -> fn n -> if n == 0 do 0 else (if n == 1 do 1 el... |
Generate an equivalent Elixir version of this Python code. |
from itertools import zip_longest
def beadsort(l):
return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))
print(beadsort([5,3,1,7,4,1,1]))
| defmodule Sort do
def bead_sort(list) when is_list(list), do: dist(dist(list))
defp dist(list), do: List.foldl(list, [], fn(n, acc) when n>0 -> dist(acc, n, []) end)
defp dist([], 0, acc), do: Enum.reverse(acc)
defp dist([h|t], 0, acc), do: dist(t, 0, [h |acc])
defp dist([], n, acc), do: dist(... |
Port the provided Python code into Elixir while preserving the original functionality. | import random
class Card(object):
suits = ("Clubs","Hearts","Spades","Diamonds")
pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace")
def __init__(self, pip,suit):
self.pip=pip
self.suit=suit
def __str__(self):
return "%s %s"%(self.pip,self.suit)
class De... | defmodule Card do
defstruct pip: nil, suit: nil
end
defmodule Playing_cards do
@pips ~w[2 3 4 5 6 7 8 9 10 Jack Queen King Ace]a
@suits ~w[Clubs Hearts Spades Diamonds]a
@pip_value Enum.with_index(@pips)
@suit_value Enum.with_index(@suits)
def deal( n_cards, deck ), do: Enum.split( deck, n_cards )... |
Write the same code in Elixir as shown below in Python. | def two_sum(arr, num):
i = 0
j = len(arr) - 1
while i < j:
if arr[i] + arr[j] == num:
return (i, j)
if arr[i] + arr[j] < num:
i += 1
else:
j -= 1
return None
numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))... | defmodule RC do
def two_sum(numbers, sum) do
Enum.with_index(numbers) |>
Enum.reduce_while([], fn {x,i},acc ->
y = sum - x
case Enum.find_index(numbers, &(&1 == y)) do
nil -> {:cont, acc}
j -> {:halt, [i,j]}
end
end)
end
end
numbers = [0, 2, 11, 19, 90]
IO.inspect RC... |
Please provide an equivalent version of this Python code in Elixir. | def two_sum(arr, num):
i = 0
j = len(arr) - 1
while i < j:
if arr[i] + arr[j] == num:
return (i, j)
if arr[i] + arr[j] < num:
i += 1
else:
j -= 1
return None
numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))... | defmodule RC do
def two_sum(numbers, sum) do
Enum.with_index(numbers) |>
Enum.reduce_while([], fn {x,i},acc ->
y = sum - x
case Enum.find_index(numbers, &(&1 == y)) do
nil -> {:cont, acc}
j -> {:halt, [i,j]}
end
end)
end
end
numbers = [0, 2, 11, 19, 90]
IO.inspect RC... |
Convert this Python block to Elixir, preserving its control flow and logic. | import sys
if "UTF-8" in sys.stdout.encoding:
print("△")
else:
raise Exception("Terminal can't handle UTF-8")
| if ["LANG", "LC_CTYPE", "LC_ALL"]
|> Enum.map(&System.get_env/1)
|> Enum.any?(&(&1 != nil and String.contains?(&1, "UTF")))
do
IO.puts "This terminal supports Unicode: \x{25b3}"
else
raise "This terminal does not support Unicode."
end
|
Write the same algorithm in Elixir as shown in this Python implementation. | import sys
if "UTF-8" in sys.stdout.encoding:
print("△")
else:
raise Exception("Terminal can't handle UTF-8")
| if ["LANG", "LC_CTYPE", "LC_ALL"]
|> Enum.map(&System.get_env/1)
|> Enum.any?(&(&1 != nil and String.contains?(&1, "UTF")))
do
IO.puts "This terminal supports Unicode: \x{25b3}"
else
raise "This terminal does not support Unicode."
end
|
Rewrite the snippet below in Elixir so it works the same as the original Python code. | from itertools import permutations
in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))
perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
| defmodule Sort do
def permutation_sort([]), do: []
def permutation_sort(list) do
Enum.find(permutation(list), fn [h|t] -> in_order?(t, h) end)
end
defp permutation([]), do: [[]]
defp permutation(list) do
for x <- list, y <- permutation(list -- [x]), do: [x|y]
end
defp in_order?([], _), do: t... |
Produce a functionally identical Elixir code for the snippet given in Python. | def root(a, b):
if b < 2:
return b
a1 = a - 1
c = 1
d = (a1 * c + b // (c ** a1)) // a
e = (a1 * d + b // (d ** a1)) // a
while c not in (d, e):
c, d, e = d, e, (a1 * e + b // (e ** a1)) // a
return min(d, e)
print("First 2,001 digits of the square root of two:\n{}".format(... | defmodule Integer_roots do
def root(_, b) when b<2, do: b
def root(a, b) do
a1 = a - 1
f = fn x -> (a1 * x + div(b, power(x, a1))) |> div(a) end
c = 1
d = f.(c)
e = f.(d)
until(c, d, e, f)
end
defp until(c, d, e, _) when c in [d, e], do: min(d, e)
defp until(_, d, e, f), do: until(d... |
Translate the given Python code snippet into Elixir without altering its behavior. | def root(a, b):
if b < 2:
return b
a1 = a - 1
c = 1
d = (a1 * c + b // (c ** a1)) // a
e = (a1 * d + b // (d ** a1)) // a
while c not in (d, e):
c, d, e = d, e, (a1 * e + b // (e ** a1)) // a
return min(d, e)
print("First 2,001 digits of the square root of two:\n{}".format(... | defmodule Integer_roots do
def root(_, b) when b<2, do: b
def root(a, b) do
a1 = a - 1
f = fn x -> (a1 * x + div(b, power(x, a1))) |> div(a) end
c = 1
d = f.(c)
e = f.(d)
until(c, d, e, f)
end
defp until(c, d, e, _) when c in [d, e], do: min(d, e)
defp until(_, d, e, f), do: until(d... |
Convert the following code from Python to Elixir, ensuring the logic remains intact. | import sys
import calendar
year = 2013
if len(sys.argv) > 1:
try:
year = int(sys.argv[-1])
except ValueError:
pass
for month in range(1, 13):
last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sun... | defmodule RC do
def lastSunday(year) do
Enum.map(1..12, fn month ->
lastday = :calendar.last_day_of_the_month(year, month)
daynum = :calendar.day_of_the_week(year, month, lastday)
sunday = lastday - rem(daynum, 7)
{year, month, sunday}
end)
end
end
y = String.to_integer(hd(System.... |
Please provide an equivalent version of this Python code in Elixir. | import sys
import calendar
year = 2013
if len(sys.argv) > 1:
try:
year = int(sys.argv[-1])
except ValueError:
pass
for month in range(1, 13):
last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sun... | defmodule RC do
def lastSunday(year) do
Enum.map(1..12, fn month ->
lastday = :calendar.last_day_of_the_month(year, month)
daynum = :calendar.day_of_the_week(year, month, lastday)
sunday = lastday - rem(daynum, 7)
{year, month, sunday}
end)
end
end
y = String.to_integer(hd(System.... |
Produce a functionally identical Elixir code for the snippet given in Python. | from operator import itemgetter
DEBUG = False
def spermutations(n):
sign = 1
p = [[i, 0 if i == 0 else -1]
for i in range(n)]
if DEBUG: print '
yield tuple(pp[0] for pp in p), sign
while any(pp[1] for pp in p):
i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) i... | defmodule Permutation do
def by_swap(n) do
p = Enum.to_list(0..-n) |> List.to_tuple
by_swap(n, p, 1)
end
defp by_swap(n, p, s) do
IO.puts "Perm:
k = 0 |> step_up(n, p) |> step_down(n, p)
if k > 0 do
pk = elem(p,k)
i = if pk>0, do: k+1, else: k-1
p = Enum.reduce(1..n, p, f... |
Change the programming language of this snippet from Python to Elixir without modifying what it does. |
bar = '▁▂▃▄▅▆▇█'
barcount = len(bar)
def sparkline(numbers):
mn, mx = min(numbers), max(numbers)
extent = mx - mn
sparkline = ''.join(bar[min([barcount - 1,
int((n - mn) / extent * barcount)])]
for n in numbers)
return mn, mx, sparkline
if __... | defmodule RC do
def sparkline(str) do
values = str |> String.split(~r/(,| )+/)
|> Enum.map(&elem(Float.parse(&1), 0))
{min, max} = Enum.min_max(values)
IO.puts Enum.map(values, &(round((&1 - min) / (max - min) * 7 + 0x2581)))
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.