Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same code in Swift as shown below in Python. |
def cocktailshiftingbounds(A):
beginIdx = 0
endIdx = len(A) - 1
while beginIdx <= endIdx:
newBeginIdx = endIdx
newEndIdx = beginIdx
for ii in range(beginIdx,endIdx):
if A[ii] > A[ii + 1]:
A[ii+1], A[ii] = A[ii], A[ii+1]
n... | func cocktailShakerSort<T: Comparable>(_ a: inout [T]) {
var begin = 0
var end = a.count
if end == 0 {
return
}
end -= 1
while begin < end {
var new_begin = end
var new_end = begin
var i = begin
while i < end {
if a[i + 1] < a[i] {
... |
Write a version of this Python function in Swift with identical behavior. | from itertools import count, islice
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, _seen={0: False, 1: False}):
def _isprime(n):
for p in primes():
if p*p > n:
... | import Foundation
class BitArray {
var array: [UInt32]
init(size: Int) {
array = Array(repeating: 0, count: (size + 31)/32)
}
func get(index: Int) -> Bool {
let bit = UInt32(1) << (index & 31)
return (array[index >> 5] & bit) != 0
}
func set(index: Int, value:... |
Convert the following code from Python to Swift, ensuring the logic remains intact. | def tau(n):
assert(isinstance(n, int) and 0 < n)
ans, i, j = 0, 1, 1
while i*i <= n:
if 0 == n%i:
ans += 1
j = n//i
if j != i:
ans += 1
i += 1
return ans
def is_tau_number(n):
assert(isinstance(n, int))
if n <= 0:
retur... | import Foundation
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
while (n & 1) == 0 {
total += 1
n >>= 1
}
var p = 3
while p * p <= n {
var count = 1
while n % p == 0 {
count += 1
n /= p
}
t... |
Transform the following Python implementation into Swift, maintaining the same output and logic. |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
| import Foundation
public class ScriptedMain {
public var meaningOfLife = 42
public init() {}
public class func main() {
var meaning = ScriptedMain().meaningOfLife
println("Main: The meaning of life is \(meaning)")
}
}
#if SCRIPTEDMAIN
@objc class ScriptedMainAutoload {
@objc class func load() {
... |
Change the programming language of this snippet from Python to Swift without modifying what it does. |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
| import Foundation
public class ScriptedMain {
public var meaningOfLife = 42
public init() {}
public class func main() {
var meaning = ScriptedMain().meaningOfLife
println("Main: The meaning of life is \(meaning)")
}
}
#if SCRIPTEDMAIN
@objc class ScriptedMainAutoload {
@objc class func load() {
... |
Preserve the algorithm and functionality while converting the code from Python to Swift. | 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... | import Foundation
func lastSundays(of year: Int) -> [Date] {
let calendar = Calendar.current
var dates = [Date]()
for month in 1...12 {
var dateComponents = DateComponents(calendar: calendar,
year: year,
month: month + 1,
... |
Produce a functionally identical Swift code for the snippet given in Python. | 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... | import Foundation
func lastSundays(of year: Int) -> [Date] {
let calendar = Calendar.current
var dates = [Date]()
for month in 1...12 {
var dateComponents = DateComponents(calendar: calendar,
year: year,
month: month + 1,
... |
Ensure the translated Swift code behaves exactly like the original Python snippet. |
from itertools import chain, groupby
from os.path import expanduser
from functools import reduce
def main():
print('\n'.join(
concatMap(circularGroup)(
anagrams(3)(
lines(readFile('~/mitWords.txt'))
)
)
))
def anagrams(n):
... | import Foundation
func loadDictionary(_ path: String) throws -> Set<String> {
let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii)
return Set<String>(contents.components(separatedBy: "\n").filter{!$0.isEmpty})
}
func rotate<T>(_ array: inout [T]) {
guard array.count > 1 else {
... |
Rewrite the snippet below in Swift so it works the same as the original Python code. | from collections import deque
from itertools import dropwhile, islice, takewhile
from textwrap import wrap
from typing import Iterable, Iterator
Digits = str
def esthetic_nums(base: int) -> Iterator[int]:
queue: deque[tuple[int, int]] = deque()
queue.extendleft((d, d) for d in range(1, base))
whi... | extension Sequence {
func take(_ n: Int) -> [Element] {
var res = [Element]()
for el in self {
guard res.count != n else {
return res
}
res.append(el)
}
return res
}
}
extension String {
func isEsthetic(base: Int = 10) -> Bool {
zip(dropFirst(0), dropFirst())
... |
Rewrite the snippet below in Swift so it works the same as the original Python code. |
u = 'abcdé'
print(ord(u[-1]))
| let flag = "🇵🇷"
print(flag.characters.count)
print(flag.unicodeScalars.count)
print(flag.utf16.count)
print(flag.utf8.count)
let nfc = "\u{01FA}"
let nfd = "\u{0041}\u{030A}\u{0301}"
let nfkx = "\u{FF21}\u{030A}\u{0301}"
print(nfc == nfd)
print(nfc == nfkx)
|
Write a version of this Python function in Swift with identical behavior. | 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... |
func generate<T>(array: inout [T], output: (_: [T], _: Int) -> Void) {
let n = array.count
var c = Array(repeating: 0, count: n)
var i = 1
var sign = 1
output(array, sign)
while i < n {
if c[i] < i {
if (i & 1) == 0 {
array.swapAt(0, i)
} else {
... |
Convert this Python block to Swift, preserving its control flow and logic. | def divisors(n):
divs = [1]
for ii in range(2, int(n ** 0.5) + 3):
if n % ii == 0:
divs.append(ii)
divs.append(int(n / ii))
divs.append(n)
return list(set(divs))
def sequence(max_n=None):
n = 0
while True:
n += 1
ii = 0
if max_n is not No... |
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
while n % 2 == 0 {
total += 1
n /= 2
}
var p = 3
while p * p <= n {
var count = 1
while n % p == 0 {
count += 1
n /= p
}
total *= count
... |
Produce a functionally identical Swift code for the snippet given in Python. | def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
... | import Foundation
extension Array where Element: Comparable {
@inlinable
public func longestIncreasingSubsequence() -> [Element] {
var startI = [Int](repeating: 0, count: count)
var endI = [Int](repeating: 0, count: count + 1)
var len = 0
for i in 0..<count {
var lo = 1
var hi = len
... |
Ensure the translated Swift code behaves exactly like the original Python snippet. | from primesieve.numpy import primes
from math import isqrt
import numpy as np
max_order = 9
blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]
def smallest_brilliant(lb):
pos = 1
root = isqrt(lb)
for blk in blocks:
n = len(blk)
if blk[-1]*blk[-1] < lb:
pos += n*(n... |
func primeArray(n: Int) -> [Bool] {
var primeArr = [Bool](repeating: true, count: n + 1)
primeArr[0] = false
primeArr[1] = false
var p = 2
while (p * p) <= n {
if primeArr[p] == true {
for j in stride(from: p * 2, through: n, by: p) {
primeA... |
Change the programming language of this snippet from Python to Swift without modifying what it does. | from primesieve.numpy import primes
from math import isqrt
import numpy as np
max_order = 9
blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]
def smallest_brilliant(lb):
pos = 1
root = isqrt(lb)
for blk in blocks:
n = len(blk)
if blk[-1]*blk[-1] < lb:
pos += n*(n... |
func primeArray(n: Int) -> [Bool] {
var primeArr = [Bool](repeating: true, count: n + 1)
primeArr[0] = false
primeArr[1] = false
var p = 2
while (p * p) <= n {
if primeArr[p] == true {
for j in stride(from: p * 2, through: n, by: p) {
primeA... |
Ensure the translated Swift code behaves exactly like the original Python snippet. | from __future__ import print_function
def order_disjoint_list_items(data, items):
itemindices = []
for item in set(items):
itemcount = items.count(item)
lastindex = [-1]
for i in range(itemcount):
lastindex.append(data.index(item, lastindex[-1] + 1))
it... | func disjointOrder<T: Hashable>(m: [T], n: [T]) -> [T] {
let replaceCounts = n.reduce(into: [T: Int](), { $0[$1, default: 0] += 1 })
let reduced = m.reduce(into: ([T](), n, replaceCounts), {cur, el in
cur.0.append(cur.2[el, default: 0] > 0 ? cur.1.removeFirst() : el)
cur.2[el]? -= 1
})
return reduced.0... |
Produce a language-to-language conversion: from Python to Swift, same semantics. | for i in range(65,123):
check = 1
for j in range(2,i):
if i%j == 0:
check = 0
if check==1:
print(chr(i),end='')
| import Foundation
class BitArray {
var array: [UInt32]
init(size: Int) {
array = Array(repeating: 0, count: (size + 31)/32)
}
func get(index: Int) -> Bool {
let bit = UInt32(1) << (index & 31)
return (array[index >> 5] & bit) != 0
}
func set(index: Int, value:... |
Translate the given Python code snippet into Swift without altering its behavior. | for i in range(65,123):
check = 1
for j in range(2,i):
if i%j == 0:
check = 0
if check==1:
print(chr(i),end='')
| import Foundation
class BitArray {
var array: [UInt32]
init(size: Int) {
array = Array(repeating: 0, count: (size + 31)/32)
}
func get(index: Int) -> Bool {
let bit = UInt32(1) << (index & 31)
return (array[index >> 5] & bit) != 0
}
func set(index: Int, value:... |
Please provide an equivalent version of this Python code in Swift. |
from functools import reduce
from itertools import count, islice
def sylvester():
def go(n):
return 1 + reduce(
lambda a, x: a * go(x),
range(0, n),
1
) if 0 != n else 2
return map(go, count(0))
def main():
print("First 10 terms of OEI... | import BigNumber
func sylvester(n: Int) -> BInt {
var a = BInt(2)
for _ in 0..<n {
a = a * a - a + 1
}
return a
}
var sum = BDouble(0)
for n in 0..<10 {
let syl = sylvester(n: n)
sum += BDouble(1) / BDouble(syl)
print(syl)
}
print("Sum of the reciprocals of first ten in sequence: \(sum)")
|
Generate an equivalent Swift version of this Python code. | import random
print(random.sample(range(1, 21), 20))
| var array = Array(1...20)
array.shuffle()
print(array)
|
Convert this Python snippet to Swift and keep its semantics consistent. |
var x = 0
var y = 0
There are also multi-line comments
Everything inside of
]
discard
|
*/
|
Translate this program into Swift but keep the logic exactly as in Python. |
def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':
n = R-L
if n < 2:
return 0
swaps = 0
m = n//2
for i in range(m):
if A[R-(i+1)] < A[L+i]:
(A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)
swaps += 1
if ... | func circleSort<T: Comparable>(_ array: inout [T]) {
func circSort(low: Int, high: Int, swaps: Int) -> Int {
if low == high {
return swaps
}
var lo = low
var hi = high
let mid = (hi - lo) / 2
var s = swaps
while lo < hi {
if array[lo] >... |
Produce a functionally identical Swift code for the snippet given in Python. | from collections import namedtuple
from math import sqrt
Pt = namedtuple('Pt', 'x, y')
Circle = Cir = namedtuple('Circle', 'x, y, r')
def circles_from_p1p2r(p1, p2, r):
'Following explanation at http://mathforum.org/library/drmath/view/53027.html'
if r == 0.0:
raise ValueError('radius of zero')
(x... | import Foundation
struct Point: Equatable {
var x: Double
var y: Double
}
struct Circle {
var center: Point
var radius: Double
static func circleBetween(
_ p1: Point,
_ p2: Point,
withRadius radius: Double
) -> (Circle, Circle?)? {
func applyPoint(_ p1: Point, _ p2: Point, op: (Double... |
Ensure the translated Swift code behaves exactly like the original Python snippet. | from collections import namedtuple
from math import sqrt
Pt = namedtuple('Pt', 'x, y')
Circle = Cir = namedtuple('Circle', 'x, y, r')
def circles_from_p1p2r(p1, p2, r):
'Following explanation at http://mathforum.org/library/drmath/view/53027.html'
if r == 0.0:
raise ValueError('radius of zero')
(x... | import Foundation
struct Point: Equatable {
var x: Double
var y: Double
}
struct Circle {
var center: Point
var radius: Double
static func circleBetween(
_ p1: Point,
_ p2: Point,
withRadius radius: Double
) -> (Circle, Circle?)? {
func applyPoint(_ p1: Point, _ p2: Point, op: (Double... |
Can you help me rewrite this code in Swift instead of Python, keeping it the same logically? | from __future__ import division
import math
from operator import mul
from itertools import product
from functools import reduce
def fac(n):
step = lambda x: 1 + x*4 - (x//2)*2
maxq = int(math.floor(math.sqrt(n)))
d = 1
q = n % 2 == 0 and 2 or 3
while q <= maxq and n % q != 0:
q = st... | import Foundation
func vampire<T>(n: T) -> [(T, T)] where T: BinaryInteger, T.Stride: SignedInteger {
let strN = String(n).sorted()
let fangLength = strN.count / 2
let start = T(pow(10, Double(fangLength - 1)))
let end = T(Double(n).squareRoot())
var fangs = [(T, T)]()
for i in start...end where n % i ==... |
Rewrite this program in Swift while keeping its functionality equivalent to the Python version. | import time
from pygame import mixer
mixer.init(frequency=16000)
s1 = mixer.Sound('test.wav')
s2 = mixer.Sound('test2.wav')
s1.play(-1)
time.sleep(0.5)
s2.play()
time.sleep(2)
s2.play(2)
time.sleep(10)
s1.set_volume(0.1)
time.sleep(5)
s1.set_volume(1)
time.sleep(5)
s1.stop()
s2.st... | import AVFoundation
class PlayerControl: NSObject, AVAudioPlayerDelegate {
let player1:AVAudioPlayer!
let player2:AVAudioPlayer!
var playedBoth = false
var volume:Float {
get {
return player1.volume
}
set {
player1.volume = newValue
... |
Change the programming language of this snippet from Python to Swift without modifying what it does. | def nonoblocks(blocks, cells):
if not blocks or blocks[0] == 0:
yield [(0, 0)]
else:
assert sum(blocks) + len(blocks)-1 <= cells, \
'Those blocks will not fit in those cells'
blength, brest = blocks[0], blocks[1:]
minspace4rest = sum(1+b for b in brest)
... | import Foundation
func nonoblock(cells: Int, blocks: [Int]) {
print("\(cells) cells and blocks \(blocks):")
let totalBlockSize = blocks.reduce(0, +)
if cells < totalBlockSize + blocks.count - 1 {
print("no solution")
return
}
func solve(cells: Int, index: Int, totalBlockSize: Int, ... |
Port the following code from Python to Swift with equivalent syntax and logic. | def nonoblocks(blocks, cells):
if not blocks or blocks[0] == 0:
yield [(0, 0)]
else:
assert sum(blocks) + len(blocks)-1 <= cells, \
'Those blocks will not fit in those cells'
blength, brest = blocks[0], blocks[1:]
minspace4rest = sum(1+b for b in brest)
... | import Foundation
func nonoblock(cells: Int, blocks: [Int]) {
print("\(cells) cells and blocks \(blocks):")
let totalBlockSize = blocks.reduce(0, +)
if cells < totalBlockSize + blocks.count - 1 {
print("no solution")
return
}
func solve(cells: Int, index: Int, totalBlockSize: Int, ... |
Keep all operations the same but rewrite the snippet in Swift. |
import strformat
import tables
type Item = tuple[name: string; weight, value, pieces: int]
const Items: seq[Item] = @[("map", 9, 150, 1),
("compass", 13, 35, 1),
("water", 153, 200, 2),
("sandwich", 50, 60, 2),
... | public struct KnapsackItem: Hashable {
public var name: String
public var weight: Int
public var value: Int
public init(name: String, weight: Int, value: Int) {
self.name = name
self.weight = weight
self.value = value
}
}
public func knapsack(items: [KnapsackItem], limit: Int) -> [KnapsackItem] ... |
Write a version of this Python function in Swift with identical behavior. | PI = 3.141592653589793
TWO_PI = 6.283185307179586
def normalize2deg(a):
while a < 0: a += 360
while a >= 360: a -= 360
return a
def normalize2grad(a):
while a < 0: a += 400
while a >= 400: a -= 400
return a
def normalize2mil(a):
while a < 0: a += 6400
while a >= 6400: a -= 6400
return a
def normalize... | import Foundation
func normalize(_ f: Double, N: Double) -> Double {
var a = f
while a < -N { a += N }
while a >= N { a -= N }
return a
}
func normalizeToDeg(_ f: Double) -> Double {
return normalize(f, N: 360)
}
func normalizeToGrad(_ f: Double) -> Double {
return normalize(f, N: 400)
}
func normaliz... |
Transform the following Python implementation into Swift, maintaining the same output and logic. | import urllib.request
import re
PLAUSIBILITY_RATIO = 2
def plausibility_check(comment, x, y):
print('\n Checking plausibility of: %s' % comment)
if x > PLAUSIBILITY_RATIO * y:
print(' PLAUSIBLE. As we have counts of %i vs %i, a ratio of %4.1f times'
% (x, y, x / y))
else:
... | import Foundation
let request = NSURLRequest(URL: NSURL(string: "http:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {res, data, err in
if (data != nil) {
if let fileAsString = NSString(data: data, encoding: NSUTF8StringEncoding) {
var firstCase = false
... |
Keep all operations the same but rewrite the snippet in Swift. | import urllib.request
import re
PLAUSIBILITY_RATIO = 2
def plausibility_check(comment, x, y):
print('\n Checking plausibility of: %s' % comment)
if x > PLAUSIBILITY_RATIO * y:
print(' PLAUSIBLE. As we have counts of %i vs %i, a ratio of %4.1f times'
% (x, y, x / y))
else:
... | import Foundation
let request = NSURLRequest(URL: NSURL(string: "http:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {res, data, err in
if (data != nil) {
if let fileAsString = NSString(data: data, encoding: NSUTF8StringEncoding) {
var firstCase = false
... |
Convert this Python block to Swift, preserving its control flow and logic. |
from __future__ import division
import sys
from PIL import Image
def _fpart(x):
return x - int(x)
def _rfpart(x):
return 1 - _fpart(x)
def putpixel(img, xy, color, alpha=1):
compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))
c = compose_color(img.getpixel(xy), color)
i... | import Darwin
public func pixel(color: Color, x: Int, y: Int) {
let idx = x + y * self.width
if idx >= 0 && idx < self.bitmap.count {
self.bitmap[idx] = self.blendColors(bot: self.bitmap[idx], top: color)
}
}
func fpart(_ x: Double) -> Double {
return modf(x).1
}
func rfpart(_ x: Double) ->... |
Convert this Python snippet to Swift and keep its semantics consistent. | import random
from collections import OrderedDict
numbers = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 's... | import Foundation
func fourIsMagic(_ number: NSNumber) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
formatter.locale = Locale(identifier: "en_EN")
var result: [String] = []
var numberString = formatter.string(from: number)!
result.append(numberString.capital... |
Change the following Python code into Swift without altering its purpose. |
beforeTxt =
smallrc01 =
rc01 =
def intarray(binstring):
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
Return 8-neighb... | import UIKit
let beforeTxt = """
1100111
1100111
1100111
1100111
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1111110
0000000
"""
let smallrc01 = """
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
0111000111100000... |
Please provide an equivalent version of this Python code in Swift. | >>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
if p.index('B') % 2 != p.index('b') % 2
and ( p.index('r') < p.index('K') < p.index('R')
or p.index('R') < p.index('K') <... | func isValid960Position(_ firstRank: String) -> Bool {
var rooksPlaced = 0
var bishopColor = -1
for (i, piece) in firstRank.enumerated() {
switch piece {
case "♚" where rooksPlaced != 1:
return false
case "♜":
rooksPlaced += 1
case "♝" where bishopColor == -1:
bishopColor = i & ... |
Maintain the same structure and functionality when rewriting this code in Swift. | irregularOrdinals = {
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
def num2ordinal(n):
conversion = int(float(n))
num = spell_integer(conversion)
hyphen = num.rsplit("-", 1)
num = num.rsplit(" ", 1)
... | fileprivate class NumberNames {
let cardinal: String
let ordinal: String
init(cardinal: String, ordinal: String) {
self.cardinal = cardinal
self.ordinal = ordinal
}
func getName(_ ordinal: Bool) -> String {
return ordinal ? self.ordinal : self.cardinal
}
cl... |
Produce a functionally identical Swift code for the snippet given in Python. | import ctypes
import os
from ctypes import c_ubyte, c_int
code = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])
code_size = len(code)
if (os.name == 'posix'):
import mmap
executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EX... | import Foundation
typealias TwoIntsOneInt = @convention(c) (Int, Int) -> Int
let code = [
144,
144,
106, 12,
184, 7, 0, 0, 0,
72, 193, 224, 32,
80,
139, 68, 36, 4, 3, 68, 36, 8,
76, 137, 227,
137, 195,
72, 193, 227, 4,
128, 203, 2,
72, 131, 196, 16,
195,
] as [UInt8]
func fudge(x: Int... |
Produce a functionally identical Swift code for the snippet given in Python. | assert 1.008 == molar_mass('H')
assert 2.016 == molar_mass('H2')
assert 18.015 == molar_mass('H2O')
assert 34.014 == molar_mass('H2O2')
assert 34.014 == molar_mass('(HO)2')
assert 142.036 == molar_mass('Na2SO4')
assert ... | import Foundation
struct Chem {
struct Molecule {
var formula: String
var parts: [Molecule]
var quantity = 1
var molarMass: Double {
switch parts.count {
case 0:
return Chem.atomicWeights[formula]! * Double(quantity)
case _:
return parts.lazy.map({ $0.molarMass }).r... |
Write a version of this Python function in Swift with identical behavior. | from fractions import Fraction
class Fr(Fraction):
def __repr__(self):
return '(%s/%s)' % (self.numerator, self.denominator)
def farey(n, length=False):
if not length:
return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})
else:
return (n*(... | class Farey {
let n: Int
init(_ x: Int) {
n = x
}
var sequence: [(Int,Int)] {
var a = 0
var b = 1
var c = 1
var d = n
var results = [(a, b)]
while c <= n {
let k = (n + b) / d
let oldA = a
let oldB = b
... |
Ensure the translated Swift code behaves exactly like the original Python snippet. | from fractions import Fraction
class Fr(Fraction):
def __repr__(self):
return '(%s/%s)' % (self.numerator, self.denominator)
def farey(n, length=False):
if not length:
return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})
else:
return (n*(... | class Farey {
let n: Int
init(_ x: Int) {
n = x
}
var sequence: [(Int,Int)] {
var a = 0
var b = 1
var c = 1
var d = n
var results = [(a, b)]
while c <= n {
let k = (n + b) / d
let oldA = a
let oldB = b
... |
Convert the following code from Python to Swift, ensuring the logic remains intact. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new =... | extension BinaryInteger {
@inlinable
public func factors(sorted: Bool = true) -> [Self] {
let maxN = Self(Double(self).squareRoot())
var res = Set<Self>()
for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {
res.insert(factor)
res.insert(self / factor)
}
r... |
Port the following code from Python to Swift with equivalent syntax and logic. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new =... | extension BinaryInteger {
@inlinable
public func factors(sorted: Bool = true) -> [Self] {
let maxN = Self(Double(self).squareRoot())
var res = Set<Self>()
for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {
res.insert(factor)
res.insert(self / factor)
}
r... |
Keep all operations the same but rewrite the snippet in Swift. | from collections import defaultdict
from itertools import product
from pprint import pprint as pp
cube2n = {x**3:x for x in range(1, 1201)}
sum2cubes = defaultdict(set)
for c1, c2 in product(cube2n, cube2n):
if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))
taxied = sorted((k, v) for k,v in sum2cubes.it... | extension Array {
func combinations(_ k: Int) -> [[Element]] {
return Self._combinations(slice: self[startIndex...], k)
}
static func _combinations(slice: Self.SubSequence, _ k: Int) -> [[Element]] {
guard k != 1 else {
return slice.map({ [$0] })
}
guard k != slice.count else {
retur... |
Write the same algorithm in Swift as shown in this Python implementation. | import numpy as np
def primesfrom2to(n):
sieve = np.ones(n//3 + (n%6==2), dtype=np.bool)
sieve[0] = False
for i in range(int(n**0.5)//3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)//3) ::2*k] = False
sieve[(k*k+4*k-2*k*(i&1))//3::2*k] = False
... | import Foundation
class PrimeSieve {
var composite: [Bool]
init(size: Int) {
composite = Array(repeating: false, count: size/2)
var p = 3
while p * p <= size {
if !composite[p/2 - 1] {
let inc = p * 2
var q = p * p
while q... |
Convert this Python block to Swift, preserving its control flow and logic. | from itertools import islice
def lfact():
yield 0
fact, summ, n = 1, 0, 1
while 1:
fact, summ, n = fact*n, summ + fact, n + 1
yield summ
print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 10)... | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
prefix func ! <T: BinaryInteger>(n: T) -> T {
guard n != 0 else {
return 0
}
return stride(from: 0, to: n, by: 1).lazy.map(factorial).reduce(0, +)
}
... |
Produce a language-to-language conversion: from Python to Swift, same semantics. | from itertools import islice
def lfact():
yield 0
fact, summ, n = 1, 0, 1
while 1:
fact, summ, n = fact*n, summ + fact, n + 1
yield summ
print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 10)... | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
prefix func ! <T: BinaryInteger>(n: T) -> T {
guard n != 0 else {
return 0
}
return stride(from: 0, to: n, by: 1).lazy.map(factorial).reduce(0, +)
}
... |
Port the provided Python code into Swift while preserving the original functionality. | from sympy import primerange
def strange_triplets(mx: int = 30) -> None:
primes = list(primerange(0, mx))
primes3 = set(primerange(0, 3 * mx))
for i, n in enumerate(primes):
for j, m in enumerate(primes[i + 1:], i + 1):
for p in primes[j + 1:]:
if n + m + p in primes3:
... | import Foundation
func primeSieve(limit: Int) -> [Bool] {
guard limit > 0 else {
return []
}
var sieve = Array(repeating: true, count: limit)
sieve[0] = false
if limit > 1 {
sieve[1] = false
}
if limit > 4 {
for i in stride(from: 4, to: limit, by: 2) {
si... |
Write the same code in Swift as shown below in Python. | from sympy import primerange
def strange_triplets(mx: int = 30) -> None:
primes = list(primerange(0, mx))
primes3 = set(primerange(0, 3 * mx))
for i, n in enumerate(primes):
for j, m in enumerate(primes[i + 1:], i + 1):
for p in primes[j + 1:]:
if n + m + p in primes3:
... | import Foundation
func primeSieve(limit: Int) -> [Bool] {
guard limit > 0 else {
return []
}
var sieve = Array(repeating: true, count: limit)
sieve[0] = false
if limit > 1 {
sieve[1] = false
}
if limit > 4 {
for i in stride(from: 4, to: limit, by: 2) {
si... |
Preserve the algorithm and functionality while converting the code from Python to Swift. |
from sympy import isprime
def motzkin(num_wanted):
mot = [1] * (num_wanted + 1)
for i in range(2, num_wanted + 1):
mot[i] = (mot[i-1]*(2*i+1) + mot[i-2]*(3*i-3)) // (i + 2)
return mot
def print_motzkin_table(N=41):
print(
" n M[n] Prime?\n------------... | import Foundation
extension BinaryInteger {
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) where self % i == 0 {
... |
Generate an equivalent Swift version of this Python code. | def divisors(n):
divs = [1]
for ii in range(2, int(n ** 0.5) + 3):
if n % ii == 0:
divs.append(ii)
divs.append(int(n / ii))
divs.append(n)
return list(set(divs))
def is_prime(n):
return len(divisors(n)) == 2
def digit_check(n):
if len(str(n))<2:
return... | func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
if number % 2 == 0 {
return number == 2
}
if number % 3 == 0 {
return number == 3
}
if number % 5 == 0 {
return number == 5
}
var p = 7
let wheel = [4,2,4,2,4,6,2,6]
while true ... |
Rewrite this program in Swift while keeping its functionality equivalent to the Python version. |
from itertools import count, islice
def a131382():
return (
elemIndex(x)(
productDigitSums(x)
) for x in count(1)
)
def productDigitSums(n):
return (digitSum(n * x) for x in count(0))
def main():
print(
table(10)([
str(x) for x ... | import Foundation
func digitSum(_ num: Int) -> Int {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
for n in 1...70 {
for m in 1... {
if digitSum(m * n) == n {
print(String(format: "%8d", m), terminator: n % 10 == 0 ? "\n" : " ")
... |
Transform the following Python implementation into Swift, maintaining the same output and logic. | def quad(top=2200):
r = [False] * top
ab = [False] * (top * 2)**2
for a in range(1, top):
for b in range(a, top):
ab[a * a + b * b] = True
s = 3
for c in range(1, top):
s1, s, s2 = s, s + 2, s + 2
for d in range(c + 1, top):
if ab[s1]:
... | func missingD(upTo n: Int) -> [Int] {
var a2 = 0, s = 3, s1 = 0, s2 = 0
var res = [Int](repeating: 0, count: n + 1)
var ab = [Int](repeating: 0, count: n * n * 2 + 1)
for a in 1...n {
a2 = a * a
for b in a...n {
ab[a2 + b * b] = 1
}
}
for c in 1..<n {
s1 = s
s += 2
s2 = s
... |
Produce a language-to-language conversion: from Python to Swift, same semantics. | primes =[]
sp =[]
usp=[]
n = 10000000
if 2<n:
primes.append(2)
for i in range(3,n+1,2):
for j in primes:
if(j>i/2) or (j==primes[-1]):
primes.append(i)
if((i-1)/2) in primes:
sp.append(i)
break
else:
usp.append(i)
... | import Foundation
class PrimeSieve {
var composite: [Bool]
init(size: Int) {
composite = Array(repeating: false, count: size/2)
var p = 3
while p * p <= size {
if !composite[p/2 - 1] {
let inc = p * 2
var q = p * p
while q... |
Can you help me rewrite this code in Swift instead of Python, keeping it the same logically? | from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
for s in table1:
h[s[index1]].append(s)
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "... | func hashJoin<A, B, K: Hashable>(_ first: [(K, A)], _ second: [(K, B)]) -> [(A, K, B)] {
var map = [K: [B]]()
for (key, val) in second {
map[key, default: []].append(val)
}
var res = [(A, K, B)]()
for (key, val) in first {
guard let vals = map[key] else {
continue
}
res += vals.map({... |
Keep all operations the same but rewrite the snippet in Swift. |
import time
print "\033[?1049h\033[H"
print "Alternate buffer!"
for i in xrange(5, 0, -1):
print "Going back in:", i
time.sleep(1)
print "\033[?1049l"
| public let CSI = ESC+"["
func write(_ text: String...) {
for txt in text { write(STDOUT_FILENO, txt, txt.utf8.count) }
}
write(CSI,"?1049h")
print("Alternate screen buffer\n")
for n in (1...5).reversed() {
print("Going back in \(n)...")
sleep(1)
}
write(CSI,"?1049l")
|
Preserve the algorithm and functionality while converting the code from Python to Swift. | import pyttsx
engine = pyttsx.init()
engine.say("It was all a dream.")
engine.runAndWait()
| import Foundation
let task = NSTask()
task.launchPath = "/usr/bin/say"
task.arguments = ["This is an example of speech synthesis."]
task.launch()
|
Maintain the same structure and functionality when rewriting this code in Swift. |
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from ... | import Darwin
import Foundation
var solution = ""
println("24 Game")
println("Generating 4 digits...")
func randomDigits() -> [Int] {
var result = [Int]()
for i in 0 ..< 4 {
result.append(Int(arc4random_uniform(9)+1))
}
return result
}
let digits = randomDigits()
print("Make 24 using these digits : ")... |
Generate an equivalent Swift version of this Python code. |
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from ... | import Darwin
import Foundation
var solution = ""
println("24 Game")
println("Generating 4 digits...")
func randomDigits() -> [Int] {
var result = [Int]()
for i in 0 ..< 4 {
result.append(Int(arc4random_uniform(9)+1))
}
return result
}
let digits = randomDigits()
print("Make 24 using these digits : ")... |
Rewrite the snippet below in Swift so it works the same as the original Python code. | from itertools import islice, count
def superd(d):
if d != int(d) or not 2 <= d <= 9:
raise ValueError("argument must be integer from 2 to 9 inclusive")
tofind = str(d) * d
for n in count(2):
if tofind in str(d * n ** d):
yield n
if __name__ == '__main__':
for d in range(2,... | import BigInt
import Foundation
let rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"]
for d in 2...9 {
print("First 10 super-\(d) numbers:")
var count = 0
var n = BigInt(3)
var k = BigInt(0)
while true {
k = n.power(d)
k *= BigInt(d)
if let _ = String(k).range(... |
Rewrite this program in Swift while keeping its functionality equivalent to the Python version. | from math import floor
from collections import deque
from typing import Dict, Generator
def padovan_r() -> Generator[int, None, None]:
last = deque([1, 1, 1], 4)
while True:
last.append(last[-2] + last[-3])
yield last.popleft()
_p, _s = 1.324717957244746025960908854, 1.0453567932525329623
de... | import Foundation
class PadovanRecurrence: Sequence, IteratorProtocol {
private var p = [1, 1, 1]
private var n = 0
func next() -> Int? {
let pn = n < 3 ? p[n] : p[0] + p[1]
p[0] = p[1]
p[1] = p[2]
p[2] = pn
n += 1
return pn
}
}
class PadovanFloor: ... |
Maintain the same structure and functionality when rewriting this code in Swift. |
from __future__ import annotations
from typing import Any
from typing import Callable
from typing import Generic
from typing import Optional
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Maybe(Generic[T]):
def __init__(self, value: Union[Optional[T], Maybe[T]] = None):
if ... | precedencegroup MonadPrecedence {
higherThan: BitwiseShiftPrecedence
associativity: left
}
infix operator >>-: MonadPrecedence
typealias Maybe = Optional
extension Maybe
{
static func unit(_ x: Wrapped) -> Maybe<Wrapped>
{
return Maybe(x)
}
func bind<T>(_ f: (Wrapped) -> Maybe<T>) -> Maybe<T>
{
return s... |
Produce a language-to-language conversion: from Python to Swift, same semantics. |
from __future__ import annotations
from itertools import chain
from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar
T = TypeVar("T")
class MList(List[T]):
@classmethod
def unit(cls, value: Iterable[T]) -> MList[T]:
return... | precedencegroup MonadPrecedence {
higherThan: BitwiseShiftPrecedence
associativity: left
}
infix operator >>-: MonadPrecedence
extension Array
{
static func unit(_ x: Element) -> [Element]
{
return [x]
}
func bind<T>(_ f: (Element) -> [T]) -> [T]
{
return flatMap(f)
}
static func >>- <U>(_ m: [Element... |
Write the same algorithm in Swift as shown in this Python implementation. | from collections import defaultdict
import urllib.request
CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}
URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
def getwords(url):
return urllib.request.urlopen(url).read().decode("utf-8").lower(... | import Foundation
func textCharacter(_ ch: Character) -> Character? {
switch (ch) {
case "a", "b", "c":
return "2"
case "d", "e", "f":
return "3"
case "g", "h", "i":
return "4"
case "j", "k", "l":
return "5"
case "m", "n", "o":
return "6"
case "p", "q... |
Please provide an equivalent version of this Python code in Swift. |
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
... | func succ<A, B, C>(_ n: @escaping (@escaping (A) -> B) -> (C) -> A) -> (@escaping (A) -> B) -> (C) -> B {
return {f in
return {x in
return f(n(f)(x))
}
}
}
func zero<A, B>(_ a: A) -> (B) -> B {
return {b in
return b
}
}
func three<A>(_ f: @escaping (A) -> A) -> (A) -> A {
return {x in
... |
Generate a Swift translation of this Python snippet without changing its computational steps. |
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
... | func succ<A, B, C>(_ n: @escaping (@escaping (A) -> B) -> (C) -> A) -> (@escaping (A) -> B) -> (C) -> B {
return {f in
return {x in
return f(n(f)(x))
}
}
}
func zero<A, B>(_ a: A) -> (B) -> B {
return {b in
return b
}
}
func three<A>(_ f: @escaping (A) -> A) -> (A) -> A {
return {x in
... |
Maintain the same structure and functionality when rewriting this code in Swift. | class Example(object):
def foo(self, x):
return 42 + x
name = "foo"
getattr(Example(), name)(5)
| import Foundation
class MyUglyClass: NSObject {
@objc
func myUglyFunction() {
print("called myUglyFunction")
}
}
let someObject: NSObject = MyUglyClass()
someObject.perform(NSSelectorFromString("myUglyFunction"))
|
Translate the given Python code snippet into Swift without altering its behavior. | import pyprimes
def primorial_prime(_pmax=500):
isprime = pyprimes.isprime
n, primo = 0, 1
for prime in pyprimes.nprimes(_pmax):
n, primo = n+1, primo * prime
if isprime(primo-1) or isprime(primo+1):
yield n
if __name__ == '__main__':
pyprimes.warn_probably = F... | import BigInt
import Foundation
extension BinaryInteger {
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) where self ... |
Ensure the translated Swift code behaves exactly like the original Python snippet. | from __future__ import print_function
from scipy.misc import factorial as fact
from scipy.misc import comb
def perm(N, k, exact=0):
return comb(N, k, exact) * fact(k, exact)
exact=True
print('Sample Perms 1..12')
for N in range(1, 13):
k = max(N-2, 1)
print('%iP%i =' % (N, k), perm(N, k, exact), end=', '... | import BigInt
func permutations(n: Int, k: Int) -> BigInt {
let l = n - k + 1
guard l <= n else {
return 1
}
return (l...n).reduce(BigInt(1), { $0 * BigInt($1) })
}
func combinations(n: Int, k: Int) -> BigInt {
let fact = {() -> BigInt in
guard k > 1 else {
return 1
}
return (2...k)... |
Generate a Swift translation of this Python snippet without changing its computational steps. | def sieve(limit):
primes = []
c = [False] * (limit + 1)
p = 3
while True:
p2 = p * p
if p2 > limit: break
for i in range(p2, limit, 2 * p): c[i] = True
while True:
p += 2
if not c[p]: break
for i in range(3, limit, 2):
if not c[i... | public struct Eratosthenes: Sequence, IteratorProtocol {
private let n: Int
private let limit: Int
private var i = 2
private var sieve: [Int]
public init(upTo: Int) {
if upTo <= 1 {
self.n = 0
self.limit = -1
self.sieve = []
} else {
self.n = upTo
self.limit = Int(Doubl... |
Produce a language-to-language conversion: from Python to Swift, same semantics. | from collections import namedtuple
from pprint import pprint as pp
OpInfo = namedtuple('OpInfo', 'prec assoc')
L, R = 'Left Right'.split()
ops = {
'^': OpInfo(prec=4, assoc=R),
'*': OpInfo(prec=3, assoc=L),
'/': OpInfo(prec=3, assoc=L),
'+': OpInfo(prec=2, assoc=L),
'-': OpInfo(prec=2, assoc=L),
'(': OpInfo(pre... |
import Foundation
struct Stack<T> {
private(set) var elements = [T]()
var isEmpty: Bool {
elements.isEmpty
}
var top: T? {
elements.last
}
mutating func push(_ newElement: T) {
elements.append(newElement)
}
mutating func pop() -> T? {
self.isEmpty ? nil : elements.removeLast()
}
}
struct Qu... |
Can you help me rewrite this code in Swift instead of Python, keeping it the same logically? | import math
def perlin_noise(x, y, z):
X = math.floor(x) & 255
Y = math.floor(y) & 255
Z = math.floor(z) & 255
x -= math.floor(x)
y -= math.floor(y)
z -= math.floor(z)
u = fade(x) ... | import Foundation
struct Perlin {
private static let permutation = [
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, ... |
Convert this Python block to Swift, preserving its control flow and logic. | from __future__ import print_function
def add_reverse(num, max_iter=1000):
i, nums = 0, {num}
while True:
i, num = i+1, num + reverse_int(num)
nums.add(num)
if reverse_int(num) == num or i >= max_iter:
break
return nums
def reverse_int(num):
return int(str(num)... | import BigInt
public struct Lychrel<T: ReversibleNumeric & CustomStringConvertible>: Sequence, IteratorProtocol {
@usableFromInline
let seed: T
@usableFromInline
var done = false
@usableFromInline
var n: T
@usableFromInline
var iterations: T
@inlinable
public init(seed: T, iterations: T = 500) ... |
Produce a functionally identical Swift code for the snippet given in Python. | from __future__ import print_function
def add_reverse(num, max_iter=1000):
i, nums = 0, {num}
while True:
i, num = i+1, num + reverse_int(num)
nums.add(num)
if reverse_int(num) == num or i >= max_iter:
break
return nums
def reverse_int(num):
return int(str(num)... | import BigInt
public struct Lychrel<T: ReversibleNumeric & CustomStringConvertible>: Sequence, IteratorProtocol {
@usableFromInline
let seed: T
@usableFromInline
var done = false
@usableFromInline
var n: T
@usableFromInline
var iterations: T
@inlinable
public init(seed: T, iterations: T = 500) ... |
Convert this Python snippet to Swift and keep its semantics consistent. | from math import log, modf, floor
def p(l, n, pwr=2):
l = int(abs(l))
digitcount = floor(log(l, 10))
log10pwr = log(pwr, 10)
raised, found = -1, 0
while found < n:
raised += 1
firstdigits = floor(10**(modf(log10pwr * raised)[0] + digitcount))
if firstdigits == l:
... | let ld10 = log(2.0) / log(10.0)
func p(L: Int, n: Int) -> Int {
var l = L
var digits = 1
while l >= 10 {
digits *= 10
l /= 10
}
var count = 0
var i = 0
while count < n {
let rhs = (Double(i) * ld10).truncatingRemainder(dividingBy: 1)
let e = exp(log(10.0) * rhs)
if Int(e * Double(... |
Convert this Python block to Swift, preserving its control flow and logic. | from math import log, modf, floor
def p(l, n, pwr=2):
l = int(abs(l))
digitcount = floor(log(l, 10))
log10pwr = log(pwr, 10)
raised, found = -1, 0
while found < n:
raised += 1
firstdigits = floor(10**(modf(log10pwr * raised)[0] + digitcount))
if firstdigits == l:
... | let ld10 = log(2.0) / log(10.0)
func p(L: Int, n: Int) -> Int {
var l = L
var digits = 1
while l >= 10 {
digits *= 10
l /= 10
}
var count = 0
var i = 0
while count < n {
let rhs = (Double(i) * ld10).truncatingRemainder(dividingBy: 1)
let e = exp(log(10.0) * rhs)
if Int(e * Double(... |
Maintain the same structure and functionality when rewriting this code in Swift. | import random
def is_Prime(n):
if n!=int(n):
return False
n=int(n)
if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
return False
if n==2 or n==3 or n==5 or n==7:
return True
s = 0
d = n-1
while d%2==0:
d>>=1
s+=1
assert(2**s * d == n-1... | import BigInt
import Foundation
public func pierpoint(n: Int) -> (first: [BigInt], second: [BigInt]) {
var primes = (first: [BigInt](repeating: 0, count: n), second: [BigInt](repeating: 0, count: n))
primes.first[0] = 2
var count1 = 1, count2 = 0
var s = [BigInt(1)]
var i2 = 0, i3 = 0, k = 1
var n2 = Big... |
Ensure the translated Swift code behaves exactly like the original Python snippet. | primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
def isPrime(n):
if n < 2:
return False
for i in primes:
if n == i:
return True
if n % i == 0:
return False
if i * i > n:
return True
print "Oops,", n, " is too large"
def init():
s = 24
w... | import BigInt
import Foundation
extension BinaryInteger {
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) {
if s... |
Produce a language-to-language conversion: from Python to Swift, same semantics. | from itertools import combinations as cmb
def isP(n):
if n == 2:
return True
if n % 2 == 0:
return False
return all(n % x > 0 for x in range(3, int(n ** 0.5) + 1, 2))
def genP(n):
p = [2]
p.extend([x for x in range(3, n + 1, 2) if isP(x)])
return p
data = [
(99809, 1), ... | import Foundation
class BitArray {
var array: [UInt32]
init(size: Int) {
array = Array(repeating: 0, count: (size + 31)/32)
}
func get(index: Int) -> Bool {
let bit = UInt32(1) << (index & 31)
return (array[index >> 5] & bit) != 0
}
func set(index: Int, value:... |
Can you help me rewrite this code in Swift instead of Python, keeping it the same logically? | from __future__ import print_function
from shapely.geometry import LineString
if __name__=="__main__":
line = LineString([(0,0),(1,0.1),(2,-0.1),(3,5),(4,6),(5,7),(6,8.1),(7,9),(8,9),(9,9)])
print (line.simplify(1.0, preserve_topology=False))
| struct Point: CustomStringConvertible {
let x: Double, y: Double
var description: String {
return "(\(x), \(y))"
}
}
func perpendicularDistance(p: Point, p1: Point, p2: Point) -> Double {
let dx = p2.x - p1.x
let dy = p2.y - p1.y
let d = (p.x * dy - p.y * dx + p2.x * p1.y - p2.y * p1.... |
Rewrite the snippet below in Swift so it works the same as the original Python code. | from __future__ import print_function
from shapely.geometry import LineString
if __name__=="__main__":
line = LineString([(0,0),(1,0.1),(2,-0.1),(3,5),(4,6),(5,7),(6,8.1),(7,9),(8,9),(9,9)])
print (line.simplify(1.0, preserve_topology=False))
| struct Point: CustomStringConvertible {
let x: Double, y: Double
var description: String {
return "(\(x), \(y))"
}
}
func perpendicularDistance(p: Point, p1: Point, p2: Point) -> Double {
let dx = p2.x - p1.x
let dy = p2.y - p1.y
let d = (p.x * dy - p.y * dx + p2.x * p1.y - p2.y * p1.... |
Maintain the same structure and functionality when rewriting this code in Swift. | import math
def test_func(x):
return math.cos(x)
def mapper(x, min_x, max_x, min_to, max_to):
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to
def cheb_coef(func, n, min, max):
coef = [0.0] * n
for i in xrange(n):
f = func(mapper(math.cos(math.pi * (i + 0.5) / n), -1, 1, min,... | import Foundation
typealias DFunc = (Double) -> Double
func mapRange(x: Double, min: Double, max: Double, minTo: Double, maxTo: Double) -> Double {
return (x - min) / (max - min) * (maxTo - minTo) + minTo
}
func chebCoeffs(fun: DFunc, n: Int, min: Double, max: Double) -> [Double] {
var res = [Double](repeating: ... |
Generate an equivalent Swift version of this Python code. | import math
def test_func(x):
return math.cos(x)
def mapper(x, min_x, max_x, min_to, max_to):
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to
def cheb_coef(func, n, min, max):
coef = [0.0] * n
for i in xrange(n):
f = func(mapper(math.cos(math.pi * (i + 0.5) / n), -1, 1, min,... | import Foundation
typealias DFunc = (Double) -> Double
func mapRange(x: Double, min: Double, max: Double, minTo: Double, maxTo: Double) -> Double {
return (x - min) / (max - min) * (maxTo - minTo) + minTo
}
func chebCoeffs(fun: DFunc, n: Int, min: Double, max: Double) -> [Double] {
var res = [Double](repeating: ... |
Translate this program into Swift but keep the logic exactly as in Python. | def bwt(s):
assert "\002" not in s and "\003" not in s, "Input string cannot contain STX and ETX characters"
s = "\002" + s + "\003"
table = sorted(s[i:] + s[:i] for i in range(len(s)))
last_column = [row[-1:] for row in table]
return "".join(last_column)
def ibwt(r):
table =... | import Foundation
private let stx = "\u{2}"
private let etx = "\u{3}"
func bwt(_ str: String) -> String? {
guard !str.contains(stx), !str.contains(etx) else {
return nil
}
let ss = stx + str + etx
let table = ss.indices.map({i in ss[i...] + ss[ss.startIndex..<i] }).sorted()
return String(table.map({st... |
Convert this Python snippet to Swift and keep its semantics consistent. | def bwt(s):
assert "\002" not in s and "\003" not in s, "Input string cannot contain STX and ETX characters"
s = "\002" + s + "\003"
table = sorted(s[i:] + s[:i] for i in range(len(s)))
last_column = [row[-1:] for row in table]
return "".join(last_column)
def ibwt(r):
table =... | import Foundation
private let stx = "\u{2}"
private let etx = "\u{3}"
func bwt(_ str: String) -> String? {
guard !str.contains(stx), !str.contains(etx) else {
return nil
}
let ss = stx + str + etx
let table = ss.indices.map({i in ss[i...] + ss[ss.startIndex..<i] }).sorted()
return String(table.map({st... |
Change the following Python code into Swift without altering its purpose. | from __future__ import print_function
def lgen(even=False, nmax=1000000):
start = 2 if even else 1
n, lst = 1, list(range(start, nmax + 1, 2))
lenlst = len(lst)
yield lst[0]
while n < lenlst and lst[n] < lenlst:
yield lst[n]
n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst... | struct LuckyNumbers : Sequence, IteratorProtocol {
let even: Bool
let through: Int
private var drainI = 0
private var n = 0
private var lst: [Int]
init(even: Bool = false, through: Int = 1_000_000) {
self.even = even
self.through = through
self.lst = Array(stride(from: even ? 2 : 1, throug... |
Ensure the translated Swift code behaves exactly like the original Python snippet. | from itertools import combinations, product, count
from functools import lru_cache, reduce
_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__
def place(m, n):
"Place m black and white queens, peacefully, on an n-by-n board"
board = set(product(range(n), repeat=2))
placements = {frozenset(c) for c in ... | enum Piece {
case empty, black, white
}
typealias Position = (Int, Int)
func place(_ m: Int, _ n: Int, pBlackQueens: inout [Position], pWhiteQueens: inout [Position]) -> Bool {
guard m != 0 else {
return true
}
var placingBlack = true
for i in 0..<n {
inner: for j in 0..<n {
let pos = (i, j)... |
Preserve the algorithm and functionality while converting the code from Python to Swift. | import math
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y, self.z ... | import Foundation
public struct Vector {
public var px = 0.0
public var py = 0.0
public var pz = 0.0
public init(px: Double, py: Double, pz: Double) {
(self.px, self.py, self.pz) = (px, py, pz)
}
public init?(array: [Double]) {
guard array.count == 3 else {
return nil
}
(self.px, s... |
Translate the given Python code snippet into Swift without altering its behavior. | from sympy import divisors
from sympy.combinatorics.subsets import Subset
def isZumkeller(n):
d = divisors(n)
s = sum(d)
if not s % 2 and max(d) <= s/2:
for x in range(1, 2**len(d)):
if sum(Subset.unrank_binary(x, d).subset) == s/2:
return True
return False
def ... | import Foundation
extension BinaryInteger {
@inlinable
public var isZumkeller: Bool {
let divs = factors(sorted: false)
let sum = divs.reduce(0, +)
guard sum & 1 != 1 else {
return false
}
guard self & 1 != 1 else {
let abundance = sum - 2*self
return abundance > 0 && abund... |
Change the programming language of this snippet from Python to Swift without modifying what it does. | 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... | import Foundation
extension String {
private static let commaReg = try! NSRegularExpression(pattern: "(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)")
public func commatize(start: Int = 0, period: Int = 3, separator: String = ",") -> String {
guard separator != "" else {
return self
}
let sep = Array(s... |
Generate an equivalent Swift version of this Python code. | def kosaraju(g):
class nonlocal: pass
size = len(g)
vis = [False]*size
l = [0]*size
nonlocal.x = size
t = [[]]*size
def visit(u):
if not vis[u]:
vis[u] = True
for v in g[u]:
visit(v)
t[v] = t[v] + [u]
non... | func kosaraju(graph: [[Int]]) -> [Int] {
let size = graph.count
var x = size
var vis = [Bool](repeating: false, count: size)
var l = [Int](repeating: 0, count: size)
var c = [Int](repeating: 0, count: size)
var t = [[Int]](repeating: [], count: size)
func visit(_ u: Int) {
guard !vis[u] else {
... |
Produce a language-to-language conversion: from Python to Swift, same semantics. | import random, sys
def makerule(data, context):
rule = {}
words = data.split(' ')
index = context
for word in words[index:]:
key = ' '.join(words[index-context:index])
if key in rule:
rule[key].append(word)
else:
rule[key] = [word]
index... | import Foundation
func makeRule(input: String, keyLength: Int) -> [String: [String]] {
let words = input.components(separatedBy: " ")
var rules = [String: [String]]()
var i = keyLength
for word in words[i...] {
let key = words[i-keyLength..<i].joined(separator: " ")
rules[key, default: []].appe... |
Produce a language-to-language conversion: from Python to Swift, same semantics. |
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(
... | infix operator ??= : AssignmentPrecedence
@inlinable
public func ??= <T>(lhs: inout T?, rhs: T?) {
lhs = lhs ?? rhs
}
private func createString(_ from: String, _ v: [Int?]) -> String {
var idx = from.count
var sliceVec = [Substring]()
while let prev = v[idx] {
let s = from.index(from.startIndex, offsetBy... |
Write a version of this Python function in Swift with identical behavior. | def ownCalcPass (password, nonce, test=False) :
start = True
num1 = 0
num2 = 0
password = int(password)
if test:
print("password: %08x" % (password))
for c in nonce :
if c != "0":
if start:
num2 = password
start = False
if test:... | func openAuthenticationResponse(_password: String, operations: String) -> String? {
var num1 = UInt32(0)
var num2 = UInt32(0)
var start = true
let password = UInt32(_password)!
for c in operations {
if (c != "0") {
if start {
num2 = password
}
... |
Translate this program into Swift but keep the logic exactly as in Python. | 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... | import BigInt
func partitions(n: Int) -> BigInt {
var p = [BigInt(1)]
for i in 1...n {
var num = BigInt(0)
var k = 1
while true {
var j = (k * (3 * k - 1)) / 2
if j > i {
break
}
if k & 1 == 1 {
num += p[i - j]
} else {
num -= p[i - j]
}
... |
Rewrite the snippet below in Swift so it works the same as the original Python code. |
def reverse(n):
u = 0
while n:
u = 10 * u + n % 10
n = int(n / 10)
return u
c = 0
for n in range(1, 200):
u = reverse(n)
s = True
for d in range (1, n):
if n % d == 0:
b = reverse(d)
if u % b != 0:
s = False
if s:
... | import Foundation
func reverse(_ number: Int) -> Int {
var rev = 0
var n = number
while n > 0 {
rev = rev * 10 + n % 10
n /= 10
}
return rev
}
func special(_ number: Int) -> Bool {
var n = 2
let rev = reverse(number)
while n * n <= number {
if number % n == 0 {
... |
Write a version of this Python function in Swift with identical behavior. |
def hpo2(n): return n & (-n)
def lhpo2(n):
q = 0
m = hpo2(n)
while m%2 == 0:
m = m >> 1
q += 1
return q
def nimsum(x,y): return x ^ y
def nimprod(x,y):
if x < 2 or y < 2:
return x * y
h = hpo2(x)
if x > h:
return nimprod(h, y) ^ nimprod(x^h, y)
if hp... | import Foundation
func hpo2(_ n: Int) -> Int {
n & -n
}
func lhpo2(_ n: Int) -> Int {
var q: Int = 0
var m: Int = hpo2(n)
while m % 2 == 0 {
m >>= 1
q += 1
}
return q
}
func nimSum(x: Int, y: Int) -> Int {
x ^ y
}
func nimProduct(x: Int, y: Int) -> Int {
if x < 2 ... |
Port the provided Python code into Swift while preserving the original functionality. | 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 Foundation
extension Numeric where Self: Strideable {
@inlinable
public func power(_ n: Self) -> Self {
return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *)
}
}
func eratosthenes(limit: Int) -> [Int] {
guard limit >= 3 else {
return limit < 2 ? [] : [2]
}
let ndxLimit =... |
Please provide an equivalent version of this Python code in Swift. | from numpy import array
def is_prime(n: int) -> bool:
assert n < 64
return ((1 << n) & 0x28208a20a08a28ac) != 0
def prime_triangle_row(a: array, start: int, length: int) -> bool:
if length == 2:
return is_prime(a[0] + a[1])
for i in range(1, length - 1, 1):
if is_prime(a[start] + a[sta... | import Foundation
func isPrime(_ n: Int) -> Bool {
guard n > 0 && n < 64 else {
return false
}
return ((UInt64(1) << n) & 0x28208a20a08a28ac) != 0
}
func primeTriangleRow(_ a: inout [Int], start: Int, length: Int) -> Bool {
if length == 2 {
return isPrime(a[start] + a[start + 1])
}... |
Rewrite this program in Swift 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 Foundation
func oneAway(string1: [Character], string2: [Character]) -> Bool {
if string1.count != string2.count {
return false
}
var result = false
var i = 0
while i < string1.count {
if string1[i] != string2[i] {
if result {
return false
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.