# How to convert code from python to julia. the magic squares

**URL:** <https://discourse.julialang.org/t/how-to-convert-code-from-python-to-julia-the-magic-squares/87397>\
**Category:** General Usage\
**Created:** [September 17, 2022, 8:23am UTC](https://discourse.julialang.org/t/how-to-convert-code-from-python-to-julia-the-magic-squares/87397 "2022-09-17T08:23:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![TesMar](https://avatars.discourse-cdn.com/v4/letter/t/dbc845/32.png) [@TesMar](https://discourse.julialang.org/u/TesMar)\
**Post date:** [September 17, 2022, 8:23am UTC](https://discourse.julialang.org/t/how-to-convert-code-from-python-to-julia-the-magic-squares/87397/1 "2022-09-17T08:23:25Z")

</div>

Hello everybody. I ask for help to convert this python code to Julia:  
sorry for the language errors, but i’m italian.

> Blockquote import collections  
> from statistics import\*  
> import numpy as np  
> import pylab as pl

file2=open(“testus.txt”,“w”)  
file2.close()

class CarreMagique :  
def **init** (self, coef) :  
self.mat = [[ coef[i+j\*3] for i in range(3) ] for j in range(3) ]  
def **str** (self) :  
return “\n”.join ( [“,”.join( [ str(n) for n in row] ) for row in self.mat ] )  
def **add** (self, carre) :  
coef =   
for i in range(3) :  
for j in range(3) :  
coef.append ( self.mat[i][j] + carre.mat[i][j])  
return CarreMagique(coef)  
def somme\_ligne\_colonne\_diagonale(self):  
tout = [sum ( ligne ) for ligne in self.mat] +   
[sum ( self.mat[i][j] for i in range(3) ) for j in range(3) ] +   
[sum ( self.mat[i][i] for i in range(3) ) ] +   
[sum ( self.mat[2-i][i] for i in range(3) ) ]  
return tout  
return sorted(tout)

```
def Coeff_unique(self):
    d = { }
    for ligne in self.mat :
        for c in ligne :
            d [c] = d.get(c,0) +1
    return len(d) == 9
    
def est_magique(self):
    unique = self.Coeff_unique()
    if not unique : return False
    somme = self.somme_ligne_colonne_diagonale()
    return min(somme) == max(somme)
    return sorted(somme)

```

def tous\_les\_carres\_permutation(stop\_after =112222 ):  
res=  
lst=([18,20,51,67,70,75,85,89])  
ok=([“18.20,51,67,70,75,85,89”])

```
"""fre=[i.replace(".", ",") for i in ok]
fre1 = [item.replace(".", ",") for item in fre]
print ("aaaaaaaaaaaa",fre1)"""

ok=ok.split(',')
ok= [int(i) for i in ok]
print ("aaaaaaaaaaaa",ok)

lst.sort(),
#pl.plot(lst)
#pl.show()

#ci fornisce tutte le frequenze dei numeri in lista
cnt=collections.Counter(lst)
print("la frequenza dei numeri nei numeri inseriti è",cnt.most_common())

od = collections.OrderedDict(cnt.most_common())  
for key, value in od.items():
    if value==1:
        print (key,value)

        #serve per eliminare i doppioni, ma si usa anche set
"""lst=list(dict.fromkeys(lst))"""

#seleziona solo quei numeri dalla lista con frequenza pari a 1
lst=([x[0] for x in cnt.items() if x[1]<2])
        

print()
print("I numeri selezionati col principio M-Log1 sono:",len(lst),".\n\nEssi,ordinati in maniera crescente,sono:\n")

print (lst)

print()

for a1 in lst:
    for a2 in lst:
        for a3 in lst:
            for b1 in lst:
                somme = a1 + a2 + a3
                c1 = somme - a1 - b1
                b2 = somme - a3 - c1
                b3 = somme - b1 - b2
                c2 = somme - a2 - b2
                c3 = somme - c1 - c2
                
                M = CarreMagique([a1,a2,a3, b1,b2,b3, c1,c2,c3])
                
                
                if M.est_magique() and 0 < b2 < 91 and 0 < b3 < 91 and 0 < c1 < 91 and 0 < c2 < 91 and 0 < c3 < 91 and b1 in lst and b2 in lst and b3 in lst and c1 in lst and c2 in lst and c3 in lst:
                    res.append (M)
                    print(M)
                    print([a1,a2,a3,b1,b2,b3,c1,c2,c3])
                             
                    
                    sommasomme= ((a1+a2+a3))
                    media_quadrato=(a1,a2,a3,b1,b2,b3,c1,c2,c3)
                    mediana_quadrato=(a1,a2,a3,b1,b2,b3,c1,c2,c3)
                    devstand=(a1,a2,a3,b1,b2,b3,c1,c2,c3)
                    
                    print('mediana : {:0.2f}'.format(median(mediana_quadrato)))
                    print("la somma eguale è", somme, ' mentre la somma delle somme è:',sommasomme)
                    print('La media dei numeri del quadrato è','{:0.2f}'.format(mean(media_quadrato)))
                    print('La mediana dei numeri del quadrato è','{:0.2f}'.format(mean(mediana_quadrato)))
                    print('La deviazione standard dei numeri del quadrato è','{:0.2f}'.format(np.std(devstand)))
                    medianumeri=('La media dei numeri del quadrato è {:0.2f}.\n'.format(mean(media_quadrato)))
                    sommaquadrato= ('La somma comune è {}.\n'.format(sommasomme))
                    terzine_in_gioco = (a1,a2,a3),(b1,b2,b3),(c1,c2,c3),(a1,b1,c1),(a2,b2,c2),(a3,b3,c3),(a1,b2,c3),(a3,b2,c1)
                    Numeri_da_giocare= ('Le terzine in gioco sono:\n{}.\n'.format(terzine_in_gioco).replace(","," "))
                    print ((Numeri_da_giocare))

                    with open ("testus.txt","a")as file2:
                         
                         file2.write(f'Quadrato magico in gioco\n{str(M)}\n'+ sommaquadrato + medianumeri+ 'La Deviazione standard è pari a: {:0.2f}.\n\n'.format(np.std(devstand)))
                         file2.flush()
                    #pl.plot(devstand,'r')
                    #pl.show()

                    print ("----")
                
                    import functools
                    import itertools
                    import math
                    
                    Lista_numeri_da_combinare = [a1,a2,a3]# la lista potrà ampliarsi a piacere
                    Sviluppo_numeri = itertools.combinations(Lista_numeri_da_combinare,3)
                    for x in Sviluppo_numeri:
                        print (x)

                    print("")

                    
                        
                    
                    """print(M)
                       print('La somma eguale è',somme)
                        print("-----")"""
                    
                #pass
                    if stop_after > 0 and len(res) >= stop_after:
                        return res
                        
                    
return res

```

import time

d = time.perf\_counter()  
res = tous\_les\_carres\_permutation()  
d = time.perf\_counter() - d  
print (“Il numero dei quadrati magici è pari a:”,len(res),“\nIl tempo di elaborazione in secondi è pari a=”,d)

print(“\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*”)

> Blockquote

---

<div class="post-metadata">

**Author:** ![gustaphe](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gustaphe/32/18174_2.png) [@gustaphe](https://discourse.julialang.org/u/gustaphe)\
**Post date:** [September 17, 2022, 8:47am UTC](https://discourse.julialang.org/t/how-to-convert-code-from-python-to-julia-the-magic-squares/87397/2 "2022-09-17T08:47:33Z")

</div>

Welcome to Julia!

[Please read: make it easier to help you](https://discourse.julialang.org/t/please-read-make-it-easier-to-help-you/14757) (especially the part about quoting code)

And do you really want _help_ converting Python code to Julia, or do you want someone to convert this Python code to Julia _for you_? If it’s the former, try to identify what parts you need help with and ask specifically about those. Maybe try and show how it’s going. If it’s the latter, ask a bit more honestly (“Can someone please transpile this for me?”) and be prepared that not many have the time and interest to perform that service for free, so you could be waiting a long time for a response.
