π
<-
Chat plein-écran
[^]

challenge to convert C code to python (prime numbers)

challenge to convert C code to python (prime numbers)

Message non lude compsystems » 27 Nov 2018, 20:54

Hello, a small challenge to convert the following code to python numworks, ti83, hpprime, ...


Code: Tout sélectionner
#include <stdio.h>
int isPrime(int n);

int main()
{
int n, cont, i;   
printf("How many consecutive primes you want to see? ");   
scanf("%d",&n);   
cont=1;   
i=2;
while( cont<=n )   
{
    if( isPrime(i) )       
    { 
        printf("%d\n",i);         
        cont = cont+1;     
    }
    i = i+1;   
}
return 0;
}

int isPrime(int n)
{
    int test_prime=1;
    for( int i=2; i<n && test_prime==1; i++ ){
        if( n%i==0 )       
        {
            test_prime = 0;     
        }
    }
    return test_prime;
}
Avatar de l’utilisateur
compsystems
Niveau 9: IC (Compteur Infatigable)
Niveau 9: IC (Compteur Infatigable)
Prochain niv.: 40.2%
 
Messages: 256
Inscription: 30 Mai 2011, 13:44
Genre: Homme
Calculatrice(s):
MyCalcs profile

Re: challenge to convert C code to python (prime numbers)

Message non lude gam » 27 Nov 2018, 22:05

you want it specially in Python for calculator or in normal Python?
créations: avec chacha: Chacha's pack, Marques(packs Oiram)
seul: Minuteur(utilitaires)
Avatar de l’utilisateur
gamAmbianceur
Niveau 13: CU (Calculateur Universel)
Niveau 13: CU (Calculateur Universel)
Prochain niv.: 12.7%
 
Messages: 166
Inscription: 06 Déc 2017, 11:59
Localisation: Strasbourg
Genre: Homme
Calculatrice(s):
MyCalcs profile
Classe: Bac +2

Re: challenge to convert C code to python (prime numbers)

Message non lude jean-baptiste boric » 27 Nov 2018, 22:37

I don't see what's the "challenge" here. It took me about one minute to make a straightforward conversion to Python:
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Tout sélectionner
def isPrime(n):
    test_prime=1;
    i=2
    while i<n and test_prime==1:
        if n%i==0:
            test_prime = 0
        i+=1
    return test_prime

n = int(input("How many consecutive primes you want to see? "))
cont=1
i=2
while cont<=n:
    if isPrime(i):
        print(i)         
        cont = cont+1
    i = i+1

By the way, that's not what I would call good C code. While keeping the same algorithm, a much cleaner Python version would be:
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Tout sélectionner
def isPrime(n):
  for i in range(2, n):
    if n % i == 0:
      return False
  return True

n = 2
counter = int(input("How many consecutive primes you want to see? "))
while counter > 0:
  if isPrime(n):
    print(n)
    counter -= 1
  n += 1
Avatar de l’utilisateur
jean-baptiste boricPremium
Niveau 10: GR (Guide de Référence)
Niveau 10: GR (Guide de Référence)
Prochain niv.: 4.5%
 
Messages: 374
Inscription: 21 Déc 2015, 22:22
Genre: Non spécifié
Calculatrice(s):
MyCalcs profile
GitHub: boricj

Re: challenge to convert C code to python (prime numbers)

Message non lude Extra44 » 27 Nov 2018, 22:45

My version, a "copy code" from C to python
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Tout sélectionner
def isPrime(n):
    test_prime=1
    for i in range(2,n):
        if n % i == 0:
            test_prime=0
            break
    return test_prime

n=int(input("How many consecutive primes you want to see? "))
cont = 1
i=2
while cont<=n:
    if isPrime(i):
        print(i)
        cont=cont+1
    i=i+1

:)
Avatar de l’utilisateur
Extra44Premium
Niveau 11: LV (Légende Vivante)
Niveau 11: LV (Légende Vivante)
Prochain niv.: 58.4%
 
Messages: 591
Images: 1
Inscription: 20 Jan 2011, 00:00
Genre: Homme
Calculatrice(s):
MyCalcs profile
Classe: S.I.

Re: challenge to convert C code to python (prime numbers)

Message non lude parisse » 28 Nov 2018, 07:08

You don't have to loop until n. In C you should do
Code: Tout sélectionner
for (int i=2;i*i<=n;++i){
  if (n%i==0) return false;
}

Since Python does not have a (IMHO) decent for loop, you must use a while loop in Python to do the same.
Avatar de l’utilisateur
parisseVIP++
Niveau 12: CP (Calculatrice sur Pattes)
Niveau 12: CP (Calculatrice sur Pattes)
Prochain niv.: 77.8%
 
Messages: 3511
Inscription: 13 Déc 2013, 16:35
Genre: Non spécifié
Calculatrice(s):
MyCalcs profile

Re: challenge to convert C code to python (prime numbers)

Message non lude jean-baptiste boric » 28 Nov 2018, 18:35

Well, there's a easy way to achieve this:
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Tout sélectionner
from math import sqrt

def isPrime(n):
  for i in range(2, int(sqrt(n)+1)):
    if n % i == 0:
      return False
  return True

But yes, Python does not offer C-like for loops, but for-each loops instead. Given the emphasis on lambdas and functional programming in Python, it does not really surprise me. I bet hardcore Python programmers can write a one-liner for returning the first n primes using just map(), filter(), reduce(), range() and lambdas...
Avatar de l’utilisateur
jean-baptiste boricPremium
Niveau 10: GR (Guide de Référence)
Niveau 10: GR (Guide de Référence)
Prochain niv.: 4.5%
 
