Convert Python List Comprehension to C# - python

How can I convert this python code to C#
points = []
for i in range(0, len(points_seq), n):
points.append(points_seq[i:i + n])
Not sure on how to convert it

In case of .Net 6+ you can use Chunk() Linq method:
// or List<int> points_seq =
int[] points_seq = ...
int n = ...
...
var points = points_seq
.Chunk(n)
.ToList(); // if you want List<int[]>, .ToArray() for int[][]
If you have previous versions of .Net you can implement the same with a help of GroupBy:
var points = points_seq
.Select((value, i) => (value : value, i : i))
.GroupBy(item => item.i / n, item => item.value)
.Select(g => g.ToArray())
.ToList();

Related

How can i convert this obsucured decrypt python code in dart?

i am trying to get obscured email that was obscured by firewall.
i found the solution in python but i don't know to do this in dart or flutter.
here is the python code
r = int(encodedString[:2],16)
email = ''.join([chr(int(encodedString[i:i+2], 16) ^ r) for i in range(2, len(encodedString), 2)])
return email
print cfDecodeEmail('543931142127353935313e352e7a373b39') # usage
In Python, encodedString[:2]/encodedString[i:i+2] extract two characters from encodedString. The Dart equivalent (assuming ASCII characters) would be encodedString.substring(0, 2) and encodedString(i, i + 2) respectively.
The equivalent of Python's ''.join(list) in Dart is list.join().
The equivalent of a Python's list comprehensions ([i for i in items]) in Dart is collection-for: [for (var i in items) i].
The equivalent of Python's for i in range(2, len(encodedString), 2) in Dart is to use a basic for loop with a start, condition, and increment: for (var i = 2; i < encodedString.length; i += 2).
In Python, int(string, 16) parses string as a hexadecimal number. In Dart, use int.parse(string, radix: 16).
In Python, chr(integer) creates a string from the specified code point. The equivalent in Dart is String.fromCharCode(integer).
Putting it all together:
String cfDecodeEmail(String encodedString) {
var r = int.parse(encodedString.substring(0, 2), radix: 16);
var email = [
for (var i = 2; i < encodedString.length; i += 2)
String.fromCharCode(
int.parse(encodedString.substring(i, i + 2), radix: 16) ^ r,
)
].join();
return email;
}
void main() {
// Prints: me#usamaejaz.com
print(cfDecodeEmail('543931142127353935313e352e7a373b39'));
}

How can I keep the mathematical order in this function?

I have this function which returns the wrong result
def calc(a): return lambda op: {
'+': lambda b: calc(a+b),
'-': lambda b: calc(a-b),
'*': lambda b: calc(a*b),
'/': lambda b: calc(a/b),
'=': a}[op]
calc(1)('+')(2)('*')(10)('=') # 30 -> should be 21
Does anyone have an idea how I can keep the functional style and follow the correct mathematical order?
Please note that I lack a firm understanding of Python hence the answer is going to be in JS. Hope it's still helpfull.
A proper solution needs to cover the following properties:
operator precedence
operator associativity (left/right/none)
operator arity (unary/binary)
round parenthesis
Operator associativity must not be confused with the mathematical property. An operator must either be left, right or not associative at all. The latter means the operator is not composable.
Precedence determines the evaluation order in case of different operators, associative in case of the same.
a + b - c = a + (b - c) :: - exceeds precedence of +
a - b - c = (a - b) - c :: - is left associative
This solution is just a rough sketch. It doesn't use string symbols as operators, which can be easily changed though. More importently it takes neither operator associativity nor parenthesis into account but always assumes left associativity and binary operators. It's just a start to get a notion for the complexity to be expected:
const prec = n => o => (o.prec = n, o);
const prec1 = prec(1);
const prec2 = prec(2);
const prec3 = prec(3);
const prec4 = prec(4);
const add = prec1(x => prec1(y => x + y));
const sub = prec2(x => prec2(y => x - y));
const mul = prec3(x => prec3(y => x * y));
const div = prec4(x => prec4(y => x / y));
const infix = x => f => infix_(f(x));
const infix_ = partialF => y => {
const go = g => {
if (partialF.prec >= g.prec)
return infix_(g(partialF(y)));
else {
const partialG = g(y);
return infix_(z => partialF(partialG(z)));
}
};
Object.defineProperty(
go,
"run",
{get() {return partialF(y)}}); // lazy property getter
return go;
};
const r1 = infix(2) (mul) (3) (sub) (4) (add) (5) (div) (2); // 2*3-4+5/2 = 4.5
const r2 = infix(2) (add) (3) (sub) (4) (mul) (5) (div) (2); // 2+3-4*5/2 = -5
console.log(r1.run);
console.log(r2.run);

