WeixiangYan/CodeTransOcean huggingface dataset:
Task: Determine if a string is squeezable


C++: #include <algorithm>
#include <string>
#include <iostream>

template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
    auto i = std::unique(str.begin(), str.end(),
        [ch](char_type a, char_type b) { return a == ch && b == ch; });
    str.erase(i, str.end());
    return str;
}

void test(const std::string& str, char ch) {
    std::cout << "character: '" << ch << "'\n";
    std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
    std::string squeezed(squeeze(str, ch));
    std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
    std::cout << '\n';
}

int main(int argc, char** argv) {
    test("", ' ');
    test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
    test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
    test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
    std::string truman("                                                    --- Harry S Truman  ");
    test(truman, ' ');
    test(truman, '-');
    test(truman, 'r');
    return 0;
}





PHP: <?php

function squeezeString($string, $squeezeChar) {
    $previousChar = null;
    $squeeze = '';
    $charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
    for ($i = 0 ; $i < count($charArray) ; $i++) {
        $currentChar = $charArray[$i];
        if ($previousChar !== $currentChar || $currentChar !== $squeezeChar) {
            $squeeze .= $charArray[$i];
        }
        $previousChar = $currentChar;
    }
    return $squeeze;
}

function isSqueezable($string, $squeezeChar) {
    return ($string !== squeezeString($string, $squeezeChar));
}