Messages: 374
Inscription: 21 Déc 2015, 22:22
Genre: Non spécifié
Calculatrice(s):
MyCalcs profile
GitHub: boricj

Re: challenge to convert C code to python (prime numbers)

Message non lude Adriweb » 28 Nov 2018, 18:43

Apparently... sum([ True if a%factor == 0 else False for factor in ( [2] + list(range(3,int(math.sqrt(a)),2) )) ])

From https://gist.github.com/cescapa/c655e8e0c1558660150f

https://stackoverflow.com/questions/106 ... n-one-line is also interesting I suppose
Image

MyCalcs: Help the community's calculator documentations by filling out your calculators info!
MyCalcs: Aidez la communauté à documenter les calculatrices en donnant des infos sur vos calculatrices !
Inspired-Lua.org: All about TI-Nspire Lua programming (tutorials, wiki/docs...)
Avatar de l’utilisateur
AdriwebAdmin
Niveau 16: CC2 (Commandeur des Calculatrices)
Niveau 16: CC2 (Commandeur des Calculatrices)
Prochain niv.: 80.2%
 
Messages: 14613
Images: 1218
Inscription: 01 Juin 2007, 00:00
Localisation: France
Genre: Homme
Calculatrice(s):
MyCalcs profile
Twitter/X: adriweb
GitHub: adriweb

Re: challenge to convert C code to python (prime numbers)

Message non lude parisse » 28 Nov 2018, 20:30

@jb boric: But you must compute sqrt(n) with approx computations and use a range. While my C loop does not use approx operations, only basic objects (integers), and basic arithmetic on integers. No lists or complex substitutes to avoid memory usage. And the code is easy to understand and efficient (of course it's not efficient for large integers but more efficient algorithms require more math input).

@adriweb: that style of coding is an horror, unreadable, and it's inefficient (well, I'm not certain you can determine how the Python interpreter does certain things). In other words it's garbage for me.

That's some reasons why I don't like Python, it will encourage using complex data types instead of simple ones and/or implement inefficient algorithms... Of course teaching C at highschool level is not a good idea, but my code would work the same in Javascript (just remove the int data type).
Avatar de l’utilisateur
parisseVIP++
Niveau 12: CP (Calculatrice sur Pattes)
Niveau 12: CP (Calculatrice sur Pattes)
Prochain niv.: 77.8%
 
Messages: 3511
Inscription: 13 Déc 2013, 16:35
Genre: Non spécifié
Calculatrice(s):
MyCalcs profile

Re: challenge to convert C code to python (prime numbers)

Message non lude Adriweb » 29 Nov 2018, 01:52

parisse a écrit:@adriweb: that style of coding is an horror, unreadable, and it's inefficient (well, I'm not certain you can determine how the Python interpreter does certain things). In other words it's garbage for me.

That's some reasons why I don't like Python

Yes, I have the same opinion actually (except maybe for the efficiency part, where python implementations probably perform just as fast as the normal way of writing that algorithm, I guess...)
Image

MyCalcs: Help the community's calculator documentations by filling out your calculators info!
MyCalcs: Aidez la communauté à documenter les calculatrices en donnant des infos sur vos calculatrices !
Inspired-Lua.org: All about TI-Nspire Lua programming (tutorials, wiki/docs...)
Avatar de l’utilisateur
AdriwebAdmin
Niveau 16: CC2 (Commandeur des Calculatrices)
Niveau 16: CC2 (Commandeur des Calculatrices)
Prochain niv.: 80.2%
 
Messages: 14613
Images: 1218
Inscription: 01 Juin 2007, 00:00
Localisation: France
Genre: Homme
Calculatrice(s):
MyCalcs profile
Twitter/X: adriweb
GitHub: adriweb

Re: challenge to convert C code to python (prime numbers)

Message non lude blouson » 29 Nov 2018, 04:41

c'est pas pour faire mon fayot , mais ce genre de code est beaucoup moins clair et compréhensible qu'algobox , franchement je plains les élèves de seconde qui vont devoir se coltiner ce genre de code , ou alors faut déjà être ingénieur en informatique , je sais pas ..
Avatar de l’utilisateur
blouson
Niveau 2: MI2 (Membre Initié)
Niveau 2: MI2 (Membre Initié)
Prochain niv.: 66.7%
 
Messages: 135
Inscription: 16 Fév 2018, 05:37
Genre: Non spécifié
Calculatrice(s):
MyCalcs profile

Suivante

Retourner vers Problèmes divers / Aide débutants

Qui est en ligne

Utilisateurs parcourant ce forum: Aucun utilisateur enregistré et 7 invités

-
Rechercher
-
Social TI-Planet
-
Sujets à la une
Comparaisons des meilleurs prix pour acheter sa calculatrice !
Aidez la communauté à documenter les révisions matérielles en listant vos calculatrices graphiques !
Phi NumWorks jailbreak
123
-
Faire un don / Premium
Pour plus de concours, de lots, de tests, nous aider à payer le serveur et les domaines...
Faire un don
Découvrez les avantages d'un compte donateur !
JoinRejoignez the donors and/or premium!les donateurs et/ou premium !


Partenaires et pub
Notre partenaire Jarrety Calculatrices à acheter chez Calcuso
-
Stats.
1335 utilisateurs:
>1297 invités
>33 membres
>5 robots
Record simultané (sur 6 mois):
6892 utilisateurs (le 07/06/2017)
-
Autres sites intéressants
Texas Instruments Education
Global | France
 (English / Français)
Banque de programmes TI
ticalc.org
 (English)
La communauté TI-82
tout82.free.fr
 (Français)