How to convert this Python algorithm to C#

I'm trying to convert a Python algorithm from this Stack Overflow answer to split a string without spaces into words to C#.
Unfortunately I don't know anything about Python so the translation is proving very difficult.
The lines I don't understand are:
wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words)) <= THIS LINE
and
def best_match(i):
candidates = enumerate(reversed(cost[max(0, i-maxword):i]))
return min((c + wordcost.get(s[i-k-1:i], 9e999), k+1) for k,c in candidates) <= THIS LINE
It looks as though best_match(i) it should return a Tuple<>. What is the equivalent in C#?
Here is the full Python script:
from math import log
# Build a cost dictionary, assuming Zipf's law and cost = -math.log(probability).
words = open("words-by-frequency.txt").read().split()
wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words))
maxword = max(len(x) for x in words)
def infer_spaces(s):
"""Uses dynamic programming to infer the location of spaces in a string
without spaces."""
# Find the best match for the i first characters, assuming cost has
# been built for the i-1 first characters.
# Returns a pair (match_cost, match_length).
def best_match(i):
candidates = enumerate(reversed(cost[max(0, i-maxword):i]))
return min((c + wordcost.get(s[i-k-1:i], 9e999), k+1) for k,c in candidates)
# Build the cost array.
cost = [0]
for i in range(1,len(s)+1):
c,k = best_match(i)
cost.append(c)
# Backtrack to recover the minimal-cost string.
out = []
i = len(s)
while i>0:
c,k = best_match(i)
assert c == cost[i]
out.append(s[i-k:i])
i -= k
return " ".join(reversed(out))
I found that algorithm interesting so here is my translation:
class WordSplitter {
private readonly Dictionary<string, double> _wordCosts;
private readonly int _maxWordLength;
public WordSplitter(string freqFilePath) {
// words = open("words-by-frequency.txt").read().split()
var words = File.ReadAllLines(freqFilePath);
// wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words))
_wordCosts = words.Select((k, i) => new { Key = k, Value = Math.Log((i + 1) * Math.Log(words.Length)) }).ToDictionary(c => c.Key, c => c.Value);
// maxword = max(len(x) for x in words)
_maxWordLength = words.Select(c => c.Length).Max();
}
public string InferSpaces(string target) {
// cost = [0]
var costs = new List<double>() { 0 };
foreach (var i in Enumerable.Range(1, target.Length)) {
var (c, k) = BestMatch(i);
costs.Add(c);
}
var output = new List<string>();
int len = target.Length;
while (len > 0) {
var (c, k) = BestMatch(len);
Debug.Assert(k > 0);
Debug.Assert(c == costs[len]);
// use Substring if your compiler version doesn't support slicing
// but pay attention that Substring second argument is length, not end index
output.Add(target[(len - k)..len]);
len -= k;
}
output.Reverse();
return String.Join(" ", output);
(double cost, int length) BestMatch(int i) {
var start = Math.Max(0, i - _maxWordLength);
// GetRange second argument is length
var x = costs.GetRange(start, i - start);
x.Reverse();
// now, this part is easier to comprehend if it's expanded a bit
// you can do it in cryptic way too like in python though if you like
(double cost, int length)? result = null;
for (int k = 0; k < x.Count; k++) {
var c = x[k];
var sub = target[(i - k - 1)..i];
var cost = c + (_wordCosts.ContainsKey(sub) ? _wordCosts[sub] : 9e99); // 9e99 is just some big number. 9e999 is outside of double range in C#, so use smaller one
// save minimal cost
if (result == null || result.Value.cost > cost)
result = (cost, k + 1);
}
// return minimal cost
return result.Value;
}
}
}
Usage:
var splitter = new WordSplitter(#"C:\tmp\words.txt");
var result = splitter.InferSpaces("thumbgreenappleactiveassignmentweeklymetaphor");

How to make python of exponential growth to code equivalent to c++?

In this code I am computing a numerical approximation of the solution of an ODE u'(tk)=u(tk)=uk and storing all the uk and tk values as shown below.
Code:
def compute_u(u0,T,n):
t = linspace(0,T,n+1)
t[0] = 0
u=zeros(n+1)
u[0]= u0
dt = T/float(n)
for k in range(0, n, 1):
u[k+1] = (1+dt)*u[k]
t[k+1] = t[k] + dt
return u, t
I am now trying to implement this code into c++ and I am facing a few rocks along the way. I am relatively new in C++ and I was wondering if anyone in this forum could point me to the right direction since python has functions that c++ does not such as linspace or zeros. Any input will be helpful.
Here you have linspace:
std::vector< float > linspace(float a, float b, uint32_t n)
{
std::vector< float > result(n);
float step = (b - a) / (float) (n - 1);
for (uint32_t i = 0; i <= n - 2; i++) {
result[i] = a + (float) i * step;
}
result.back() = b;
return result;
}
try out zeros yourself.
Or a better solution: use Eigen, it has both functions.

Non Divisible subset in python

I have been given a set S, of n integers, and have to print the size of a maximal subset S' of S where the sum of any 2 numbers in S' are not evenly divisible by k.
Input Format
The first line contains 2 space-separated integers, n and k, respectively.
The second line contains n space-separated integers describing the unique values of the set.
My Code :
import sys
n,k = raw_input().strip().split(' ')
n,k = [int(n),int(k)]
a = map(int,raw_input().strip().split(' '))
count = 0
for i in range(len(a)):
for j in range(len(a)):
if (a[i]+a[j])%k != 0:
count = count+1
print count
Input:
4 3
1 7 2 4
Expected Output:
3
My Output:
10
What am i doing wrong? Anyone?
You can solve it in O(n) time using the following approach:
L = [0]*k
for x in a:
L[x % k] += 1
res = 0
for i in range(k//2+1):
if i == 0 or k == i*2:
res += bool(L[i])
else:
res += max(L[i], L[k-i])
print(res)
Yes O(n) solution for this problem is very much possible. Like planetp rightly pointed out its pretty much the same solution I have coded in java. Added comments for better understanding.
import java.io.; import java.util.;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int k=in.nextInt();
int [] arr = new int[k];
Arrays.fill(arr, 0);
Map<Integer,Integer> mp=new HashMap<>();
Storing the values in a map considering there are no duplicates. You can store them in array list if there are duplicates. Only then you have different results.
for(int i=0;i
int res=0;
for(int i=0;i<=(k/2);i++)
{
if(i==0 || k==i*2)
{
if(arr[i]!=0)
res+=1;
}
If the no. is divisible by k we can have only one and if the no is exactly half of k then we can have only 1. Rational if a & b are divisble by k then a+b is also divisible by k. Similarly if c%k=k/2 then if we have more than one such no. their combination is divisible by k. Hence we restrict them to 1 value each.
else
{
int p=arr[i];
int q=arr[k-i];
if(p>=q)
res+=p;
else
res+=q;
}
This is simple figure out which is more from a list of 0 to k/2 in the list if a[x]>a[k-x] get the values which is greater. i.e. if we have k=4 and we have no. 1,3,5,7,9,13,17. Then a[1]=4 and a[3]=2 thus pick a[1] because 1,5,13,17 can be kept together.
}
System.out.println(res);
}
}
# given k, n and a as per your input.
# Will return 0 directly if n == 1
def maxsize(k, n, a):
import itertools
while n > 1:
sets = itertools.combinations(a, n)
for set_ in sets:
if all((u+v) % k for (u, v) in itertools.combinations(set_, 2)):
return n
n -= 1
return 0
Java solution
public class Solution {
static PrintStream out = System.out;
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner (System.in);
int n = in.nextInt();
int k = in.nextInt();
int[] A = new int[n];
for(int i=0;i<n;i++){
A[i]=in.nextInt();
}
int[] R = new int[k];
for(int i=0;i<n;i++)
R[A[i] % k]+=1;
int res=0;
for(int i=0;i<k/2+1;i++){
if(i==0 || k==i*2)
res+= (R[i]!=0)?1:0;
else
res+= Math.max(R[i], R[k-i]);
}
out.println(res);
}
}

Categories

Resources