$strings = array(
    ['-', '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '],
    ['1', '..1111111111111111111111111111111111111111111111111111111111111117777888'],
    ['l', "I never give 'em hell, I just tell the truth, and they think it's hell. "],
    [' ', '                                                    --- Harry S Truman  '],
    ['9', '0112223333444445555556666666777777778888888889999999999'],
    ['e', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"],
    ['k', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"],
);
foreach ($strings as $params) {
    list($char, $original) = $params;
    echo 'Original   : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL;
    if (isSqueezable($original, $char)) {
        $squeeze = squeezeString($original, $char);
        echo 'Squeeze(', $char, ') : <<<', $squeeze, '>>> (len=', mb_strlen($squeeze), ')', PHP_EOL, PHP_EOL;
    } else {
        echo 'Squeeze(', $char, ') : string is not squeezable (char=', $char, ')...', PHP_EOL, PHP_EOL;
    }
}
Task: Determine if a string is squeezable




Go: package main

import "fmt"



func squeeze(s string, c rune) (string, int, int) {
    r := []rune(s)
    le, del := len(r), 0
    for i := le - 2; i >= 0; i-- {
        if r[i] == c && r[i] == r[i+1] {
            copy(r[i:], r[i+1:])
            del++
        }
    }
    if del == 0 {
        return s, le, le
    }
    r = r[:le-del]
    return string(r), le, len(r)
}

func main() {
    strings := []string{
        "",
        `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
        "aardvark",
        "😍😀🙌💃😍😍😍🙌",
    }
    chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}

    for i, s := range strings {
        for _, c := range chars[i] {
            ss, olen, slen := squeeze(s, c)
            fmt.Printf("specified character = %q\n", c)
            fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
            fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
        }
    }
}



PHP: <?php

function squeezeString($string, $squeezeChar) {
    $previousChar = null;
    $squeeze = '';
    $charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
    for ($i = 0 ; $i < count($charArray) ; $i++) {
        $currentChar = $charArray[$i];
        if ($previousChar !== $currentChar || $currentChar !== $squeezeChar) {
            $squeeze .= $charArray[$i];
        }
        $previousChar = $currentChar;
    }
    return $squeeze;
}

function isSqueezable($string, $squeezeChar) {
    return ($string !== squeezeString($string, $squeezeChar));
}

$strings = array(
    ['-', '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '],
    ['1', '..1111111111111111111111111111111111111111111111111111111111111117777888'],
    ['l', "I never give 'em hell, I just tell the truth, and they think it's hell. "],
    [' ', '                                                    --- Harry S Truman  '],
    ['9', '0112223333444445555556666666777777778888888889999999999'],
    ['e', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"],
    ['k', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"],
);
foreach ($strings as $params) {
    list($char, $original) = $params;
    echo 'Original   : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL;
    if (isSqueezable($original, $char)) {
        $squeeze = squeezeString($original, $char);
        echo 'Squeeze(', $char, ') : <<<', $squeeze, '>>> (len=', mb_strlen($squeeze), ')', PHP_EOL, PHP_EOL;
    } else {
        echo 'Squeeze(', $char, ') : string is not squeezable (char=', $char, ')...', PHP_EOL, PHP_EOL;
    }
}
Task: Determine if a string is squeezable






PHP: <?php

function squeezeString($string, $squeezeChar) {
    $previousChar = null;
    $squeeze = '';
    $charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
    for ($i = 0 ; $i < count($charArray) ; $i++) {
        $currentChar = $charArray[$i];
        if ($previousChar !== $currentChar || $currentChar !== $squeezeChar) {
            $squeeze .= $charArray[$i];
        }
        $previousChar = $currentChar;
    }
    return $squeeze;
}

function isSqueezable($string, $squeezeChar) {
    return ($string !== squeezeString($string, $squeezeChar));
}

$strings = array(
    ['-', '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '],
    ['1', '..1111111111111111111111111111111111111111111111111111111111111117777888'],
    ['l', "I never give 'em hell, I just tell the truth, and they think it's hell. "],
    [' ', '                                                    --- Harry S Truman  '],
    ['9', '0112223333444445555556666666777777778888888889999999999'],
    ['e', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"],
    ['k', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"],
);
foreach ($strings as $params) {
    list($char, $original) = $params;
    echo 'Original   : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL;
    if (isSqueezable($original, $char)) {
        $squeeze = squeezeString($original, $char);
        echo 'Squeeze(', $char, ') : <<<', $squeeze, '>>> (len=', mb_strlen($squeeze), ')', PHP_EOL, PHP_EOL;
    } else {
        echo 'Squeeze(', $char, ') : string is not squeezable (char=', $char, ')...', PHP_EOL, PHP_EOL;
    }
}


Python: from itertools import groupby

def squeezer(s, txt):
    return ''.join(item if item == s else ''.join(grp)
                   for item, grp in groupby(txt))

if __name__ == '__main__':
    strings = [
            "",
            '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
            "..1111111111111111111111111111111111111111111111111111111111111117777888",
            "I never give 'em hell, I just tell the truth, and they think it's hell. ",
            "                                                   ---  Harry S Truman  ",
            "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
            "headmistressship",
            "aardvark",
            "😍😀🙌💃😍😍😍🙌",
            ]
    squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',')
    for txt, chars in zip(strings, squeezers):
        this = "Original"
        print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" )
        for ch in chars:
            this = f"Squeezer '{ch}'"
            sqz = squeezer(ch, txt)
            print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Task: Determine if a string is squeezable






PHP: <?php

function squeezeString($string, $squeezeChar) {
    $previousChar = null;
    $squeeze = '';
    $charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
    for ($i = 0 ; $i < count($charArray) ; $i++) {
        $currentChar = $charArray[$i];
        if ($previousChar !== $currentChar || $currentChar !== $squeezeChar) {
            $squeeze .= $charArray[$i];
        }
        $previousChar = $currentChar;
    }
    return $squeeze;
}

function isSqueezable($string, $squeezeChar) {
    return ($string !== squeezeString($string, $squeezeChar));
}

$strings = array(
    ['-', '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '],
    ['1', '..1111111111111111111111111111111111111111111111111111111111111117777888'],
    ['l', "I never give 'em hell, I just tell the truth, and they think it's hell. "],
    [' ', '                                                    --- Harry S Truman  '],
    ['9', '0112223333444445555556666666777777778888888889999999999'],
    ['e', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"],
    ['k', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"],
);
foreach ($strings as $params) {
    list($char, $original) = $params;
    echo 'Original   : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL;
    if (isSqueezable($original, $char)) {
        $squeeze = squeezeString($original, $char);
        echo 'Squeeze(', $char, ') : <<<', $squeeze, '>>> (len=', mb_strlen($squeeze), ')', PHP_EOL, PHP_EOL;
    } else {
        echo 'Squeeze(', $char, ') : string is not squeezable (char=', $char, ')...', PHP_EOL, PHP_EOL;
    }
}



VB: Imports System.Linq.Enumerable

Module Module1

    Function Squeeze(s As String, c As Char) As String
        If String.IsNullOrEmpty(s) Then
            Return ""
        End If
        Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
    End Function

    Sub SqueezeAndPrint(s As String, c As Char)
        Console.WriteLine("squeeze: 
        Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
        s = Squeeze(s, c)
        Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
    End Sub

    Sub Main()
        Const QUOTE = """"

        SqueezeAndPrint("", " ")
        SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
        SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
        SqueezeAndPrint("I never give 

        Dim s = "                                                    --- Harry S Truman  "
        SqueezeAndPrint(s, " ")
        SqueezeAndPrint(s, "-")
        SqueezeAndPrint(s, "r")
    End Sub

End Module
Task: Convert decimal number to rational

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>


void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom)
{
	
	int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 };
	int64_t x, d, n = 1;
	int i, neg = 0;

	if (md <= 1) { *denom = 1; *num = (int64_t) f; return; }

	if (f < 0) { neg = 1; f = -f; }

	while (f != floor(f)) { n <<= 1; f *= 2; }
	d = f;

	
	for (i = 0; i < 64; i++) {
		a = n ? d / n : 0;
		if (i && !a) break;

		x = d; d = n; n = x % n;

		x = a;
		if (k[1] * a + k[0] >= md) {
			x = (md - k[0]) / k[1];
			if (x * 2 >= a || k[1] >= md)
				i = 65;
			else
				break;
		}

		h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];
		k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];
	}
	*denom = k[1];
	*num = neg ? -h[1] : h[1];
}

int main()
{
	int i;
	int64_t d, n;
	double f;

	printf("f = %16.14f\n", f = 1.0/7);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	printf("\nf = %16.14f\n", f = atan2(1,1) * 4);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	return 0;
}




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    for _, d := range []string{"0.9054054", "0.518518", "0.75"} {
        if r, ok := new(big.Rat).SetString(d); ok {
            fmt.Println(d, "=", r)
        } else {
            fmt.Println(d, "invalid decimal number")
        }
    }
}
Task: Convert decimal number to rational

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>


void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom)
{
	
	int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 };
	int64_t x, d, n = 1;
	int i, neg = 0;

	if (md <= 1) { *denom = 1; *num = (int64_t) f; return; }

	if (f < 0) { neg = 1; f = -f; }

	while (f != floor(f)) { n <<= 1; f *= 2; }
	d = f;

	
	for (i = 0; i < 64; i++) {
		a = n ? d / n : 0;
		if (i && !a) break;

		x = d; d = n; n = x % n;

		x = a;
		if (k[1] * a + k[0] >= md) {
			x = (md - k[0]) / k[1];
			if (x * 2 >= a || k[1] >= md)
				i = 65;
			else
				break;
		}

		h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];
		k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];
	}
	*denom = k[1];
	*num = neg ? -h[1] : h[1];
}

int main()
{
	int i;
	int64_t d, n;
	double f;

	printf("f = %16.14f\n", f = 1.0/7);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	printf("\nf = %16.14f\n", f = atan2(1,1) * 4);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	return 0;
}





Java: import org.apache.commons.math3.fraction.BigFraction;

public class Test {

    public static void main(String[] args) {
        double[] n = {0.750000000, 0.518518000, 0.905405400, 0.142857143,
            3.141592654, 2.718281828, -0.423310825, 31.415926536};

        for (double d : n)
            System.out.printf("%-12s : %s%n", d, new BigFraction(d, 0.00000002D, 10000));
    }
}
Task: Convert decimal number to rational

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>


void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom)
{
	
	int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 };
	int64_t x, d, n = 1;
	int i, neg = 0;

	if (md <= 1) { *denom = 1; *num = (int64_t) f; return; }

	if (f < 0) { neg = 1; f = -f; }

	while (f != floor(f)) { n <<= 1; f *= 2; }
	d = f;

	
	for (i = 0; i < 64; i++) {
		a = n ? d / n : 0;
		if (i && !a) break;

		x = d; d = n; n = x % n;

		x = a;
		if (k[1] * a + k[0] >= md) {
			x = (md - k[0]) / k[1];
			if (x * 2 >= a || k[1] >= md)
				i = 65;
			else
				break;
		}

		h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];
		k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];
	}
	*denom = k[1];
	*num = neg ? -h[1] : h[1];
}

int main()
{
	int i;
	int64_t d, n;
	double f;

	printf("f = %16.14f\n", f = 1.0/7);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	printf("\nf = %16.14f\n", f = atan2(1,1) * 4);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	return 0;
}







Python: >>> from fractions import Fraction
>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))

0.9054054 67/74
0.518518 14/27
0.75 3/4
>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))

0.9054054 4527027/5000000
0.518518 259259/500000
0.75 3/4
>>>
Task: Convert decimal number to rational

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>


void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom)
{
	
	int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 };
	int64_t x, d, n = 1;
	int i, neg = 0;

	if (md <= 1) { *denom = 1; *num = (int64_t) f; return; }

	if (f < 0) { neg = 1; f = -f; }

	while (f != floor(f)) { n <<= 1; f *= 2; }
	d = f;

	
	for (i = 0; i < 64; i++) {
		a = n ? d / n : 0;
		if (i && !a) break;

		x = d; d = n; n = x % n;

		x = a;
		if (k[1] * a + k[0] >= md) {
			x = (md - k[0]) / k[1];
			if (x * 2 >= a || k[1] >= md)
				i = 65;
			else
				break;
		}

		h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];
		k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];
	}
	*denom = k[1];
	*num = neg ? -h[1] : h[1];
}

int main()
{
	int i;
	int64_t d, n;
	double f;

	printf("f = %16.14f\n", f = 1.0/7);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	printf("\nf = %16.14f\n", f = atan2(1,1) * 4);
	for (i = 1; i <= 20000000; i *= 16) {
		printf("denom <= %d: ", i);
		rat_approx(f, i, &n, &d);
		printf("%lld/%lld\n", n, d);
	}

	return 0;
}








VB: Function Real2Rational(r As Double, bound As Long) As String

If r = 0 Then
    Real2Rational = "0/1"
ElseIf r < 0 Then
    Result = Real2Rational(-r, bound)
    Real2Rational = "-" & Result
Else
    best = 1
    bestError = 1E+99
    For i = 1 To bound + 1
        currentError = Abs(i * r - Round(i * r))
        If currentError < bestError Then
            best = i
            bestError = currentError
            If bestError < 1 / bound Then GoTo SkipLoop
        End If
    Next i
SkipLoop:
    Real2Rational = Round(best * r) & "/" & best
End If
End Function

Sub TestReal2Rational()
Debug.Print "0.75" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.75, CLng(Order));
Next i
Debug.Print

Debug.Print "0.518518" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.518518, CLng(Order));
Next i
Debug.Print

Debug.Print "0.9054054" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.9054054, CLng(Order));
Next i
Debug.Print

Debug.Print "0.142857143" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.142857143, CLng(Order));
Next i
Debug.Print

Debug.Print "3.141592654" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(3.141592654, CLng(Order));
Next i
Debug.Print

Debug.Print "2.718281828" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(2.718281828, CLng(Order));
Next i
Debug.Print

Debug.Print "-0.423310825" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(-0.423310825, CLng(Order));
Next i
Debug.Print

Debug.Print "31.415926536" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(31.415926536, CLng(Order));
Next i
End Sub
Task: Convert decimal number to rational




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    for _, d := range []string{"0.9054054", "0.518518", "0.75"} {
        if r, ok := new(big.Rat).SetString(d); ok {
            fmt.Println(d, "=", r)
        } else {
            fmt.Println(d, "invalid decimal number")
        }
    }
}


Java: import org.apache.commons.math3.fraction.BigFraction;

public class Test {

    public static void main(String[] args) {
        double[] n = {0.750000000, 0.518518000, 0.905405400, 0.142857143,
            3.141592654, 2.718281828, -0.423310825, 31.415926536};

        for (double d : n)
            System.out.printf("%-12s : %s%n", d, new BigFraction(d, 0.00000002D, 10000));
    }
}
Task: Convert decimal number to rational





Java: import org.apache.commons.math3.fraction.BigFraction;

public class Test {

    public static void main(String[] args) {
        double[] n = {0.750000000, 0.518518000, 0.905405400, 0.142857143,
            3.141592654, 2.718281828, -0.423310825, 31.415926536};

        for (double d : n)
            System.out.printf("%-12s : %s%n", d, new BigFraction(d, 0.00000002D, 10000));
    }
}



Python: >>> from fractions import Fraction
>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))

0.9054054 67/74
0.518518 14/27
0.75 3/4
>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))

0.9054054 4527027/5000000
0.518518 259259/500000
0.75 3/4
>>>
Task: Convert decimal number to rational




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    for _, d := range []string{"0.9054054", "0.518518", "0.75"} {
        if r, ok := new(big.Rat).SetString(d); ok {
            fmt.Println(d, "=", r)
        } else {
            fmt.Println(d, "invalid decimal number")
        }
    }
}




Python: >>> from fractions import Fraction
>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))

0.9054054 67/74
0.518518 14/27
0.75 3/4
>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))

0.9054054 4527027/5000000
0.518518 259259/500000
0.75 3/4
>>>
Task: Convert decimal number to rational




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    for _, d := range []string{"0.9054054", "0.518518", "0.75"} {
        if r, ok := new(big.Rat).SetString(d); ok {
            fmt.Println(d, "=", r)
        } else {
            fmt.Println(d, "invalid decimal number")
        }
    }
}





VB: Function Real2Rational(r As Double, bound As Long) As String

If r = 0 Then
    Real2Rational = "0/1"
ElseIf r < 0 Then
    Result = Real2Rational(-r, bound)
    Real2Rational = "-" & Result
Else
    best = 1
    bestError = 1E+99
    For i = 1 To bound + 1
        currentError = Abs(i * r - Round(i * r))
        If currentError < bestError Then
            best = i
            bestError = currentError
            If bestError < 1 / bound Then GoTo SkipLoop
        End If
    Next i
SkipLoop:
    Real2Rational = Round(best * r) & "/" & best
End If
End Function

Sub TestReal2Rational()
Debug.Print "0.75" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.75, CLng(Order));
Next i
Debug.Print

Debug.Print "0.518518" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.518518, CLng(Order));
Next i
Debug.Print

Debug.Print "0.9054054" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.9054054, CLng(Order));
Next i
Debug.Print

Debug.Print "0.142857143" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(0.142857143, CLng(Order));
Next i
Debug.Print

Debug.Print "3.141592654" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(3.141592654, CLng(Order));
Next i
Debug.Print

Debug.Print "2.718281828" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(2.718281828, CLng(Order));
Next i
Debug.Print

Debug.Print "-0.423310825" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(-0.423310825, CLng(Order));
Next i
Debug.Print

Debug.Print "31.415926536" & ":";
For i = 0 To 5
    Order = CDbl(10) ^ CDbl(i)
    Debug.Print " " & Real2Rational(31.415926536, CLng(Order));
Next i
End Sub