2

I have the following method defined in a py file:

def leerPrimos(ruta):
    inicio = time.clock()
    cuenta = 0
    archOut = 'C:/Users/esteban/Desktop/taller-primos-complejidad-algoritmica/python-files/PYsalida2.out';

    with open(ruta) as fIn:
        with open(archOut,'a') as fOut:
            for linea in fIn:
                if is_prime(int(linea)):
                    fOut.write(linea)
                    print(linea)
    final = time.clock()
    tiemp = final - inicio
    tiempo(tiemp)

then i Call the method:

leerPrimos("C:/Users/esteban/Desktop/taller-primos-complejidad-algoritmica/dataset.in")

The first with open(ruta) works fine, and print(linea) is shown in IDLE console but fOut.write(linea) is not working at all, when the method finishes, there's nothing written in the fOut file.

Am I doing something wrong ? I'm a java developer but was asked to do some homework in python please help. :)

EDIT here's the complete file:

import time

def leerPrimos(ruta):
    inicio = time.clock()
    cuenta = 0
    archOut = 'C:/Users/esteban/Desktop/taller-primos-complejidad-algoritmica/python-files/PYsalida2.out';

    with open(ruta) as fIn:
        with open(archOut,'a+') as fOut:
            for linea in fIn:
                if is_prime(int(linea)):
                    fOut.write(linea)
                    print(linea)
    final = time.clock()
    tiemp = final - inicio
    tiempo(tiemp)


def tiempo(milis):
    seg = (milis / 1000) % 60
    mins = ((milis / (1000 * 60)) % 60)
    horas = ((milis / (1000 * 60 * 60)) % 60)
    t = str(seg) + " segundos, " + str(mins) + " minutos, " + str(horas) + " horas"
    print (t)
    return t

def findPrimes():
    start = time.clock()
    MAX = 10000000
    count = 0
# se hizo el ejercicio con solo 10 000 000  porque toma más de 30 horas en correr
# el algoritmo con 1 000 000 000 
    with open("C:/Users/esteban/Desktop/taller-primos-complejidad-algoritmica/python-files/PYsalida1.out", "a") as myfile:
        for i in range(1,MAX+1):
            if is_prime(i):
                count += 1
                print (str(i) + "\n")
                myfile.write(str(i) + "\n")                
    end = time.clock()        
    print ("Tiempo tomado: " + str((end-start)))    
    print ("Números primos encontrados: " + str(count))



#fuente: https://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test#Python
def _try_composite(a, d, n, s):
    if pow(a, d, n) == 1:
        return False
    for i in range(s):
        if pow(a, 2**i * d, n) == n-1:
            return False
    return True # n  is definitely composite

 #fuente: https://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test#Python
def is_prime(n, _precision_for_huge_n=16):
    if n in _known_primes or n in (0, 1):
        return True
    if any((n % p) == 0 for p in _known_primes):
        return False
    d, s = n - 1, 0
    while not d % 2:
        d, s = d >> 1, s + 1
    # Returns exact according to http://primes.utm.edu/prove/prove2_3.html
    if n < 1373653: 
        return not any(_try_composite(a, d, n, s) for a in (2, 3))
    if n < 25326001: 
        return not any(_try_composite(a, d, n, s) for a in (2, 3, 5))
    if n < 118670087467: 
        if n == 3215031751: 
            return False
        return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7))
    if n < 2152302898747: 
        return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11))
    if n < 3474749660383: 
        return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13))
    if n < 341550071728321: 
        return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13, 17))
    # otherwise
    return not any(_try_composite(a, d, n, s) 
                   for a in _known_primes[:_precision_for_huge_n])

_known_primes = [2, 3]
_known_primes += [x for x in range(5, 1000, 2) if is_prime(x)]

#findPrimes()
leerPrimos("C:/Users/esteban/Desktop/taller-primos-complejidad-algoritmica/dataset.in")
Esteban Rincon
  • 2,040
  • 3
  • 27
  • 44
  • What happens if you use `open(archOut,'a+')` and `fOut.write(linea+'\n')`? – OneCricketeer Feb 29 '16 at 21:00
  • BTW its python version: **3.5.1** – Esteban Rincon Feb 29 '16 at 21:00
  • 3
    Are you sure it's even reaching that line? Perhaps `int(linea)` never `is_prime`... – Two-Bit Alchemist Feb 29 '16 at 21:01
  • @cricket_007, nothing happens with "a+" – Esteban Rincon Feb 29 '16 at 21:01
  • @Two-BitAlchemist, if that were true, nothing would print in the console and this isn't the case. :) – Esteban Rincon Feb 29 '16 at 21:02
  • @Two-BitAlchemist Question says "`print(linea)` is shown in IDLE console" – OneCricketeer Feb 29 '16 at 21:02
  • Please submit the other code so we could investigate the problem deeper. – Gal Ben David Feb 29 '16 at 21:03
  • 1
    @AdamSmith, I'll place the complete `py` file so you can reproduce. – Esteban Rincon Feb 29 '16 at 21:04
  • 1
    @estebanrincon Please provide a sample of your input file as well. I assume it is just line-separated numbers? – OneCricketeer Feb 29 '16 at 21:04
  • @cricket_007, the input file is just the numbers from 1 - 10 million, one number per line – Esteban Rincon Feb 29 '16 at 21:06
  • 2
    Do me a big favor and change `if is_prime(int(linea))` to `if True` and tell me it doesn't write anything to your file. If that's the case, double check your paths. – Two-Bit Alchemist Feb 29 '16 at 21:12
  • OK, so is there some type of behavior in python where the writing takes place differently ? What i was doing was: i run the file and then 5 seconds later i stopped the process just to check that the file is being written to (with no luck after a while, i asked this question) I decided to just run it anyways without interrupting it and to my surprise if i let it finish it does write to the file – Esteban Rincon Feb 29 '16 at 21:17
  • this was done with *java,python,groovy,c* and they all worked with no problem even if i stopped the process – Esteban Rincon Feb 29 '16 at 21:18
  • 2
    Because, when you write to file it's not instantly written to file, but cached internally and flushed into file in batches later. [`file.flush()`](https://docs.python.org/2/library/stdtypes.html?highlight=file%20flush#file.flush) flushes this cache. It is also done on file close. AFAIK it is the same in other languages you mentioned. – Yaroslav Admin Feb 29 '16 at 21:21
  • 2
    @estebanrincon maybe it fails that way if you run it inside IDLE. If you ran it from the desktop the `with` blocks should trigger their `file.flush` even if it's interrupted by Ctrl+C – Adam Smith Feb 29 '16 at 21:23
  • @YaroslavAdmin, i use `BufferedWriter` in the other langs but this doesn't seem to affect the file when i interrupt it, so i don't understand – Esteban Rincon Feb 29 '16 at 21:23
  • @AdamSmith, could be, but i ran the other langs with eclipse and netbeans. – Esteban Rincon Feb 29 '16 at 21:24
  • 1
    @estebanrincon IDLE is an odd bird. I don't think ti's too controversial to say that the vast majority of professional Python programmers would prefer that IDLE wasn't included in Python to begin with. It changes basic interactions in subtle ways because it's basically sandboxing your Python inside a Tkinter app. This might be one of those ways, it's difficult to say (if the Tkinter app dies, it might not gracefully exit its subprocesses) – Adam Smith Feb 29 '16 at 21:26
  • @estebanrincon Though it's the same in [Java](http://stackoverflow.com/q/4040221/1377864). The reason why it was working before may be because you reached the batch limit and it was flushed, but you stopped Python before you reached batch limit. – Yaroslav Admin Feb 29 '16 at 21:27
  • 1
    @estebanrincon if you'll be doing a good deal of Python and are looking for a good REPR, you should check out IPython's Notebook features. I do 90% of my ad-hoc programming there. – Adam Smith Feb 29 '16 at 21:27
  • 1
    @AdamSmith, Thank you ! feel free to make your comments as answers since the "sandboxing" is probably the reason this doesn't work properly – Esteban Rincon Feb 29 '16 at 21:30

0 Answers0